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