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