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