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