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