Use the indirect way to the actual request tracker, so that people
[openssl.git] / ssl / kssl.c
1 /* ssl/kssl.c -*- mode: C; c-file-style: "eay" -*- */
2 /* Written by Vern Staats <staatsvr@asc.hpc.mil> for the OpenSSL project 2000.
3  */
4 /* ====================================================================
5  * Copyright (c) 2000 The OpenSSL Project.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer. 
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. All advertising materials mentioning features or use of this
20  *    software must display the following acknowledgment:
21  *    "This product includes software developed by the OpenSSL Project
22  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
23  *
24  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
25  *    endorse or promote products derived from this software without
26  *    prior written permission. For written permission, please contact
27  *    licensing@OpenSSL.org.
28  *
29  * 5. Products derived from this software may not be called "OpenSSL"
30  *    nor may "OpenSSL" appear in their names without prior written
31  *    permission of the OpenSSL Project.
32  *
33  * 6. Redistributions of any form whatsoever must retain the following
34  *    acknowledgment:
35  *    "This product includes software developed by the OpenSSL Project
36  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
39  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
41  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
42  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
44  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
45  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
47  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
49  * OF THE POSSIBILITY OF SUCH DAMAGE.
50  * ====================================================================
51  *
52  * This product includes cryptographic software written by Eric Young
53  * (eay@cryptsoft.com).  This product includes software written by Tim
54  * Hudson (tjh@cryptsoft.com).
55  *
56  */
57
58
59 /*  ssl/kssl.c  --  Routines to support (& debug) Kerberos5 auth for openssl
60 **
61 **  19990701    VRS     Started.
62 **  200011??    Jeffrey Altman, Richard Levitte
63 **                      Generalized for Heimdal, Newer MIT, & Win32.
64 **                      Integrated into main OpenSSL 0.9.7 snapshots.
65 **  20010413    Simon Wilkinson, VRS
66 **                      Real RFC2712 KerberosWrapper replaces AP_REQ.
67 */
68
69 #include <openssl/opensslconf.h>
70
71 #define _XOPEN_SOURCE /* glibc2 needs this to declare strptime() */
72 #include <time.h>
73 #include <string.h>
74
75 #include <openssl/ssl.h>
76 #include <openssl/evp.h>
77 #include <openssl/objects.h>
78 #include <openssl/krb5_asn.h>
79
80 #ifndef OPENSSL_NO_KRB5
81
82 /* 
83  * When OpenSSL is built on Windows, we do not want to require that
84  * the Kerberos DLLs be available in order for the OpenSSL DLLs to
85  * work.  Therefore, all Kerberos routines are loaded at run time
86  * and we do not link to a .LIB file.
87  */
88
89 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
90 /* 
91  * The purpose of the following pre-processor statements is to provide
92  * compatibility with different releases of MIT Kerberos for Windows.
93  * All versions up to 1.2 used macros.  But macros do not allow for
94  * a binary compatible interface for DLLs.  Therefore, all macros are
95  * being replaced by function calls.  The following code will allow
96  * an OpenSSL DLL built on Windows to work whether or not the macro
97  * or function form of the routines are utilized.
98  */
99 #ifdef  krb5_cc_get_principal
100 #define NO_DEF_KRB5_CCACHE
101 #undef  krb5_cc_get_principal
102 #endif
103 #define krb5_cc_get_principal    kssl_krb5_cc_get_principal
104
105 #define krb5_free_data_contents  kssl_krb5_free_data_contents   
106 #define krb5_free_context        kssl_krb5_free_context         
107 #define krb5_auth_con_free       kssl_krb5_auth_con_free        
108 #define krb5_free_principal      kssl_krb5_free_principal       
109 #define krb5_mk_req_extended     kssl_krb5_mk_req_extended      
110 #define krb5_get_credentials     kssl_krb5_get_credentials      
111 #define krb5_cc_default          kssl_krb5_cc_default           
112 #define krb5_sname_to_principal  kssl_krb5_sname_to_principal   
113 #define krb5_init_context        kssl_krb5_init_context         
114 #define krb5_free_ticket         kssl_krb5_free_ticket          
115 #define krb5_rd_req              kssl_krb5_rd_req               
116 #define krb5_kt_default          kssl_krb5_kt_default           
117 #define krb5_kt_resolve          kssl_krb5_kt_resolve           
118 /* macros in mit 1.2.2 and earlier; functions in mit 1.2.3 and greater */
119 #ifndef krb5_kt_close
120 #define krb5_kt_close            kssl_krb5_kt_close
121 #endif /* krb5_kt_close */
122 #ifndef krb5_kt_get_entry
123 #define krb5_kt_get_entry        kssl_krb5_kt_get_entry
124 #endif /* krb5_kt_get_entry */
125 #define krb5_auth_con_init       kssl_krb5_auth_con_init        
126
127 #define krb5_principal_compare   kssl_krb5_principal_compare
128 #define krb5_decrypt_tkt_part    kssl_krb5_decrypt_tkt_part
129 #define krb5_timeofday           kssl_krb5_timeofday
130 #define krb5_rc_default           kssl_krb5_rc_default
131
132 #ifdef krb5_rc_initialize
133 #undef krb5_rc_initialize
134 #endif
135 #define krb5_rc_initialize   kssl_krb5_rc_initialize
136
137 #ifdef krb5_rc_get_lifespan
138 #undef krb5_rc_get_lifespan
139 #endif
140 #define krb5_rc_get_lifespan kssl_krb5_rc_get_lifespan
141
142 #ifdef krb5_rc_destroy
143 #undef krb5_rc_destroy
144 #endif
145 #define krb5_rc_destroy      kssl_krb5_rc_destroy
146
147 #define valid_cksumtype      kssl_valid_cksumtype
148 #define krb5_checksum_size   kssl_krb5_checksum_size
149 #define krb5_kt_free_entry   kssl_krb5_kt_free_entry
150 #define krb5_auth_con_setrcache  kssl_krb5_auth_con_setrcache
151 #define krb5_auth_con_getrcache  kssl_krb5_auth_con_getrcache
152 #define krb5_get_server_rcache   kssl_krb5_get_server_rcache
153
154 /* Prototypes for built in stubs */
155 void kssl_krb5_free_data_contents(krb5_context, krb5_data *);
156 void kssl_krb5_free_principal(krb5_context, krb5_principal );
157 krb5_error_code kssl_krb5_kt_resolve(krb5_context,
158                                      krb5_const char *,
159                                      krb5_keytab *);
160 krb5_error_code kssl_krb5_kt_default(krb5_context,
161                                      krb5_keytab *);
162 krb5_error_code kssl_krb5_free_ticket(krb5_context, krb5_ticket *);
163 krb5_error_code kssl_krb5_rd_req(krb5_context, krb5_auth_context *, 
164                                  krb5_const krb5_data *,
165                                  krb5_const_principal, krb5_keytab, 
166                                  krb5_flags *,krb5_ticket **);
167
168 krb5_boolean kssl_krb5_principal_compare(krb5_context, krb5_const_principal,
169                                          krb5_const_principal);
170 krb5_error_code kssl_krb5_mk_req_extended(krb5_context,
171                                           krb5_auth_context  *,
172                                           krb5_const krb5_flags,
173                                           krb5_data  *,
174                                           krb5_creds  *,
175                                           krb5_data  * );
176 krb5_error_code kssl_krb5_init_context(krb5_context *);
177 void kssl_krb5_free_context(krb5_context);
178 krb5_error_code kssl_krb5_cc_default(krb5_context,krb5_ccache  *);
179 krb5_error_code kssl_krb5_sname_to_principal(krb5_context,
180                                              krb5_const char  *,
181                                              krb5_const char  *,
182                                              krb5_int32,
183                                              krb5_principal  *);
184 krb5_error_code kssl_krb5_get_credentials(krb5_context,
185                                           krb5_const krb5_flags,
186                                           krb5_ccache,
187                                           krb5_creds  *,
188                                           krb5_creds  *  *);
189 krb5_error_code kssl_krb5_auth_con_init(krb5_context,
190                                         krb5_auth_context  *);
191 krb5_error_code kssl_krb5_cc_get_principal(krb5_context context, 
192                                            krb5_ccache cache,
193                                            krb5_principal *principal);
194 krb5_error_code kssl_krb5_auth_con_free(krb5_context,krb5_auth_context);
195 size_t kssl_krb5_checksum_size(krb5_context context,krb5_cksumtype ctype);
196 krb5_boolean kssl_valid_cksumtype(krb5_cksumtype ctype);
197 krb5_error_code krb5_kt_free_entry(krb5_context,krb5_keytab_entry FAR * );
198 krb5_error_code kssl_krb5_auth_con_setrcache(krb5_context, 
199                                              krb5_auth_context, 
200                                              krb5_rcache);
201 krb5_error_code kssl_krb5_get_server_rcache(krb5_context, 
202                                             krb5_const krb5_data *,
203                                             krb5_rcache *);
204 krb5_error_code kssl_krb5_auth_con_getrcache(krb5_context, 
205                                              krb5_auth_context,
206                                              krb5_rcache *);
207
208 /* Function pointers (almost all Kerberos functions are _stdcall) */
209 static void (_stdcall *p_krb5_free_data_contents)(krb5_context, krb5_data *)
210         =NULL;
211 static void (_stdcall *p_krb5_free_principal)(krb5_context, krb5_principal )
212         =NULL;
213 static krb5_error_code(_stdcall *p_krb5_kt_resolve)
214                         (krb5_context, krb5_const char *, krb5_keytab *)=NULL;
215 static krb5_error_code (_stdcall *p_krb5_kt_default)(krb5_context,
216                                                      krb5_keytab *)=NULL;
217 static krb5_error_code (_stdcall *p_krb5_free_ticket)(krb5_context, 
218                                                       krb5_ticket *)=NULL;
219 static krb5_error_code (_stdcall *p_krb5_rd_req)(krb5_context, 
220                                                  krb5_auth_context *, 
221                                                  krb5_const krb5_data *,
222                                                  krb5_const_principal, 
223                                                  krb5_keytab, krb5_flags *,
224                                                  krb5_ticket **)=NULL;
225 static krb5_error_code (_stdcall *p_krb5_mk_req_extended)
226                         (krb5_context, krb5_auth_context *,
227                          krb5_const krb5_flags, krb5_data *, krb5_creds *,
228                          krb5_data * )=NULL;
229 static krb5_error_code (_stdcall *p_krb5_init_context)(krb5_context *)=NULL;
230 static void (_stdcall *p_krb5_free_context)(krb5_context)=NULL;
231 static krb5_error_code (_stdcall *p_krb5_cc_default)(krb5_context,
232                                                      krb5_ccache  *)=NULL;
233 static krb5_error_code (_stdcall *p_krb5_sname_to_principal)
234                         (krb5_context, krb5_const char *, krb5_const char *,
235                          krb5_int32, krb5_principal *)=NULL;
236 static krb5_error_code (_stdcall *p_krb5_get_credentials)
237                         (krb5_context, krb5_const krb5_flags, krb5_ccache,
238                          krb5_creds *, krb5_creds **)=NULL;
239 static krb5_error_code (_stdcall *p_krb5_auth_con_init)
240                         (krb5_context, krb5_auth_context *)=NULL;
241 static krb5_error_code (_stdcall *p_krb5_cc_get_principal)
242                         (krb5_context context, krb5_ccache cache,
243                          krb5_principal *principal)=NULL;
244 static krb5_error_code (_stdcall *p_krb5_auth_con_free)
245                         (krb5_context, krb5_auth_context)=NULL;
246 static krb5_error_code (_stdcall *p_krb5_decrypt_tkt_part)
247                         (krb5_context, krb5_const krb5_keyblock *,
248                                            krb5_ticket *)=NULL;
249 static krb5_error_code (_stdcall *p_krb5_timeofday)
250                         (krb5_context context, krb5_int32 *timeret)=NULL;
251 static krb5_error_code (_stdcall *p_krb5_rc_default)
252                         (krb5_context context, krb5_rcache *rc)=NULL;
253 static krb5_error_code (_stdcall *p_krb5_rc_initialize)
254                         (krb5_context context, krb5_rcache rc,
255                                      krb5_deltat lifespan)=NULL;
256 static krb5_error_code (_stdcall *p_krb5_rc_get_lifespan)
257                         (krb5_context context, krb5_rcache rc,
258                                        krb5_deltat *lifespan)=NULL;
259 static krb5_error_code (_stdcall *p_krb5_rc_destroy)
260                         (krb5_context context, krb5_rcache rc)=NULL;
261 static krb5_boolean (_stdcall *p_krb5_principal_compare)
262                      (krb5_context, krb5_const_principal, krb5_const_principal)=NULL;
263 static size_t (_stdcall *p_krb5_checksum_size)(krb5_context context,krb5_cksumtype ctype)=NULL;
264 static krb5_boolean (_stdcall *p_valid_cksumtype)(krb5_cksumtype ctype)=NULL;
265 static krb5_error_code (_stdcall *p_krb5_kt_free_entry)
266                         (krb5_context,krb5_keytab_entry * )=NULL;
267 static krb5_error_code (_stdcall * p_krb5_auth_con_setrcache)(krb5_context, 
268                                                                krb5_auth_context, 
269                                                                krb5_rcache)=NULL;
270 static krb5_error_code (_stdcall * p_krb5_get_server_rcache)(krb5_context, 
271                                                               krb5_const krb5_data *, 
272                                                               krb5_rcache *)=NULL;
273 static krb5_error_code (* p_krb5_auth_con_getrcache)(krb5_context, 
274                                                       krb5_auth_context,
275                                                       krb5_rcache *)=NULL;
276 static krb5_error_code (_stdcall * p_krb5_kt_close)(krb5_context context, 
277                                                     krb5_keytab keytab)=NULL;
278 static krb5_error_code (_stdcall * p_krb5_kt_get_entry)(krb5_context context, 
279                                                         krb5_keytab keytab,
280                        krb5_const_principal principal, krb5_kvno vno,
281                        krb5_enctype enctype, krb5_keytab_entry *entry)=NULL;
282 static int krb5_loaded = 0;     /* only attempt to initialize func ptrs once */
283
284 /* Function to Load the Kerberos 5 DLL and initialize function pointers */
285 void
286 load_krb5_dll(void)
287         {
288         HANDLE hKRB5_32;
289     
290         krb5_loaded++;
291         hKRB5_32 = LoadLibrary("KRB5_32");
292         if (!hKRB5_32)
293                 return;
294
295         (FARPROC) p_krb5_free_data_contents =
296                 GetProcAddress( hKRB5_32, "krb5_free_data_contents" );
297         (FARPROC) p_krb5_free_context =
298                 GetProcAddress( hKRB5_32, "krb5_free_context" );
299         (FARPROC) p_krb5_auth_con_free =
300                 GetProcAddress( hKRB5_32, "krb5_auth_con_free" );
301         (FARPROC) p_krb5_free_principal =
302                 GetProcAddress( hKRB5_32, "krb5_free_principal" );
303         (FARPROC) p_krb5_mk_req_extended =
304                 GetProcAddress( hKRB5_32, "krb5_mk_req_extended" );
305         (FARPROC) p_krb5_get_credentials =
306                 GetProcAddress( hKRB5_32, "krb5_get_credentials" );
307         (FARPROC) p_krb5_cc_get_principal =
308                 GetProcAddress( hKRB5_32, "krb5_cc_get_principal" );
309         (FARPROC) p_krb5_cc_default =
310                 GetProcAddress( hKRB5_32, "krb5_cc_default" );
311         (FARPROC) p_krb5_sname_to_principal =
312                 GetProcAddress( hKRB5_32, "krb5_sname_to_principal" );
313         (FARPROC) p_krb5_init_context =
314                 GetProcAddress( hKRB5_32, "krb5_init_context" );
315         (FARPROC) p_krb5_free_ticket =
316                 GetProcAddress( hKRB5_32, "krb5_free_ticket" );
317         (FARPROC) p_krb5_rd_req =
318                 GetProcAddress( hKRB5_32, "krb5_rd_req" );
319         (FARPROC) p_krb5_principal_compare =
320                 GetProcAddress( hKRB5_32, "krb5_principal_compare" );
321         (FARPROC) p_krb5_decrypt_tkt_part =
322                 GetProcAddress( hKRB5_32, "krb5_decrypt_tkt_part" );
323         (FARPROC) p_krb5_timeofday =
324                 GetProcAddress( hKRB5_32, "krb5_timeofday" );
325         (FARPROC) p_krb5_rc_default =
326                 GetProcAddress( hKRB5_32, "krb5_rc_default" );
327         (FARPROC) p_krb5_rc_initialize =
328                 GetProcAddress( hKRB5_32, "krb5_rc_initialize" );
329         (FARPROC) p_krb5_rc_get_lifespan =
330                 GetProcAddress( hKRB5_32, "krb5_rc_get_lifespan" );
331         (FARPROC) p_krb5_rc_destroy =
332                 GetProcAddress( hKRB5_32, "krb5_rc_destroy" );
333         (FARPROC) p_krb5_kt_default =
334                 GetProcAddress( hKRB5_32, "krb5_kt_default" );
335         (FARPROC) p_krb5_kt_resolve =
336                 GetProcAddress( hKRB5_32, "krb5_kt_resolve" );
337         (FARPROC) p_krb5_auth_con_init =
338                 GetProcAddress( hKRB5_32, "krb5_auth_con_init" );
339         (FARPROC) p_valid_cksumtype =
340                 GetProcAddress( hKRB5_32, "valid_cksumtype" );
341         (FARPROC) p_krb5_checksum_size =
342                 GetProcAddress( hKRB5_32, "krb5_checksum_size" );
343         (FARPROC) p_krb5_kt_free_entry =
344                 GetProcAddress( hKRB5_32, "krb5_kt_free_entry" );
345         (FARPROC) p_krb5_auth_con_setrcache =
346                 GetProcAddress( hKRB5_32, "krb5_auth_con_setrcache" );
347         (FARPROC) p_krb5_get_server_rcache =
348                 GetProcAddress( hKRB5_32, "krb5_get_server_rcache" );
349         (FARPROC) p_krb5_auth_con_getrcache =
350                 GetProcAddress( hKRB5_32, "krb5_auth_con_getrcache" );
351         (FARPROC) p_krb5_kt_close =
352                 GetProcAddress( hKRB5_32, "krb5_kt_close" );
353         (FARPROC) p_krb5_kt_get_entry =
354                 GetProcAddress( hKRB5_32, "krb5_kt_get_entry" );
355         }
356
357 /* Stubs for each function to be dynamicly loaded */
358 void
359 kssl_krb5_free_data_contents(krb5_context CO, krb5_data  * data)
360         {
361         if (!krb5_loaded)
362                 load_krb5_dll();
363
364         if ( p_krb5_free_data_contents )
365                 p_krb5_free_data_contents(CO,data);
366         }
367
368 krb5_error_code
369 kssl_krb5_mk_req_extended (krb5_context CO,
370                           krb5_auth_context  * pACO,
371                           krb5_const krb5_flags F,
372                           krb5_data  * pD1,
373                           krb5_creds  * pC,
374                           krb5_data  * pD2)
375         {
376         if (!krb5_loaded)
377                 load_krb5_dll();
378
379         if ( p_krb5_mk_req_extended )
380                 return(p_krb5_mk_req_extended(CO,pACO,F,pD1,pC,pD2));
381         else
382                 return KRB5KRB_ERR_GENERIC;
383         }
384 krb5_error_code
385 kssl_krb5_auth_con_init(krb5_context CO,
386                        krb5_auth_context  * pACO)
387         {
388         if (!krb5_loaded)
389                 load_krb5_dll();
390
391         if ( p_krb5_auth_con_init )
392                 return(p_krb5_auth_con_init(CO,pACO));
393         else
394                 return KRB5KRB_ERR_GENERIC;
395         }
396 krb5_error_code
397 kssl_krb5_auth_con_free (krb5_context CO,
398                         krb5_auth_context ACO)
399         {
400         if (!krb5_loaded)
401                 load_krb5_dll();
402
403         if ( p_krb5_auth_con_free )
404                 return(p_krb5_auth_con_free(CO,ACO));
405         else
406                 return KRB5KRB_ERR_GENERIC;
407         }
408 krb5_error_code
409 kssl_krb5_get_credentials(krb5_context CO,
410                          krb5_const krb5_flags F,
411                          krb5_ccache CC,
412                          krb5_creds  * pCR,
413                          krb5_creds  ** ppCR)
414         {
415         if (!krb5_loaded)
416                 load_krb5_dll();
417
418         if ( p_krb5_get_credentials )
419                 return(p_krb5_get_credentials(CO,F,CC,pCR,ppCR));
420         else
421                 return KRB5KRB_ERR_GENERIC;
422         }
423 krb5_error_code
424 kssl_krb5_sname_to_principal(krb5_context CO,
425                             krb5_const char  * pC1,
426                             krb5_const char  * pC2,
427                             krb5_int32 I,
428                             krb5_principal  * pPR)
429         {
430         if (!krb5_loaded)
431                 load_krb5_dll();
432
433         if ( p_krb5_sname_to_principal )
434                 return(p_krb5_sname_to_principal(CO,pC1,pC2,I,pPR));
435         else
436                 return KRB5KRB_ERR_GENERIC;
437         }
438
439 krb5_error_code
440 kssl_krb5_cc_default(krb5_context CO,
441                     krb5_ccache  * pCC)
442         {
443         if (!krb5_loaded)
444                 load_krb5_dll();
445
446         if ( p_krb5_cc_default )
447                 return(p_krb5_cc_default(CO,pCC));
448         else
449                 return KRB5KRB_ERR_GENERIC;
450         }
451
452 krb5_error_code
453 kssl_krb5_init_context(krb5_context * pCO)
454         {
455         if (!krb5_loaded)
456                 load_krb5_dll();
457
458         if ( p_krb5_init_context )
459                 return(p_krb5_init_context(pCO));
460         else
461                 return KRB5KRB_ERR_GENERIC;
462         }
463
464 void
465 kssl_krb5_free_context(krb5_context CO)
466         {
467         if (!krb5_loaded)
468                 load_krb5_dll();
469
470         if ( p_krb5_free_context )
471                 p_krb5_free_context(CO);
472         }
473
474 void
475 kssl_krb5_free_principal(krb5_context c, krb5_principal p)
476         {
477         if (!krb5_loaded)
478                 load_krb5_dll();
479
480         if ( p_krb5_free_principal )
481                 p_krb5_free_principal(c,p);
482         }
483
484 krb5_error_code
485 kssl_krb5_kt_resolve(krb5_context con,
486                     krb5_const char * sz,
487                     krb5_keytab * kt)
488         {
489         if (!krb5_loaded)
490                 load_krb5_dll();
491
492         if ( p_krb5_kt_resolve )
493                 return(p_krb5_kt_resolve(con,sz,kt));
494         else
495                 return KRB5KRB_ERR_GENERIC;
496         }
497
498 krb5_error_code
499 kssl_krb5_kt_default(krb5_context con,
500                     krb5_keytab * kt)
501         {
502         if (!krb5_loaded)
503                 load_krb5_dll();
504
505         if ( p_krb5_kt_default )
506                 return(p_krb5_kt_default(con,kt));
507         else
508                 return KRB5KRB_ERR_GENERIC;
509         }
510
511 krb5_error_code
512 kssl_krb5_free_ticket(krb5_context con,
513                      krb5_ticket * kt)
514         {
515         if (!krb5_loaded)
516                 load_krb5_dll();
517
518         if ( p_krb5_free_ticket )
519                 return(p_krb5_free_ticket(con,kt));
520         else
521                 return KRB5KRB_ERR_GENERIC;
522         }
523
524 krb5_error_code
525 kssl_krb5_rd_req(krb5_context con, krb5_auth_context * pacon,
526                 krb5_const krb5_data * data,
527                 krb5_const_principal princ, krb5_keytab keytab,
528                 krb5_flags * flags, krb5_ticket ** pptkt)
529         {
530         if (!krb5_loaded)
531                 load_krb5_dll();
532
533         if ( p_krb5_rd_req )
534                 return(p_krb5_rd_req(con,pacon,data,princ,keytab,flags,pptkt));
535         else
536                 return KRB5KRB_ERR_GENERIC;
537         }
538
539 krb5_boolean
540 krb5_principal_compare(krb5_context con, krb5_const_principal princ1,
541                 krb5_const_principal princ2)
542         {
543         if (!krb5_loaded)
544                 load_krb5_dll();
545
546         if ( p_krb5_principal_compare )
547                 return(p_krb5_principal_compare(con,princ1,princ2));
548         else
549                 return KRB5KRB_ERR_GENERIC;
550         }
551
552 krb5_error_code
553 krb5_decrypt_tkt_part(krb5_context con, krb5_const krb5_keyblock *keys,
554                 krb5_ticket *ticket)
555         {
556         if (!krb5_loaded)
557                 load_krb5_dll();
558
559         if ( p_krb5_decrypt_tkt_part )
560                 return(p_krb5_decrypt_tkt_part(con,keys,ticket));
561         else
562                 return KRB5KRB_ERR_GENERIC;
563         }
564
565 krb5_error_code
566 krb5_timeofday(krb5_context con, krb5_int32 *timeret)
567         {
568         if (!krb5_loaded)
569                 load_krb5_dll();
570
571         if ( p_krb5_timeofday )
572                 return(p_krb5_timeofday(con,timeret));
573         else
574                 return KRB5KRB_ERR_GENERIC;
575         }
576
577 krb5_error_code
578 krb5_rc_default(krb5_context con, krb5_rcache *rc)
579         {
580         if (!krb5_loaded)
581                 load_krb5_dll();
582
583         if ( p_krb5_rc_default )
584                 return(p_krb5_rc_default(con,rc));
585         else
586                 return KRB5KRB_ERR_GENERIC;
587         }
588
589 krb5_error_code
590 krb5_rc_initialize(krb5_context con, krb5_rcache rc, krb5_deltat lifespan)
591         {
592         if (!krb5_loaded)
593                 load_krb5_dll();
594
595         if ( p_krb5_rc_initialize )
596                 return(p_krb5_rc_initialize(con, rc, lifespan));
597         else
598                 return KRB5KRB_ERR_GENERIC;
599         }
600
601 krb5_error_code
602 krb5_rc_get_lifespan(krb5_context con, krb5_rcache rc, krb5_deltat *lifespanp)
603         {
604         if (!krb5_loaded)
605                 load_krb5_dll();
606
607         if ( p_krb5_rc_get_lifespan )
608                 return(p_krb5_rc_get_lifespan(con, rc, lifespanp));
609         else
610                 return KRB5KRB_ERR_GENERIC;
611         }
612
613 krb5_error_code
614 krb5_rc_destroy(krb5_context con, krb5_rcache rc)
615         {
616         if (!krb5_loaded)
617                 load_krb5_dll();
618
619         if ( p_krb5_rc_destroy )
620                 return(p_krb5_rc_destroy(con, rc));
621         else
622                 return KRB5KRB_ERR_GENERIC;
623         }
624
625 size_t 
626 krb5_checksum_size(krb5_context context,krb5_cksumtype ctype)
627         {
628         if (!krb5_loaded)
629                 load_krb5_dll();
630
631         if ( p_krb5_checksum_size )
632                 return(p_krb5_checksum_size(context, ctype));
633         else
634                 return KRB5KRB_ERR_GENERIC;
635         }
636
637 krb5_boolean 
638 valid_cksumtype(krb5_cksumtype ctype)
639         {
640         if (!krb5_loaded)
641                 load_krb5_dll();
642
643         if ( p_valid_cksumtype )
644                 return(p_valid_cksumtype(ctype));
645         else
646                 return KRB5KRB_ERR_GENERIC;
647         }
648
649 krb5_error_code 
650 krb5_kt_free_entry(krb5_context con,krb5_keytab_entry * entry)
651         {
652         if (!krb5_loaded)
653                 load_krb5_dll();
654
655         if ( p_krb5_kt_free_entry )
656                 return(p_krb5_kt_free_entry(con,entry));
657         else
658                 return KRB5KRB_ERR_GENERIC;
659         }
660                  
661 /* Structure definitions  */
662 #ifndef NO_DEF_KRB5_CCACHE
663 #ifndef krb5_x
664 #define krb5_x(ptr,args) ((ptr)?((*(ptr)) args):(abort(),1))
665 #define krb5_xc(ptr,args) ((ptr)?((*(ptr)) args):(abort(),(char*)0))
666 #endif 
667
668 typedef krb5_pointer    krb5_cc_cursor; /* cursor for sequential lookup */
669
670 typedef struct _krb5_ccache
671         {
672         krb5_magic magic;
673         struct _krb5_cc_ops FAR *ops;
674         krb5_pointer data;
675         } *krb5_ccache;
676
677 typedef struct _krb5_cc_ops
678         {
679         krb5_magic magic;
680         char  *prefix;
681         char  * (KRB5_CALLCONV *get_name)
682                 (krb5_context, krb5_ccache);
683         krb5_error_code (KRB5_CALLCONV *resolve)
684                 (krb5_context, krb5_ccache  *, const char  *);
685         krb5_error_code (KRB5_CALLCONV *gen_new)
686                 (krb5_context, krb5_ccache  *);
687         krb5_error_code (KRB5_CALLCONV *init)
688                 (krb5_context, krb5_ccache, krb5_principal);
689         krb5_error_code (KRB5_CALLCONV *destroy)
690                 (krb5_context, krb5_ccache);
691         krb5_error_code (KRB5_CALLCONV *close)
692                 (krb5_context, krb5_ccache);
693         krb5_error_code (KRB5_CALLCONV *store)
694                 (krb5_context, krb5_ccache, krb5_creds  *);
695         krb5_error_code (KRB5_CALLCONV *retrieve)
696                 (krb5_context, krb5_ccache,
697                 krb5_flags, krb5_creds  *, krb5_creds  *);
698         krb5_error_code (KRB5_CALLCONV *get_princ)
699                 (krb5_context, krb5_ccache, krb5_principal  *);
700         krb5_error_code (KRB5_CALLCONV *get_first)
701                 (krb5_context, krb5_ccache, krb5_cc_cursor  *);
702         krb5_error_code (KRB5_CALLCONV *get_next)
703                 (krb5_context, krb5_ccache,
704                 krb5_cc_cursor  *, krb5_creds  *);
705         krb5_error_code (KRB5_CALLCONV *end_get)
706                 (krb5_context, krb5_ccache, krb5_cc_cursor  *);
707         krb5_error_code (KRB5_CALLCONV *remove_cred)
708                 (krb5_context, krb5_ccache,
709                 krb5_flags, krb5_creds  *);
710         krb5_error_code (KRB5_CALLCONV *set_flags)
711                 (krb5_context, krb5_ccache, krb5_flags);
712         } krb5_cc_ops;
713 #endif /* NO_DEF_KRB5_CCACHE */
714
715 krb5_error_code 
716 kssl_krb5_cc_get_principal
717     (krb5_context context, krb5_ccache cache,
718       krb5_principal *principal)
719         {
720         if ( p_krb5_cc_get_principal )
721                 return(p_krb5_cc_get_principal(context,cache,principal));
722         else
723                 return(krb5_x
724                         ((cache)->ops->get_princ,(context, cache, principal)));
725         }
726
727 krb5_error_code
728 kssl_krb5_auth_con_setrcache(krb5_context con, krb5_auth_context acon,
729                              krb5_rcache rcache)
730         {
731         if ( p_krb5_auth_con_setrcache )
732                  return(p_krb5_auth_con_setrcache(con,acon,rcache));
733         else
734                  return KRB5KRB_ERR_GENERIC;
735         }
736
737 krb5_error_code
738 kssl_krb5_get_server_rcache(krb5_context con, krb5_const krb5_data * data,
739                             krb5_rcache * rcache) 
740         {
741         if ( p_krb5_get_server_rcache )
742                 return(p_krb5_get_server_rcache(con,data,rcache));
743         else
744                 return KRB5KRB_ERR_GENERIC;
745         }
746
747 krb5_error_code
748 kssl_krb5_auth_con_getrcache(krb5_context con, krb5_auth_context acon,
749                              krb5_rcache * prcache)
750         {
751         if ( p_krb5_auth_con_getrcache )
752                 return(p_krb5_auth_con_getrcache(con,acon, prcache));
753         else
754                 return KRB5KRB_ERR_GENERIC;
755         }
756  
757 krb5_error_code
758 kssl_krb5_kt_close(krb5_context context, krb5_keytab keytab)
759         {
760         if ( p_krb5_kt_close )
761                 return(p_krb5_kt_close(context,keytab));
762         else 
763                 return KRB5KRB_ERR_GENERIC;
764         }
765
766 krb5_error_code
767 kssl_krb5_kt_get_entry(krb5_context context, krb5_keytab keytab,
768                        krb5_const_principal principal, krb5_kvno vno,
769                        krb5_enctype enctype, krb5_keytab_entry *entry)
770         {
771         if ( p_krb5_kt_get_entry )
772                 return(p_krb5_kt_get_entry(context,keytab,principal,vno,enctype,entry));
773         else
774                 return KRB5KRB_ERR_GENERIC;
775         }
776 #endif  /* OPENSSL_SYS_WINDOWS || OPENSSL_SYS_WIN32 */
777
778 char
779 *kstring(char *string)
780         {
781         static char     *null = "[NULL]";
782
783         return ((string == NULL)? null: string);
784         }
785
786 #define MAXKNUM 255
787 char
788 *knumber(int len, krb5_octet *contents)
789         {
790         static char     buf[MAXKNUM+1];
791         int             i;
792
793         BIO_snprintf(buf, MAXKNUM, "[%d] ", len);
794
795         for (i=0; i < len  &&  MAXKNUM > strlen(buf)+3; i++)
796                 {
797                 BIO_snprintf(&buf[strlen(buf)], 3, "%02x", contents[i]);
798                 }
799
800         return (buf);
801         }
802
803
804 /*      Given KRB5 enctype (basically DES or 3DES),
805 **      return closest match openssl EVP_ encryption algorithm.
806 **      Return NULL for unknown or problematic (krb5_dk_encrypt) enctypes.
807 **      Assume ENCTYPE_*_RAW (krb5_raw_encrypt) are OK.
808 */
809 const EVP_CIPHER *
810 kssl_map_enc(krb5_enctype enctype)
811         {
812         switch (enctype)
813                 {
814         case ENCTYPE_DES_HMAC_SHA1:             /*    EVP_des_cbc();       */
815         case ENCTYPE_DES_CBC_CRC:
816         case ENCTYPE_DES_CBC_MD4:
817         case ENCTYPE_DES_CBC_MD5:
818         case ENCTYPE_DES_CBC_RAW:
819                                 return EVP_des_cbc();
820                                 break;
821         case ENCTYPE_DES3_CBC_SHA1:             /*    EVP_des_ede3_cbc();  */
822         case ENCTYPE_DES3_CBC_SHA:
823         case ENCTYPE_DES3_CBC_RAW:
824                                 return EVP_des_ede3_cbc();
825                                 break;
826         default:                return NULL;
827                                 break;
828                 }
829         }
830
831
832 /*      Return true:1 if p "looks like" the start of the real authenticator
833 **      described in kssl_skip_confound() below.  The ASN.1 pattern is
834 **      "62 xx 30 yy" (APPLICATION-2, SEQUENCE), where xx-yy =~ 2, and
835 **      xx and yy are possibly multi-byte length fields.
836 */
837 int     kssl_test_confound(unsigned char *p)
838         {
839         int     len = 2;
840         int     xx = 0, yy = 0;
841
842         if (*p++ != 0x62)  return 0;
843         if (*p > 0x82)  return 0;
844         switch(*p)  {
845                 case 0x82:  p++;          xx = (*p++ << 8);  xx += *p++;  break;
846                 case 0x81:  p++;          xx =  *p++;  break;
847                 case 0x80:  return 0;
848                 default:    xx = *p++;  break;
849                 }
850         if (*p++ != 0x30)  return 0;
851         if (*p > 0x82)  return 0;
852         switch(*p)  {
853                 case 0x82:  p++; len+=2;  yy = (*p++ << 8);  yy += *p++;  break;
854                 case 0x81:  p++; len++;   yy =  *p++;  break;
855                 case 0x80:  return 0;
856                 default:    yy = *p++;  break;
857                 }
858
859         return (xx - len == yy)? 1: 0;
860         }
861
862 /*      Allocate, fill, and return cksumlens array of checksum lengths.
863 **      This array holds just the unique elements from the krb5_cksumarray[].
864 **      array[n] == 0 signals end of data.
865 **
866 **      The krb5_cksumarray[] was an internal variable that has since been
867 **      replaced by a more general method for storing the data.  It should
868 **      not be used.  Instead we use real API calls and make a guess for 
869 **      what the highest assigned CKSUMTYPE_ constant is.  As of 1.2.2
870 **      it is 0x000c (CKSUMTYPE_HMAC_SHA1_DES3).  So we will use 0x0010.
871 */
872 size_t  *populate_cksumlens(void)
873         {
874         int             i, j, n;
875         static size_t   *cklens = NULL;
876
877 #ifdef KRB5_MIT_OLD11
878         n = krb5_max_cksum;
879 #else
880         n = 0x0010;
881 #endif  /* KRB5_MIT_OLD11 */
882  
883 #ifdef KRB5CHECKAUTH
884         if (!cklens && !(cklens = (size_t *) calloc(sizeof(int),n+1)))  return NULL;
885
886         for (i=0; i < n; i++)  {
887                 if (!valid_cksumtype(i))  continue;     /*  array has holes  */
888                 for (j=0; j < n; j++)  {
889                         if (cklens[j] == 0)  {
890                                 cklens[j] = krb5_checksum_size(NULL,i);
891                                 break;          /*  krb5 elem was new: add   */
892                                 }
893                         if (cklens[j] == krb5_checksum_size(NULL,i))  {
894                                 break;          /*  ignore duplicate elements */
895                                 }
896                         }
897                 }
898 #endif  /* KRB5CHECKAUTH */
899
900         return cklens;
901         }
902
903 /*      Return pointer to start of real authenticator within authenticator, or
904 **      return NULL on error.
905 **      Decrypted authenticator looks like this:
906 **              [0 or 8 byte confounder] [4-24 byte checksum] [real authent'r]
907 **      This hackery wouldn't be necessary if MIT KRB5 1.0.6 had the
908 **      krb5_auth_con_getcksumtype() function advertised in its krb5.h.
909 */
910 unsigned char   *kssl_skip_confound(krb5_enctype etype, unsigned char *a)
911         {
912         int             i, conlen;
913         size_t          cklen;
914         static size_t   *cksumlens = NULL;
915         unsigned char   *test_auth;
916
917         conlen = (etype)? 8: 0;
918
919         if (!cksumlens  &&  !(cksumlens = populate_cksumlens()))  return NULL;
920         for (i=0; (cklen = cksumlens[i]) != 0; i++)
921                 {
922                 test_auth = a + conlen + cklen;
923                 if (kssl_test_confound(test_auth))  return test_auth;
924                 }
925
926         return NULL;
927         }
928
929
930 /*      Set kssl_err error info when reason text is a simple string
931 **              kssl_err = struct { int reason; char text[KSSL_ERR_MAX+1]; }
932 */
933 void
934 kssl_err_set(KSSL_ERR *kssl_err, int reason, char *text)
935         {
936         if (kssl_err == NULL)  return;
937
938         kssl_err->reason = reason;
939         BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, text);
940         return;
941         }
942
943
944 /*      Display contents of krb5_data struct, for debugging
945 */
946 void
947 print_krb5_data(char *label, krb5_data *kdata)
948         {
949         int i;
950
951         printf("%s[%d] ", label, kdata->length);
952         for (i=0; i < kdata->length; i++)
953                 {
954                 if (0 &&  isprint((int) kdata->data[i]))
955                         printf( "%c ",  kdata->data[i]);
956                 else
957                         printf( "%02x ", (unsigned char) kdata->data[i]);
958                 }
959         printf("\n");
960         }
961
962
963 /*      Display contents of krb5_authdata struct, for debugging
964 */
965 void
966 print_krb5_authdata(char *label, krb5_authdata **adata)
967         {
968         if (adata == NULL)
969                 {
970                 printf("%s, authdata==0\n", label);
971                 return;
972                 }
973         printf("%s [%p]\n", label, adata);
974 #if 0
975         {
976         int     i;
977         printf("%s[at%d:%d] ", label, adata->ad_type, adata->length);
978         for (i=0; i < adata->length; i++)
979                 {
980                 printf((isprint(adata->contents[i]))? "%c ": "%02x",
981                         adata->contents[i]);
982                 }
983         printf("\n");
984         }
985 #endif
986         }
987
988
989 /*      Display contents of krb5_keyblock struct, for debugging
990 */
991 void
992 print_krb5_keyblock(char *label, krb5_keyblock *keyblk)
993         {
994         int i;
995
996         if (keyblk == NULL)
997                 {
998                 printf("%s, keyblk==0\n", label);
999                 return;
1000                 }
1001 #ifdef KRB5_HEIMDAL
1002         printf("%s\n\t[et%d:%d]: ", label, keyblk->keytype,
1003                                            keyblk->keyvalue->length);
1004         for (i=0; i < keyblk->keyvalue->length; i++)
1005                 {
1006                 printf("%02x",(unsigned char *)(keyblk->keyvalue->contents)[i]);
1007                 }
1008         printf("\n");
1009 #else
1010         printf("%s\n\t[et%d:%d]: ", label, keyblk->enctype, keyblk->length);
1011         for (i=0; i < keyblk->length; i++)
1012                 {
1013                 printf("%02x",keyblk->contents[i]);
1014                 }
1015         printf("\n");
1016 #endif
1017         }
1018
1019
1020 /*      Display contents of krb5_principal_data struct, for debugging
1021 **      (krb5_principal is typedef'd == krb5_principal_data *)
1022 */
1023 void
1024 print_krb5_princ(char *label, krb5_principal_data *princ)
1025         {
1026         int i, ui, uj;
1027
1028         printf("%s principal Realm: ", label);
1029         if (princ == NULL)  return;
1030         for (ui=0; ui < princ->realm.length; ui++)  putchar(princ->realm.data[ui]);
1031         printf(" (nametype %d) has %d strings:\n", princ->type,princ->length);
1032         for (i=0; i < princ->length; i++)
1033                 {
1034                 printf("\t%d [%d]: ", i, princ->data[i].length);
1035                 for (uj=0; uj < princ->data[i].length; uj++)  {
1036                         putchar(princ->data[i].data[uj]);
1037                         }
1038                 printf("\n");
1039                 }
1040         return;
1041         }
1042
1043
1044 /*      Given krb5 service (typically "kssl") and hostname in kssl_ctx,
1045 **      Return encrypted Kerberos ticket for service @ hostname.
1046 **      If authenp is non-NULL, also return encrypted authenticator,
1047 **      whose data should be freed by caller.
1048 **      (Originally was: Create Kerberos AP_REQ message for SSL Client.)
1049 **
1050 **      19990628        VRS     Started; Returns Kerberos AP_REQ message.
1051 **      20010409        VRS     Modified for RFC2712; Returns enc tkt.
1052 **      20010606        VRS     May also return optional authenticator.
1053 */
1054 krb5_error_code
1055 kssl_cget_tkt(  /* UPDATE */    KSSL_CTX *kssl_ctx,
1056                 /* OUT    */    krb5_data **enc_ticketp,
1057                 /* UPDATE */    krb5_data *authenp,
1058                 /* OUT    */    KSSL_ERR *kssl_err)
1059         {
1060         krb5_error_code         krb5rc = KRB5KRB_ERR_GENERIC;
1061         krb5_context            krb5context = NULL;
1062         krb5_auth_context       krb5auth_context = NULL;
1063         krb5_ccache             krb5ccdef = NULL;
1064         krb5_creds              krb5creds, *krb5credsp = NULL;
1065         krb5_data               krb5_app_req;
1066
1067         kssl_err_set(kssl_err, 0, "");
1068         memset((char *)&krb5creds, 0, sizeof(krb5creds));
1069
1070         if (!kssl_ctx)
1071                 {
1072                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1073                         "No kssl_ctx defined.\n");
1074                 goto err;
1075                 }
1076         else if (!kssl_ctx->service_host)
1077                 {
1078                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1079                         "kssl_ctx service_host undefined.\n");
1080                 goto err;
1081                 }
1082
1083         if ((krb5rc = krb5_init_context(&krb5context)) != 0)
1084                 {
1085                 BIO_snprintf(kssl_err->text,KSSL_ERR_MAX,
1086                         "krb5_init_context() fails: %d\n", krb5rc);
1087                 kssl_err->reason = SSL_R_KRB5_C_INIT;
1088                 goto err;
1089                 }
1090
1091         if ((krb5rc = krb5_sname_to_principal(krb5context,
1092                 kssl_ctx->service_host,
1093                 (kssl_ctx->service_name)? kssl_ctx->service_name: KRB5SVC,
1094                 KRB5_NT_SRV_HST, &krb5creds.server)) != 0)
1095                 {
1096                 BIO_snprintf(kssl_err->text,KSSL_ERR_MAX,
1097                         "krb5_sname_to_principal() fails for %s/%s\n",
1098                         kssl_ctx->service_host,
1099                         (kssl_ctx->service_name)? kssl_ctx->service_name:
1100                                                   KRB5SVC);
1101                 kssl_err->reason = SSL_R_KRB5_C_INIT;
1102                 goto err;
1103                 }
1104
1105         if ((krb5rc = krb5_cc_default(krb5context, &krb5ccdef)) != 0)
1106                 {
1107                 kssl_err_set(kssl_err, SSL_R_KRB5_C_CC_PRINC,
1108                         "krb5_cc_default fails.\n");
1109                 goto err;
1110                 }
1111
1112         if ((krb5rc = krb5_cc_get_principal(krb5context, krb5ccdef,
1113                 &krb5creds.client)) != 0)
1114                 {
1115                 kssl_err_set(kssl_err, SSL_R_KRB5_C_CC_PRINC,
1116                         "krb5_cc_get_principal() fails.\n");
1117                 goto err;
1118                 }
1119
1120         if ((krb5rc = krb5_get_credentials(krb5context, 0, krb5ccdef,
1121                 &krb5creds, &krb5credsp)) != 0)
1122                 {
1123                 kssl_err_set(kssl_err, SSL_R_KRB5_C_GET_CRED,
1124                         "krb5_get_credentials() fails.\n");
1125                 goto err;
1126                 }
1127
1128         *enc_ticketp = &krb5credsp->ticket;
1129 #ifdef KRB5_HEIMDAL
1130         kssl_ctx->enctype = krb5credsp->session.keytype;
1131 #else
1132         kssl_ctx->enctype = krb5credsp->keyblock.enctype;
1133 #endif
1134
1135         krb5rc = KRB5KRB_ERR_GENERIC;
1136         /*      caller should free data of krb5_app_req  */
1137         /*  20010406 VRS deleted for real KerberosWrapper
1138         **  20010605 VRS reinstated to offer Authenticator to KerberosWrapper
1139         */
1140         krb5_app_req.length = 0;
1141         if (authenp)
1142                 {
1143                 krb5_data       krb5in_data;
1144                 unsigned char   *p;
1145                 long            arlen;
1146                 KRB5_APREQBODY  *ap_req;
1147
1148                 authenp->length = 0;
1149                 krb5in_data.data = NULL;
1150                 krb5in_data.length = 0;
1151                 if ((krb5rc = krb5_mk_req_extended(krb5context,
1152                         &krb5auth_context, 0, &krb5in_data, krb5credsp,
1153                         &krb5_app_req)) != 0)
1154                         {
1155                         kssl_err_set(kssl_err, SSL_R_KRB5_C_MK_REQ,
1156                                 "krb5_mk_req_extended() fails.\n");
1157                         goto err;
1158                         }
1159
1160                 arlen = krb5_app_req.length;
1161                 p = (unsigned char *)krb5_app_req.data;
1162                 ap_req = (KRB5_APREQBODY *) d2i_KRB5_APREQ(NULL, &p, arlen);
1163                 if (ap_req)
1164                         {
1165                         authenp->length = i2d_KRB5_ENCDATA(
1166                                         ap_req->authenticator, NULL);
1167                         if (authenp->length  && 
1168                                 (authenp->data = malloc(authenp->length)))
1169                                 {
1170                                 unsigned char   *adp = (unsigned char *)authenp->data;
1171                                 authenp->length = i2d_KRB5_ENCDATA(
1172                                                 ap_req->authenticator, &adp);
1173                                 }
1174                         }
1175
1176                 if (ap_req)  KRB5_APREQ_free((KRB5_APREQ *) ap_req);
1177                 if (krb5_app_req.length)  
1178                         kssl_krb5_free_data_contents(krb5context,&krb5_app_req);
1179                 }
1180 #ifdef KRB5_HEIMDAL
1181         if (kssl_ctx_setkey(kssl_ctx, &krb5credsp->session))
1182                 {
1183                 kssl_err_set(kssl_err, SSL_R_KRB5_C_INIT,
1184                         "kssl_ctx_setkey() fails.\n");
1185                 }
1186 #else
1187         if (kssl_ctx_setkey(kssl_ctx, &krb5credsp->keyblock))
1188                 {
1189                 kssl_err_set(kssl_err, SSL_R_KRB5_C_INIT,
1190                         "kssl_ctx_setkey() fails.\n");
1191                 }
1192 #endif
1193         else    krb5rc = 0;
1194
1195  err:
1196 #ifdef KSSL_DEBUG
1197         kssl_ctx_show(kssl_ctx);
1198 #endif  /* KSSL_DEBUG */
1199
1200         if (krb5creds.client)   krb5_free_principal(krb5context,
1201                                                         krb5creds.client);
1202         if (krb5creds.server)   krb5_free_principal(krb5context,
1203                                                         krb5creds.server);
1204         if (krb5auth_context)   krb5_auth_con_free(krb5context,
1205                                                         krb5auth_context);
1206         if (krb5context)        krb5_free_context(krb5context);
1207         return (krb5rc);
1208         }
1209
1210
1211 /*  Given d2i_-decoded asn1ticket, allocate and return a new krb5_ticket.
1212 **  Return Kerberos error code and kssl_err struct on error.
1213 **  Allocates krb5_ticket and krb5_principal; caller should free these.
1214 **
1215 **      20010410        VRS     Implemented krb5_decode_ticket() as
1216 **                              old_krb5_decode_ticket(). Missing from MIT1.0.6.
1217 **      20010615        VRS     Re-cast as openssl/asn1 d2i_*() functions.
1218 **                              Re-used some of the old krb5_decode_ticket()
1219 **                              code here.  This tkt should alloc/free just
1220 **                              like the real thing.
1221 */
1222 krb5_error_code
1223 kssl_TKT2tkt(   /* IN     */    krb5_context    krb5context,
1224                 /* IN     */    KRB5_TKTBODY    *asn1ticket,
1225                 /* OUT    */    krb5_ticket     **krb5ticket,
1226                 /* OUT    */    KSSL_ERR *kssl_err  )
1227         {
1228         krb5_error_code                 krb5rc = KRB5KRB_ERR_GENERIC;
1229         krb5_ticket                     *new5ticket = NULL;
1230         ASN1_GENERALSTRING              *gstr_svc, *gstr_host;
1231
1232         *krb5ticket = NULL;
1233
1234         if (asn1ticket == NULL  ||  asn1ticket->realm == NULL  ||
1235                 asn1ticket->sname == NULL  || 
1236                 sk_ASN1_GENERALSTRING_num(asn1ticket->sname->namestring) < 2)
1237                 {
1238                 BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
1239                         "Null field in asn1ticket.\n");
1240                 kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
1241                 return KRB5KRB_ERR_GENERIC;
1242                 }
1243
1244         if ((new5ticket = (krb5_ticket *) calloc(1, sizeof(krb5_ticket)))==NULL)
1245                 {
1246                 BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
1247                         "Unable to allocate new krb5_ticket.\n");
1248                 kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
1249                 return ENOMEM;          /*  or  KRB5KRB_ERR_GENERIC;    */
1250                 }
1251
1252         gstr_svc  = sk_ASN1_GENERALSTRING_value(asn1ticket->sname->namestring, 0);
1253         gstr_host = sk_ASN1_GENERALSTRING_value(asn1ticket->sname->namestring, 1);
1254
1255         if ((krb5rc = kssl_build_principal_2(krb5context,
1256                         &new5ticket->server,
1257                         asn1ticket->realm->length, (char *)asn1ticket->realm->data,
1258                         gstr_svc->length,  (char *)gstr_svc->data,
1259                         gstr_host->length, (char *)gstr_host->data)) != 0)
1260                 {
1261                 free(new5ticket);
1262                 BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
1263                         "Error building ticket server principal.\n");
1264                 kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
1265                 return krb5rc;          /*  or  KRB5KRB_ERR_GENERIC;    */
1266                 }
1267
1268         krb5_princ_type(krb5context, new5ticket->server) =
1269                         asn1ticket->sname->nametype->data[0];
1270         new5ticket->enc_part.enctype = asn1ticket->encdata->etype->data[0];
1271         new5ticket->enc_part.kvno = asn1ticket->encdata->kvno->data[0];
1272         new5ticket->enc_part.ciphertext.length =
1273                         asn1ticket->encdata->cipher->length;
1274         if ((new5ticket->enc_part.ciphertext.data =
1275                 calloc(1, asn1ticket->encdata->cipher->length)) == NULL)
1276                 {
1277                 free(new5ticket);
1278                 BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
1279                         "Error allocating cipher in krb5ticket.\n");
1280                 kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
1281                 return KRB5KRB_ERR_GENERIC;
1282                 }
1283         else
1284                 {
1285                 memcpy(new5ticket->enc_part.ciphertext.data,
1286                         asn1ticket->encdata->cipher->data,
1287                         asn1ticket->encdata->cipher->length);
1288                 }
1289
1290         *krb5ticket = new5ticket;
1291         return 0;
1292         }
1293
1294
1295 /*      Given krb5 service name in KSSL_CTX *kssl_ctx (typically "kssl"),
1296 **              and krb5 AP_REQ message & message length,
1297 **      Return Kerberos session key and client principle
1298 **              to SSL Server in KSSL_CTX *kssl_ctx.
1299 **
1300 **      19990702        VRS     Started.
1301 */
1302 krb5_error_code
1303 kssl_sget_tkt(  /* UPDATE */    KSSL_CTX                *kssl_ctx,
1304                 /* IN     */    krb5_data               *indata,
1305                 /* OUT    */    krb5_ticket_times       *ttimes,
1306                 /* OUT    */    KSSL_ERR                *kssl_err  )
1307         {
1308         krb5_error_code                 krb5rc = KRB5KRB_ERR_GENERIC;
1309         static krb5_context             krb5context = NULL;
1310         static krb5_auth_context        krb5auth_context = NULL;
1311         krb5_ticket                     *krb5ticket = NULL;
1312         KRB5_TKTBODY                    *asn1ticket = NULL;
1313         unsigned char                   *p;
1314         krb5_keytab                     krb5keytab = NULL;
1315         krb5_keytab_entry               kt_entry;
1316         krb5_principal                  krb5server;
1317         krb5_rcache                     rcache = NULL;
1318
1319         kssl_err_set(kssl_err, 0, "");
1320
1321         if (!kssl_ctx)
1322                 {
1323                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1324                         "No kssl_ctx defined.\n");
1325                 goto err;
1326                 }
1327
1328 #ifdef KSSL_DEBUG
1329         printf("in kssl_sget_tkt(%s)\n", kstring(kssl_ctx->service_name));
1330 #endif  /* KSSL_DEBUG */
1331
1332         if (!krb5context  &&  (krb5rc = krb5_init_context(&krb5context)))
1333                 {
1334                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1335                         "krb5_init_context() fails.\n");
1336                 goto err;
1337                 }
1338         if (krb5auth_context  &&
1339                 (krb5rc = krb5_auth_con_free(krb5context, krb5auth_context)))
1340                 {
1341                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1342                         "krb5_auth_con_free() fails.\n");
1343                 goto err;
1344                 }
1345         else  krb5auth_context = NULL;
1346         if (!krb5auth_context  &&
1347                 (krb5rc = krb5_auth_con_init(krb5context, &krb5auth_context)))
1348                 {
1349                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1350                         "krb5_auth_con_init() fails.\n");
1351                 goto err;
1352                 }
1353
1354  
1355         if ((krb5rc = krb5_auth_con_getrcache(krb5context, krb5auth_context,
1356                 &rcache)))
1357                 {
1358                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1359                         "krb5_auth_con_getrcache() fails.\n");
1360                 goto err;
1361                 }
1362  
1363         if ((krb5rc = krb5_sname_to_principal(krb5context, NULL,
1364                 (kssl_ctx->service_name)? kssl_ctx->service_name: KRB5SVC,
1365                 KRB5_NT_SRV_HST, &krb5server)) != 0)
1366                 {
1367                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1368                         "krb5_sname_to_principal() fails.\n");
1369                 goto err;
1370                 }
1371
1372         if (rcache == NULL) 
1373                 {
1374                 if ((krb5rc = krb5_get_server_rcache(krb5context,
1375                         krb5_princ_component(krb5context, krb5server, 0),
1376                         &rcache)))
1377                         {
1378                         kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1379                                 "krb5_get_server_rcache() fails.\n");
1380                         goto err;
1381                         }
1382                 }
1383
1384         if ((krb5rc = krb5_auth_con_setrcache(krb5context, krb5auth_context, rcache)))
1385                 {
1386                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1387                         "krb5_auth_con_setrcache() fails.\n");
1388                 goto err;
1389                 }
1390
1391
1392         /*      kssl_ctx->keytab_file == NULL ==> use Kerberos default
1393         */
1394         if (kssl_ctx->keytab_file)
1395                 {
1396                 krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file,
1397                         &krb5keytab);
1398                 if (krb5rc)
1399                         {
1400                         kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
1401                                 "krb5_kt_resolve() fails.\n");
1402                         goto err;
1403                         }
1404                 }
1405         else
1406                 {
1407                 krb5rc = krb5_kt_default(krb5context,&krb5keytab);
1408                 if (krb5rc)
1409                         {
1410                         kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, 
1411                                 "krb5_kt_default() fails.\n");
1412                         goto err;
1413                         }
1414                 }
1415
1416         /*      Actual Kerberos5 krb5_recvauth() has initial conversation here
1417         **      o       check KRB5_SENDAUTH_BADAUTHVERS
1418         **              unless KRB5_RECVAUTH_SKIP_VERSION
1419         **      o       check KRB5_SENDAUTH_BADAPPLVERS
1420         **      o       send "0" msg if all OK
1421         */
1422
1423         /*  20010411 was using AP_REQ instead of true KerberosWrapper
1424         **
1425         **  if ((krb5rc = krb5_rd_req(krb5context, &krb5auth_context,
1426         **                      &krb5in_data, krb5server, krb5keytab,
1427         **                      &ap_option, &krb5ticket)) != 0)  { Error }
1428         */
1429
1430         p = (unsigned char *)indata->data;
1431         if ((asn1ticket = (KRB5_TKTBODY *) d2i_KRB5_TICKET(NULL, &p,
1432                                                 (long) indata->length)) == NULL)
1433                 {
1434                 BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
1435                         "d2i_KRB5_TICKET() ASN.1 decode failure.\n");
1436                 kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
1437                 goto err;
1438                 }
1439         
1440         /* Was:  krb5rc = krb5_decode_ticket(krb5in_data,&krb5ticket)) != 0) */
1441         if ((krb5rc = kssl_TKT2tkt(krb5context, asn1ticket, &krb5ticket,
1442                                         kssl_err)) != 0)
1443                 {
1444                 BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
1445                         "Error converting ASN.1 ticket to krb5_ticket.\n");
1446                 kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
1447                 goto err;
1448                 }
1449
1450         if (! krb5_principal_compare(krb5context, krb5server,
1451                                                   krb5ticket->server))  {
1452                 krb5rc = KRB5_PRINC_NOMATCH;
1453                 BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
1454                         "server principal != ticket principal\n");
1455                 kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
1456                 goto err;
1457                 }
1458         if ((krb5rc = krb5_kt_get_entry(krb5context, krb5keytab,
1459                         krb5ticket->server, krb5ticket->enc_part.kvno,
1460                         krb5ticket->enc_part.enctype, &kt_entry)) != 0)  {
1461                 BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
1462                         "krb5_kt_get_entry() fails with %x.\n", krb5rc);
1463                 kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
1464                 goto err;
1465                 }
1466         if ((krb5rc = krb5_decrypt_tkt_part(krb5context, &kt_entry.key,
1467                         krb5ticket)) != 0)  {
1468                 BIO_snprintf(kssl_err->text, KSSL_ERR_MAX,
1469                         "krb5_decrypt_tkt_part() failed.\n");
1470                 kssl_err->reason = SSL_R_KRB5_S_RD_REQ;
1471                 goto err;
1472                 }
1473         else  {
1474                 krb5_kt_free_entry(krb5context, &kt_entry);
1475 #ifdef KSSL_DEBUG
1476                 {
1477                 int i; krb5_address **paddr = krb5ticket->enc_part2->caddrs;
1478                 printf("Decrypted ticket fields:\n");
1479                 printf("\tflags: %X, transit-type: %X",
1480                         krb5ticket->enc_part2->flags,
1481                         krb5ticket->enc_part2->transited.tr_type);
1482                 print_krb5_data("\ttransit-data: ",
1483                         &(krb5ticket->enc_part2->transited.tr_contents));
1484                 printf("\tcaddrs: %p, authdata: %p\n",
1485                         krb5ticket->enc_part2->caddrs,
1486                         krb5ticket->enc_part2->authorization_data);
1487                 if (paddr)
1488                         {
1489                         printf("\tcaddrs:\n");
1490                         for (i=0; paddr[i] != NULL; i++)
1491                                 {
1492                                 krb5_data d;
1493                                 d.length=paddr[i]->length;
1494                                 d.data=paddr[i]->contents;
1495                                 print_krb5_data("\t\tIP: ", &d);
1496                                 }
1497                         }
1498                 printf("\tstart/auth/end times: %d / %d / %d\n",
1499                         krb5ticket->enc_part2->times.starttime,
1500                         krb5ticket->enc_part2->times.authtime,
1501                         krb5ticket->enc_part2->times.endtime);
1502                 }
1503 #endif  /* KSSL_DEBUG */
1504                 }
1505
1506         krb5rc = KRB5_NO_TKT_SUPPLIED;
1507         if (!krb5ticket  ||     !krb5ticket->enc_part2  ||
1508                 !krb5ticket->enc_part2->client  ||
1509                 !krb5ticket->enc_part2->client->data  ||
1510                 !krb5ticket->enc_part2->session)
1511                 {
1512                 kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET,
1513                         "bad ticket from krb5_rd_req.\n");
1514                 }
1515         else if (kssl_ctx_setprinc(kssl_ctx, KSSL_CLIENT,
1516                 &krb5ticket->enc_part2->client->realm,
1517                 krb5ticket->enc_part2->client->data))
1518                 {
1519                 kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET,
1520                         "kssl_ctx_setprinc() fails.\n");
1521                 }
1522         else if (kssl_ctx_setkey(kssl_ctx, krb5ticket->enc_part2->session))
1523                 {
1524                 kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET,
1525                         "kssl_ctx_setkey() fails.\n");
1526                 }
1527         else if (krb5ticket->enc_part2->flags & TKT_FLG_INVALID)
1528                 {
1529                 krb5rc = KRB5KRB_AP_ERR_TKT_INVALID;
1530                 kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET,
1531                         "invalid ticket from krb5_rd_req.\n");
1532                 }
1533         else    krb5rc = 0;
1534
1535         kssl_ctx->enctype       = krb5ticket->enc_part.enctype;
1536         ttimes->authtime        = krb5ticket->enc_part2->times.authtime;
1537         ttimes->starttime       = krb5ticket->enc_part2->times.starttime;
1538         ttimes->endtime         = krb5ticket->enc_part2->times.endtime;
1539         ttimes->renew_till      = krb5ticket->enc_part2->times.renew_till;
1540
1541  err:
1542 #ifdef KSSL_DEBUG
1543         kssl_ctx_show(kssl_ctx);
1544 #endif  /* KSSL_DEBUG */
1545
1546         if (asn1ticket)         KRB5_TICKET_free((KRB5_TICKET *) asn1ticket);
1547         if (krb5keytab)         krb5_kt_close(krb5context, krb5keytab);
1548         if (krb5ticket)         krb5_free_ticket(krb5context, krb5ticket);
1549         if (krb5server)         krb5_free_principal(krb5context, krb5server);
1550         return (krb5rc);
1551         }
1552
1553
1554 /*      Allocate & return a new kssl_ctx struct.
1555 */
1556 KSSL_CTX        *
1557 kssl_ctx_new(void)
1558         {
1559         return ((KSSL_CTX *) calloc(1, sizeof(KSSL_CTX)));
1560         }
1561
1562
1563 /*      Frees a kssl_ctx struct and any allocated memory it holds.
1564 **      Returns NULL.
1565 */
1566 KSSL_CTX        *
1567 kssl_ctx_free(KSSL_CTX *kssl_ctx)
1568         {
1569         if (kssl_ctx == NULL)  return kssl_ctx;
1570
1571         if (kssl_ctx->key)              memset(kssl_ctx->key, 0,
1572                                                               kssl_ctx->length);
1573         if (kssl_ctx->key)              free(kssl_ctx->key);
1574         if (kssl_ctx->client_princ)     free(kssl_ctx->client_princ);
1575         if (kssl_ctx->service_host)     free(kssl_ctx->service_host);
1576         if (kssl_ctx->service_name)     free(kssl_ctx->service_name);
1577         if (kssl_ctx->keytab_file)      free(kssl_ctx->keytab_file);
1578
1579         free(kssl_ctx);
1580         return (KSSL_CTX *) NULL;
1581         }
1582
1583
1584 /*      Given a (krb5_data *) entity (and optional realm),
1585 **      set the plain (char *) client_princ or service_host member
1586 **      of the kssl_ctx struct.
1587 */
1588 krb5_error_code
1589 kssl_ctx_setprinc(KSSL_CTX *kssl_ctx, int which,
1590         krb5_data *realm, krb5_data *entity)
1591         {
1592         char    **princ;
1593         int     length;
1594
1595         if (kssl_ctx == NULL  ||  entity == NULL)  return KSSL_CTX_ERR;
1596
1597         switch (which)
1598                 {
1599         case KSSL_CLIENT:       princ = &kssl_ctx->client_princ;        break;
1600         case KSSL_SERVER:       princ = &kssl_ctx->service_host;        break;
1601         default:                return KSSL_CTX_ERR;                    break;
1602                 }
1603         if (*princ)  free(*princ);
1604
1605         length = entity->length + ((realm)? realm->length + 2: 1);
1606         if ((*princ = calloc(1, length)) == NULL)
1607                 return KSSL_CTX_ERR;
1608         else
1609                 {
1610                 strncpy(*princ, entity->data, entity->length);
1611                 (*princ)[entity->length]='\0';
1612                 if (realm)
1613                         {
1614                         strcat (*princ, "@");
1615                         (void) strncat(*princ, realm->data, realm->length);
1616                         (*princ)[entity->length+1+realm->length]='\0';
1617                         }
1618                 }
1619
1620         return KSSL_CTX_OK;
1621         }
1622
1623
1624 /*      Set one of the plain (char *) string members of the kssl_ctx struct.
1625 **      Default values should be:
1626 **              which == KSSL_SERVICE   =>      "khost" (KRB5SVC)
1627 **              which == KSSL_KEYTAB    =>      "/etc/krb5.keytab" (KRB5KEYTAB)
1628 */
1629 krb5_error_code
1630 kssl_ctx_setstring(KSSL_CTX *kssl_ctx, int which, char *text)
1631         {
1632         char    **string;
1633
1634         if (!kssl_ctx)  return KSSL_CTX_ERR;
1635
1636         switch (which)
1637                 {
1638         case KSSL_SERVICE:      string = &kssl_ctx->service_name;       break;
1639         case KSSL_SERVER:       string = &kssl_ctx->service_host;       break;
1640         case KSSL_CLIENT:       string = &kssl_ctx->client_princ;       break;
1641         case KSSL_KEYTAB:       string = &kssl_ctx->keytab_file;        break;
1642         default:                return KSSL_CTX_ERR;                    break;
1643                 }
1644         if (*string)  free(*string);
1645
1646         if (!text)
1647                 {
1648                 *string = '\0';
1649                 return KSSL_CTX_OK;
1650                 }
1651
1652         if ((*string = calloc(1, strlen(text) + 1)) == NULL)
1653                 return KSSL_CTX_ERR;
1654         else
1655                 strcpy(*string, text);
1656
1657         return KSSL_CTX_OK;
1658         }
1659
1660
1661 /*      Copy the Kerberos session key from a (krb5_keyblock *) to a kssl_ctx
1662 **      struct.  Clear kssl_ctx->key if Kerberos session key is NULL.
1663 */
1664 krb5_error_code
1665 kssl_ctx_setkey(KSSL_CTX *kssl_ctx, krb5_keyblock *session)
1666         {
1667         int             length;
1668         krb5_enctype    enctype;
1669         krb5_octet FAR  *contents = NULL;
1670
1671         if (!kssl_ctx)  return KSSL_CTX_ERR;
1672
1673         if (kssl_ctx->key)
1674                 {
1675                 memset(kssl_ctx->key, 0, kssl_ctx->length);
1676                 free(kssl_ctx->key);
1677                 }
1678
1679         if (session)
1680                 {
1681
1682 #ifdef KRB5_HEIMDAL
1683                 length = session->keyvalue->length;
1684                 enctype = session->keytype;
1685                 contents = session->keyvalue->contents;
1686 #else
1687                 length = session->length;
1688                 enctype = session->enctype;
1689                 contents = session->contents;
1690 #endif
1691                 kssl_ctx->enctype = enctype;
1692                 kssl_ctx->length  = length;
1693                 }
1694         else
1695                 {
1696                 kssl_ctx->enctype = ENCTYPE_UNKNOWN;
1697                 kssl_ctx->length  = 0;
1698                 return KSSL_CTX_OK;
1699                 }
1700
1701         if ((kssl_ctx->key =
1702                 (krb5_octet FAR *) calloc(1, kssl_ctx->length)) == NULL)
1703                 {
1704                 kssl_ctx->length  = 0;
1705                 return KSSL_CTX_ERR;
1706                 }
1707         else
1708                 memcpy(kssl_ctx->key, contents, length);
1709
1710         return KSSL_CTX_OK;
1711         }
1712
1713
1714 /*      Display contents of kssl_ctx struct
1715 */
1716 void
1717 kssl_ctx_show(KSSL_CTX *kssl_ctx)
1718         {
1719         int     i;
1720
1721         printf("kssl_ctx: ");
1722         if (kssl_ctx == NULL)
1723                 {
1724                 printf("NULL\n");
1725                 return;
1726                 }
1727         else
1728                 printf("%p\n", kssl_ctx);
1729
1730         printf("\tservice:\t%s\n",
1731                 (kssl_ctx->service_name)? kssl_ctx->service_name: "NULL");
1732         printf("\tclient:\t%s\n",
1733                 (kssl_ctx->client_princ)? kssl_ctx->client_princ: "NULL");
1734         printf("\tserver:\t%s\n",
1735                 (kssl_ctx->service_host)? kssl_ctx->service_host: "NULL");
1736         printf("\tkeytab:\t%s\n",
1737                 (kssl_ctx->keytab_file)? kssl_ctx->keytab_file: "NULL");
1738         printf("\tkey [%d:%d]:\t",
1739                 kssl_ctx->enctype, kssl_ctx->length);
1740
1741         for (i=0; i < kssl_ctx->length  &&  kssl_ctx->key; i++)
1742                 {
1743                 printf("%02x", kssl_ctx->key[i]);
1744                 }
1745         printf("\n");
1746         return;
1747         }
1748
1749     int 
1750     kssl_keytab_is_available(KSSL_CTX *kssl_ctx)
1751 {
1752     krb5_context                krb5context = NULL;
1753     krb5_keytab                 krb5keytab = NULL;
1754     krb5_keytab_entry           entry;
1755     krb5_principal              princ = NULL;
1756     krb5_error_code             krb5rc = KRB5KRB_ERR_GENERIC;
1757     int rc = 0;
1758
1759     if ((krb5rc = krb5_init_context(&krb5context)))
1760         return(0);
1761
1762     /*  kssl_ctx->keytab_file == NULL ==> use Kerberos default
1763     */
1764     if (kssl_ctx->keytab_file)
1765     {
1766         krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file,
1767                                   &krb5keytab);
1768         if (krb5rc)
1769             goto exit;
1770     }
1771     else
1772     {
1773         krb5rc = krb5_kt_default(krb5context,&krb5keytab);
1774         if (krb5rc)
1775             goto exit;
1776     }
1777
1778     /* the host key we are looking for */
1779     krb5rc = krb5_sname_to_principal(krb5context, NULL, 
1780                                      kssl_ctx->service_name ? kssl_ctx->service_name: KRB5SVC,
1781                                      KRB5_NT_SRV_HST, &princ);
1782
1783     krb5rc = krb5_kt_get_entry(krb5context, krb5keytab, 
1784                                 princ,
1785                                 0 /* IGNORE_VNO */,
1786                                 0 /* IGNORE_ENCTYPE */,
1787                                 &entry);
1788     if ( krb5rc == KRB5_KT_NOTFOUND ) {
1789         rc = 1;
1790         goto exit;
1791     } else if ( krb5rc )
1792         goto exit;
1793     
1794     krb5_kt_free_entry(krb5context, &entry);
1795     rc = 1;
1796
1797   exit:
1798     if (krb5keytab)     krb5_kt_close(krb5context, krb5keytab);
1799     if (princ)          krb5_free_principal(krb5context, princ);
1800     if (krb5context)    krb5_free_context(krb5context);
1801     return(rc);
1802 }
1803
1804 int 
1805 kssl_tgt_is_available(KSSL_CTX *kssl_ctx)
1806         {
1807         krb5_error_code         krb5rc = KRB5KRB_ERR_GENERIC;
1808         krb5_context            krb5context = NULL;
1809         krb5_ccache             krb5ccdef = NULL;
1810         krb5_creds              krb5creds, *krb5credsp = NULL;
1811         int                     rc = 0;
1812
1813         memset((char *)&krb5creds, 0, sizeof(krb5creds));
1814
1815         if (!kssl_ctx)
1816             return(0);
1817
1818         if (!kssl_ctx->service_host)
1819             return(0);
1820
1821         if ((krb5rc = krb5_init_context(&krb5context)) != 0)
1822             goto err;
1823
1824         if ((krb5rc = krb5_sname_to_principal(krb5context,
1825                                               kssl_ctx->service_host,
1826                                               (kssl_ctx->service_name)? kssl_ctx->service_name: KRB5SVC,
1827                                               KRB5_NT_SRV_HST, &krb5creds.server)) != 0)
1828             goto err;
1829
1830         if ((krb5rc = krb5_cc_default(krb5context, &krb5ccdef)) != 0)
1831             goto err;
1832
1833         if ((krb5rc = krb5_cc_get_principal(krb5context, krb5ccdef,
1834                                              &krb5creds.client)) != 0)
1835             goto err;
1836
1837         if ((krb5rc = krb5_get_credentials(krb5context, 0, krb5ccdef,
1838                                             &krb5creds, &krb5credsp)) != 0)
1839             goto err;
1840
1841         rc = 1;
1842
1843       err:
1844 #ifdef KSSL_DEBUG
1845         kssl_ctx_show(kssl_ctx);
1846 #endif  /* KSSL_DEBUG */
1847
1848         if (krb5creds.client)   krb5_free_principal(krb5context, krb5creds.client);
1849         if (krb5creds.server)   krb5_free_principal(krb5context, krb5creds.server);
1850         if (krb5context)        krb5_free_context(krb5context);
1851         return(rc);
1852         }
1853
1854 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_WIN32)
1855 void kssl_krb5_free_data_contents(krb5_context context, krb5_data *data)
1856         {
1857 #ifdef KRB5_HEIMDAL
1858         data->length = 0;
1859         if (data->data)
1860             free(data->data);
1861 #elif defined(KRB5_MIT_OLD11)
1862         if (data->data)  {
1863                 krb5_xfree(data->data);
1864                 data->data = 0;
1865                 }
1866 #else
1867         krb5_free_data_contents(NULL, data);
1868 #endif
1869         }
1870 #endif /* !OPENSSL_SYS_WINDOWS && !OPENSSL_SYS_WIN32 */
1871
1872
1873 /*  Given pointers to KerberosTime and struct tm structs, convert the
1874 **  KerberosTime string to struct tm.  Note that KerberosTime is a
1875 **  ASN1_GENERALIZEDTIME value, constrained to GMT with no fractional
1876 **  seconds as defined in RFC 1510.
1877 **  Return pointer to the (partially) filled in struct tm on success,
1878 **  return NULL on failure.
1879 */
1880 struct tm       *k_gmtime(ASN1_GENERALIZEDTIME *gtime, struct tm *k_tm)
1881         {
1882         char            c, *p;
1883
1884         if (!k_tm)  return NULL;
1885         if (gtime == NULL  ||  gtime->length < 14)  return NULL;
1886         if (gtime->data == NULL)  return NULL;
1887
1888         p = (char *)&gtime->data[14];
1889
1890         c = *p;  *p = '\0';  p -= 2;  k_tm->tm_sec  = atoi(p);      *(p+2) = c;
1891         c = *p;  *p = '\0';  p -= 2;  k_tm->tm_min  = atoi(p);      *(p+2) = c;
1892         c = *p;  *p = '\0';  p -= 2;  k_tm->tm_hour = atoi(p);      *(p+2) = c;
1893         c = *p;  *p = '\0';  p -= 2;  k_tm->tm_mday = atoi(p);      *(p+2) = c;
1894         c = *p;  *p = '\0';  p -= 2;  k_tm->tm_mon  = atoi(p)-1;    *(p+2) = c;
1895         c = *p;  *p = '\0';  p -= 4;  k_tm->tm_year = atoi(p)-1900; *(p+4) = c;
1896
1897         return k_tm;
1898         }
1899
1900
1901 /*  Helper function for kssl_validate_times().
1902 **  We need context->clockskew, but krb5_context is an opaque struct.
1903 **  So we try to sneek the clockskew out through the replay cache.
1904 **      If that fails just return a likely default (300 seconds).
1905 */
1906 krb5_deltat     get_rc_clockskew(krb5_context context)
1907         {
1908         krb5_rcache     rc;
1909         krb5_deltat     clockskew;
1910
1911         if (krb5_rc_default(context, &rc))  return KSSL_CLOCKSKEW;
1912         if (krb5_rc_initialize(context, rc, 0))  return KSSL_CLOCKSKEW;
1913         if (krb5_rc_get_lifespan(context, rc, &clockskew))  {
1914                 clockskew = KSSL_CLOCKSKEW;
1915                 }
1916         (void) krb5_rc_destroy(context, rc);
1917         return clockskew;
1918         }
1919
1920
1921 /*  kssl_validate_times() combines (and more importantly exposes)
1922 **  the MIT KRB5 internal function krb5_validate_times() and the
1923 **  in_clock_skew() macro.  The authenticator client time is checked
1924 **  to be within clockskew secs of the current time and the current
1925 **  time is checked to be within the ticket start and expire times.
1926 **  Either check may be omitted by supplying a NULL value.
1927 **  Returns 0 for valid times, SSL_R_KRB5* error codes otherwise.
1928 **  See Also: (Kerberos source)/krb5/lib/krb5/krb/valid_times.c
1929 **  20010420 VRS
1930 */
1931 krb5_error_code  kssl_validate_times(   krb5_timestamp atime,
1932                                         krb5_ticket_times *ttimes)
1933         {
1934         krb5_deltat     skew;
1935         krb5_timestamp  start, now;
1936         krb5_error_code rc;
1937         krb5_context    context;
1938
1939         if ((rc = krb5_init_context(&context)))  return SSL_R_KRB5_S_BAD_TICKET;
1940         skew = get_rc_clockskew(context); 
1941         if ((rc = krb5_timeofday(context,&now))) return SSL_R_KRB5_S_BAD_TICKET;
1942         krb5_free_context(context);
1943
1944         if (atime  &&  labs(atime - now) >= skew)  return SSL_R_KRB5_S_TKT_SKEW;
1945
1946         if (! ttimes)  return 0;
1947
1948         start = (ttimes->starttime != 0)? ttimes->starttime: ttimes->authtime;
1949         if (start - now > skew)  return SSL_R_KRB5_S_TKT_NYV;
1950         if ((now - ttimes->endtime) > skew)  return SSL_R_KRB5_S_TKT_EXPIRED;
1951
1952 #ifdef KSSL_DEBUG
1953         printf("kssl_validate_times: %d |<-  | %d - %d | < %d  ->| %d\n",
1954                 start, atime, now, skew, ttimes->endtime);
1955 #endif  /* KSSL_DEBUG */
1956
1957         return 0;
1958         }
1959
1960
1961 /*  Decode and decrypt given DER-encoded authenticator, then pass
1962 **  authenticator ctime back in *atimep (or 0 if time unavailable).
1963 **  Returns krb5_error_code and kssl_err on error.  A NULL 
1964 **  authenticator (authentp->length == 0) is not considered an error.
1965 **  Note that kssl_check_authent() makes use of the KRB5 session key;
1966 **  you must call kssl_sget_tkt() to get the key before calling this routine.
1967 */
1968 krb5_error_code  kssl_check_authent(
1969                         /* IN     */    KSSL_CTX        *kssl_ctx,
1970                         /* IN     */    krb5_data       *authentp,
1971                         /* OUT    */    krb5_timestamp  *atimep,
1972                         /* OUT    */    KSSL_ERR        *kssl_err  )
1973         {
1974         krb5_error_code         krb5rc = 0;
1975         KRB5_ENCDATA            *dec_authent = NULL;
1976         KRB5_AUTHENTBODY        *auth = NULL;
1977         krb5_enctype            enctype;
1978         EVP_CIPHER_CTX          ciph_ctx;
1979         const EVP_CIPHER        *enc = NULL;
1980         unsigned char           iv[EVP_MAX_IV_LENGTH];
1981         unsigned char           *p, *unenc_authent;
1982         int                     padl, outl, unencbufsize;
1983         struct tm               tm_time, *tm_l, *tm_g;
1984         time_t                  now, tl, tg, tr, tz_offset;
1985
1986         EVP_CIPHER_CTX_init(&ciph_ctx);
1987         *atimep = 0;
1988         kssl_err_set(kssl_err, 0, "");
1989
1990 #ifndef KRB5CHECKAUTH
1991         authentp = NULL;
1992 #else
1993 #if     KRB5CHECKAUTH == 0
1994         authentp = NULL;
1995 #endif
1996 #endif  /* KRB5CHECKAUTH */
1997
1998         if (authentp == NULL  ||  authentp->length == 0)  return 0;
1999
2000 #ifdef KSSL_DEBUG
2001         {
2002         unsigned int ui;
2003         printf("kssl_check_authent: authenticator[%d]:\n",authentp->length);
2004         p = authentp->data; 
2005         for (ui=0; ui < authentp->length; ui++)  printf("%02x ",p[ui]);
2006         printf("\n");
2007         }
2008 #endif  /* KSSL_DEBUG */
2009
2010         unencbufsize = 2 * authentp->length;
2011         if ((unenc_authent = calloc(1, unencbufsize)) == NULL)
2012                 {
2013                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
2014                         "Unable to allocate authenticator buffer.\n");
2015                 krb5rc = KRB5KRB_ERR_GENERIC;
2016                 goto err;
2017                 }
2018
2019         p = (unsigned char *)authentp->data;
2020         if ((dec_authent = d2i_KRB5_ENCDATA(NULL, &p,
2021                                         (long) authentp->length)) == NULL) 
2022                 {
2023                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
2024                         "Error decoding authenticator.\n");
2025                 krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
2026                 goto err;
2027                 }
2028
2029         enctype = dec_authent->etype->data[0];  /* should = kssl_ctx->enctype */
2030 #if !defined(KRB5_MIT_OLD11)
2031             switch ( enctype ) {
2032             case ENCTYPE_DES3_CBC_SHA1:         /*    EVP_des_ede3_cbc();  */
2033             case ENCTYPE_DES3_CBC_SHA:
2034             case ENCTYPE_DES3_CBC_RAW:
2035                 krb5rc = 0;                     /* Skip, can't handle derived keys */
2036                 goto err;
2037             }
2038 #endif
2039         enc = kssl_map_enc(enctype);
2040         memset(iv, 0, EVP_MAX_IV_LENGTH);       /* per RFC 1510 */
2041
2042         if (enc == NULL)
2043                 {
2044                 /*  Disable kssl_check_authent for ENCTYPE_DES3_CBC_SHA1.
2045                 **  This enctype indicates the authenticator was encrypted
2046                 **  using key-usage derived keys which openssl cannot decrypt.
2047                 */
2048                 goto err;
2049                 }
2050         if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv))
2051                 {
2052                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
2053                         "EVP_DecryptInit_ex error decrypting authenticator.\n");
2054                 krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
2055                 goto err;
2056                 }
2057         if (!EVP_DecryptUpdate(&ciph_ctx, unenc_authent, &outl,
2058                         dec_authent->cipher->data, dec_authent->cipher->length))
2059                 {
2060                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
2061                         "EVP_DecryptUpdate error decrypting authenticator.\n");
2062                 krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
2063                 goto err;
2064                 }
2065         if (outl > unencbufsize)
2066                 {
2067                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
2068                         "Buffer overflow decrypting authenticator.\n");
2069                 krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
2070                 goto err;
2071                 }
2072         if (!EVP_DecryptFinal_ex(&ciph_ctx, &(unenc_authent[outl]), &padl))
2073                 {
2074                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
2075                         "EVP_DecryptFinal_ex error decrypting authenticator.\n");
2076                 krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
2077                 goto err;
2078                 }
2079         outl += padl;
2080         if (outl > unencbufsize)
2081                 {
2082                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
2083                         "Buffer overflow decrypting authenticator.\n");
2084                 krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
2085                 goto err;
2086                 }
2087         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2088
2089 #ifdef KSSL_DEBUG
2090         printf("kssl_check_authent: decrypted authenticator[%d] =\n", outl);
2091         for (padl=0; padl < outl; padl++) printf("%02x ",unenc_authent[padl]);
2092         printf("\n");
2093 #endif  /* KSSL_DEBUG */
2094
2095         if ((p = kssl_skip_confound(enctype, unenc_authent)) == NULL)
2096                 {
2097                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
2098                         "confounded by authenticator.\n");
2099                 krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
2100                 goto err;
2101                 }
2102         outl -= p - unenc_authent;
2103
2104         if ((auth = (KRB5_AUTHENTBODY *) d2i_KRB5_AUTHENT(NULL, &p,
2105                                                           (long) outl))==NULL)
2106                 {
2107                 kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT,
2108                         "Error decoding authenticator body.\n");
2109                 krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY;
2110                 goto err;
2111                 }
2112
2113         memset(&tm_time,0,sizeof(struct tm));
2114         if (k_gmtime(auth->ctime, &tm_time)  &&
2115                 ((tr = mktime(&tm_time)) != (time_t)(-1)))
2116                 {
2117                 now  = time(&now);
2118                 tm_l = localtime(&now);         tl = mktime(tm_l);
2119                 tm_g = gmtime(&now);            tg = mktime(tm_g);
2120                 tz_offset = tg - tl;
2121
2122                 *atimep = tr - tz_offset;
2123                 }
2124
2125 #ifdef KSSL_DEBUG
2126         printf("kssl_check_authent: returns %d for client time ", *atimep);
2127         if (auth && auth->ctime && auth->ctime->length && auth->ctime->data)
2128                 printf("%.*s\n", auth->ctime->length, auth->ctime->data);
2129         else    printf("NULL\n");
2130 #endif  /* KSSL_DEBUG */
2131
2132  err:
2133         if (auth)               KRB5_AUTHENT_free((KRB5_AUTHENT *) auth);
2134         if (dec_authent)        KRB5_ENCDATA_free(dec_authent);
2135         if (unenc_authent)      free(unenc_authent);
2136         return krb5rc;
2137         }
2138
2139
2140 /*  Replaces krb5_build_principal_ext(), with varargs length == 2 (svc, host),
2141 **  because I dont't know how to stub varargs.
2142 **  Returns krb5_error_code == ENOMEM on alloc error, otherwise
2143 **  passes back newly constructed principal, which should be freed by caller.
2144 */
2145 krb5_error_code  kssl_build_principal_2(
2146                         /* UPDATE */    krb5_context    context,
2147                         /* OUT    */    krb5_principal  *princ,
2148                         /* IN     */    int rlen,  const char *realm,
2149                         /* IN     */    int slen,  const char *svc,
2150                         /* IN     */    int hlen,  const char *host)
2151         {
2152         krb5_data               *p_data = NULL;
2153         krb5_principal          new_p = NULL;
2154         char                    *new_r = NULL;
2155
2156         if ((p_data = (krb5_data *) calloc(2, sizeof(krb5_data))) == NULL  ||
2157             (new_p = (krb5_principal) calloc(1, sizeof(krb5_principal_data)))
2158                         == NULL)  goto err;
2159         new_p->length = 2;
2160         new_p->data = p_data;
2161
2162         if ((new_r = calloc(1, rlen + 1)) == NULL)  goto err;
2163         memcpy(new_r, realm, rlen);
2164         krb5_princ_set_realm_length(context, new_p, rlen);
2165         krb5_princ_set_realm_data(context, new_p, new_r);
2166
2167         if ((new_p->data[0].data = calloc(1, slen + 1)) == NULL)  goto err;
2168         memcpy(new_p->data[0].data, svc, slen);
2169         new_p->data[0].length = slen;
2170
2171         if ((new_p->data[1].data = calloc(1, hlen + 1)) == NULL)  goto err;
2172         memcpy(new_p->data[1].data, host, hlen);
2173         new_p->data[1].length = hlen;
2174         
2175         krb5_princ_type(context, new_p) = KRB5_NT_UNKNOWN;
2176         *princ = new_p;
2177         return 0;
2178
2179  err:
2180         if (new_p  &&  new_p[0].data)   free(new_p[0].data);
2181         if (new_p  &&  new_p[1].data)   free(new_p[1].data);
2182         if (new_p)      free(new_p);
2183         if (new_r)      free(new_r);
2184         return ENOMEM;
2185         }
2186
2187
2188 #else /* !OPENSSL_NO_KRB5 */
2189
2190 #if defined(PEDANTIC) || defined(OPENSSL_SYS_VMS)
2191 static int dummy=(int)&dummy;
2192 #endif
2193
2194 #endif  /* !OPENSSL_NO_KRB5     */
2195