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