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