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