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