5bb33b11d75c0dcce004d9fb72d2ab18eca83d3e
[kai/samba.git] / source3 / libsmb / clikrb5.c
1 /* 
2    Unix SMB/CIFS implementation.
3    simple kerberos5 routines for active directory
4    Copyright (C) Andrew Tridgell 2001
5    Copyright (C) Luke Howard 2002-2003
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
7    Copyright (C) Guenther Deschner 2005-2007
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #define KRB5_PRIVATE    1       /* this file uses PRIVATE interfaces! */
24 #define KRB5_DEPRECATED 1       /* this file uses DEPRECATED interfaces! */
25
26 #include "includes.h"
27
28 #ifdef HAVE_KRB5
29
30 #ifdef HAVE_KRB5_KEYBLOCK_KEYVALUE /* Heimdal */
31 #define KRB5_KEY_TYPE(k)        ((k)->keytype) 
32 #define KRB5_KEY_LENGTH(k)      ((k)->keyvalue.length)
33 #define KRB5_KEY_DATA(k)        ((k)->keyvalue.data)
34 #define KRB5_KEY_DATA_CAST      void
35 #else /* MIT */
36 #define KRB5_KEY_TYPE(k)        ((k)->enctype)
37 #define KRB5_KEY_LENGTH(k)      ((k)->length)
38 #define KRB5_KEY_DATA(k)        ((k)->contents)
39 #define KRB5_KEY_DATA_CAST      krb5_octet
40 #endif /* HAVE_KRB5_KEYBLOCK_KEYVALUE */
41
42 #define GSSAPI_CHECKSUM      0x8003             /* Checksum type value for Kerberos */
43 #define GSSAPI_BNDLENGTH     16                 /* Bind Length (rfc-1964 pg.3) */
44 #define GSSAPI_CHECKSUM_SIZE (12+GSSAPI_BNDLENGTH)
45
46 #if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_FWD_TGT_CREDS) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY)
47 static krb5_error_code ads_krb5_get_fwd_ticket( krb5_context context,
48                                          krb5_auth_context *auth_context,
49                                          krb5_creds *credsp,
50                                          krb5_ccache ccache,
51                                          krb5_data *authenticator);
52 #endif
53
54 /**************************************************************
55  Wrappers around kerberos string functions that convert from
56  utf8 -> unix charset and vica versa.
57 **************************************************************/
58
59 /**************************************************************
60  krb5_parse_name that takes a UNIX charset.
61 **************************************************************/
62
63  krb5_error_code smb_krb5_parse_name(krb5_context context,
64                                 const char *name, /* in unix charset */
65                                 krb5_principal *principal)
66 {
67         krb5_error_code ret;
68         char *utf8_name;
69         size_t converted_size;
70
71         if (!push_utf8_allocate(&utf8_name, name, &converted_size)) {
72                 return ENOMEM;
73         }
74
75         ret = krb5_parse_name(context, utf8_name, principal);
76         SAFE_FREE(utf8_name);
77         return ret;
78 }
79
80 #ifdef HAVE_KRB5_PARSE_NAME_NOREALM
81 /**************************************************************
82  krb5_parse_name_norealm that takes a UNIX charset.
83 **************************************************************/
84
85 static krb5_error_code smb_krb5_parse_name_norealm_conv(krb5_context context,
86                                 const char *name, /* in unix charset */
87                                 krb5_principal *principal)
88 {
89         krb5_error_code ret;
90         char *utf8_name;
91         size_t converted_size;
92
93         *principal = NULL;
94         if (!push_utf8_allocate(&utf8_name, name, &converted_size)) {
95                 return ENOMEM;
96         }
97
98         ret = krb5_parse_name_norealm(context, utf8_name, principal);
99         SAFE_FREE(utf8_name);
100         return ret;
101 }
102 #endif
103
104 /**************************************************************
105  krb5_parse_name that returns a UNIX charset name. Must
106  be freed with normal free() call.
107 **************************************************************/
108
109  krb5_error_code smb_krb5_unparse_name(krb5_context context,
110                                         krb5_const_principal principal,
111                                         char **unix_name)
112 {
113         krb5_error_code ret;
114         char *utf8_name;
115         size_t converted_size;
116
117         *unix_name = NULL;
118         ret = krb5_unparse_name(context, principal, &utf8_name);
119         if (ret) {
120                 return ret;
121         }
122
123         if (!pull_utf8_allocate(unix_name, utf8_name, &converted_size)) {
124                 krb5_free_unparsed_name(context, utf8_name);
125                 return ENOMEM;
126         }
127         krb5_free_unparsed_name(context, utf8_name);
128         return 0;
129 }
130
131 #ifndef HAVE_KRB5_SET_REAL_TIME
132 /*
133  * This function is not in the Heimdal mainline.
134  */
135  krb5_error_code krb5_set_real_time(krb5_context context, int32_t seconds, int32_t microseconds)
136 {
137         krb5_error_code ret;
138         int32_t sec, usec;
139
140         ret = krb5_us_timeofday(context, &sec, &usec);
141         if (ret)
142                 return ret;
143
144         context->kdc_sec_offset = seconds - sec;
145         context->kdc_usec_offset = microseconds - usec;
146
147         return 0;
148 }
149 #endif
150
151 #if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
152
153 #if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)
154
155 /* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
156  * to krb5_set_default_tgs_ktypes. See
157  *         http://lists.samba.org/archive/samba-technical/2006-July/048271.html
158  *
159  * If the MIT libraries are not exporting internal symbols, we will end up in
160  * this branch, which is correct. Otherwise we will continue to use the
161  * internal symbol
162  */
163  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
164 {
165     return krb5_set_default_tgs_enctypes(ctx, enc);
166 }
167
168 #elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)
169
170 /* Heimdal */
171  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
172 {
173         return krb5_set_default_in_tkt_etypes(ctx, enc);
174 }
175
176 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */
177
178 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */
179
180 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
181 /* HEIMDAL */
182  bool setup_kaddr( krb5_address *pkaddr, struct sockaddr_storage *paddr)
183 {
184         memset(pkaddr, '\0', sizeof(krb5_address));
185 #if defined(HAVE_IPV6) && defined(KRB5_ADDRESS_INET6)
186         if (paddr->ss_family == AF_INET6) {
187                 pkaddr->addr_type = KRB5_ADDRESS_INET6;
188                 pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
189                 pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
190                 return true;
191         }
192 #endif
193         if (paddr->ss_family == AF_INET) {
194                 pkaddr->addr_type = KRB5_ADDRESS_INET;
195                 pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
196                 pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
197                 return true;
198         }
199         return false;
200 }
201 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
202 /* MIT */
203  bool setup_kaddr( krb5_address *pkaddr, struct sockaddr_storage *paddr)
204 {
205         memset(pkaddr, '\0', sizeof(krb5_address));
206 #if defined(HAVE_IPV6) && defined(ADDRTYPE_INET6)
207         if (paddr->ss_family == AF_INET6) {
208                 pkaddr->addrtype = ADDRTYPE_INET6;
209                 pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
210                 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
211                 return true;
212         }
213 #endif
214         if (paddr->ss_family == AF_INET) {
215                 pkaddr->addrtype = ADDRTYPE_INET;
216                 pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
217                 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
218                 return true;
219         }
220         return false;
221 }
222 #else
223 #error UNKNOWN_ADDRTYPE
224 #endif
225
226 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_USE_ENCTYPE) && defined(HAVE_KRB5_STRING_TO_KEY) && defined(HAVE_KRB5_ENCRYPT_BLOCK)
227 static int create_kerberos_key_from_string_direct(krb5_context context,
228                                                   krb5_principal host_princ,
229                                                   krb5_data *password,
230                                                   krb5_keyblock *key,
231                                                   krb5_enctype enctype)
232 {
233         int ret = 0;
234         krb5_data salt;
235         krb5_encrypt_block eblock;
236
237         ret = krb5_principal2salt(context, host_princ, &salt);
238         if (ret) {
239                 DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
240                 return ret;
241         }
242         krb5_use_enctype(context, &eblock, enctype);
243         ret = krb5_string_to_key(context, &eblock, key, password, &salt);
244         SAFE_FREE(salt.data);
245
246         return ret;
247 }
248 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
249 static int create_kerberos_key_from_string_direct(krb5_context context,
250                                                   krb5_principal host_princ,
251                                                   krb5_data *password,
252                                                   krb5_keyblock *key,
253                                                   krb5_enctype enctype)
254 {
255         int ret;
256         krb5_salt salt;
257
258         ret = krb5_get_pw_salt(context, host_princ, &salt);
259         if (ret) {
260                 DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
261                 return ret;
262         }
263
264         ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, salt, key);
265         krb5_free_salt(context, salt);
266
267         return ret;
268 }
269 #else
270 #error UNKNOWN_CREATE_KEY_FUNCTIONS
271 #endif
272
273  int create_kerberos_key_from_string(krb5_context context,
274                                         krb5_principal host_princ,
275                                         krb5_data *password,
276                                         krb5_keyblock *key,
277                                         krb5_enctype enctype,
278                                         bool no_salt)
279 {
280         krb5_principal salt_princ = NULL;
281         int ret;
282         /*
283          * Check if we've determined that the KDC is salting keys for this
284          * principal/enctype in a non-obvious way.  If it is, try to match
285          * its behavior.
286          */
287         if (no_salt) {
288                 KRB5_KEY_DATA(key) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
289                 if (!KRB5_KEY_DATA(key)) {
290                         return ENOMEM;
291                 }
292                 memcpy(KRB5_KEY_DATA(key), password->data, password->length);
293                 KRB5_KEY_LENGTH(key) = password->length;
294                 KRB5_KEY_TYPE(key) = enctype;
295                 return 0;
296         }
297         salt_princ = kerberos_fetch_salt_princ_for_host_princ(context, host_princ, enctype);
298         ret = create_kerberos_key_from_string_direct(context, salt_princ ? salt_princ : host_princ, password, key, enctype);
299         if (salt_princ) {
300                 krb5_free_principal(context, salt_princ);
301         }
302         return ret;
303 }
304
305 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
306  krb5_error_code get_kerberos_allowed_etypes(krb5_context context, 
307                                             krb5_enctype **enctypes)
308 {
309         return krb5_get_permitted_enctypes(context, enctypes);
310 }
311 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
312  krb5_error_code get_kerberos_allowed_etypes(krb5_context context, 
313                                             krb5_enctype **enctypes)
314 {
315         return krb5_get_default_in_tkt_etypes(context, enctypes);
316 }
317 #else
318 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
319 #endif
320
321 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
322  krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
323                                         krb5_auth_context auth_context,
324                                         krb5_keyblock *keyblock)
325 {
326         return krb5_auth_con_setkey(context, auth_context, keyblock);
327 }
328 #endif
329
330 bool unwrap_edata_ntstatus(TALLOC_CTX *mem_ctx, 
331                            DATA_BLOB *edata, 
332                            DATA_BLOB *edata_out)
333 {
334         DATA_BLOB edata_contents;
335         ASN1_DATA data;
336         int edata_type;
337
338         if (!edata->length) {
339                 return False;
340         }
341
342         asn1_load(&data, *edata);
343         asn1_start_tag(&data, ASN1_SEQUENCE(0));
344         asn1_start_tag(&data, ASN1_CONTEXT(1));
345         asn1_read_Integer(&data, &edata_type);
346
347         if (edata_type != KRB5_PADATA_PW_SALT) {
348                 DEBUG(0,("edata is not of required type %d but of type %d\n", 
349                         KRB5_PADATA_PW_SALT, edata_type));
350                 asn1_free(&data);
351                 return False;
352         }
353         
354         asn1_start_tag(&data, ASN1_CONTEXT(2));
355         asn1_read_OctetString(&data, &edata_contents);
356         asn1_end_tag(&data);
357         asn1_end_tag(&data);
358         asn1_end_tag(&data);
359         asn1_free(&data);
360
361         *edata_out = data_blob_talloc(mem_ctx, edata_contents.data, edata_contents.length);
362
363         data_blob_free(&edata_contents);
364
365         return True;
366 }
367
368
369 bool unwrap_pac(TALLOC_CTX *mem_ctx, DATA_BLOB *auth_data, DATA_BLOB *unwrapped_pac_data)
370 {
371         DATA_BLOB pac_contents;
372         ASN1_DATA data;
373         int data_type;
374
375         if (!auth_data->length) {
376                 return False;
377         }
378
379         asn1_load(&data, *auth_data);
380         asn1_start_tag(&data, ASN1_SEQUENCE(0));
381         asn1_start_tag(&data, ASN1_SEQUENCE(0));
382         asn1_start_tag(&data, ASN1_CONTEXT(0));
383         asn1_read_Integer(&data, &data_type);
384         
385         if (data_type != KRB5_AUTHDATA_WIN2K_PAC ) {
386                 DEBUG(10,("authorization data is not a Windows PAC (type: %d)\n", data_type));
387                 asn1_free(&data);
388                 return False;
389         }
390         
391         asn1_end_tag(&data);
392         asn1_start_tag(&data, ASN1_CONTEXT(1));
393         asn1_read_OctetString(&data, &pac_contents);
394         asn1_end_tag(&data);
395         asn1_end_tag(&data);
396         asn1_end_tag(&data);
397         asn1_free(&data);
398
399         *unwrapped_pac_data = data_blob_talloc(mem_ctx, pac_contents.data, pac_contents.length);
400
401         data_blob_free(&pac_contents);
402
403         return True;
404 }
405
406  bool get_auth_data_from_tkt(TALLOC_CTX *mem_ctx, DATA_BLOB *auth_data, krb5_ticket *tkt)
407 {
408         DATA_BLOB auth_data_wrapped;
409         bool got_auth_data_pac = False;
410         int i;
411         
412 #if defined(HAVE_KRB5_TKT_ENC_PART2)
413         if (tkt->enc_part2 && tkt->enc_part2->authorization_data && 
414             tkt->enc_part2->authorization_data[0] && 
415             tkt->enc_part2->authorization_data[0]->length)
416         {
417                 for (i = 0; tkt->enc_part2->authorization_data[i] != NULL; i++) {
418                 
419                         if (tkt->enc_part2->authorization_data[i]->ad_type != 
420                             KRB5_AUTHDATA_IF_RELEVANT) {
421                                 DEBUG(10,("get_auth_data_from_tkt: ad_type is %d\n", 
422                                         tkt->enc_part2->authorization_data[i]->ad_type));
423                                 continue;
424                         }
425
426                         auth_data_wrapped = data_blob(tkt->enc_part2->authorization_data[i]->contents,
427                                                       tkt->enc_part2->authorization_data[i]->length);
428
429                         /* check if it is a PAC */
430                         got_auth_data_pac = unwrap_pac(mem_ctx, &auth_data_wrapped, auth_data);
431                         data_blob_free(&auth_data_wrapped);
432
433                         if (got_auth_data_pac) {
434                                 return true;
435                         }
436                 }
437
438                 return got_auth_data_pac;
439         }
440                 
441 #else
442         if (tkt->ticket.authorization_data && 
443             tkt->ticket.authorization_data->len)
444         {
445                 for (i = 0; i < tkt->ticket.authorization_data->len; i++) {
446                         
447                         if (tkt->ticket.authorization_data->val[i].ad_type != 
448                             KRB5_AUTHDATA_IF_RELEVANT) {
449                                 DEBUG(10,("get_auth_data_from_tkt: ad_type is %d\n", 
450                                         tkt->ticket.authorization_data->val[i].ad_type));
451                                 continue;
452                         }
453
454                         auth_data_wrapped = data_blob(tkt->ticket.authorization_data->val[i].ad_data.data,
455                                                       tkt->ticket.authorization_data->val[i].ad_data.length);
456
457                         /* check if it is a PAC */
458                         got_auth_data_pac = unwrap_pac(mem_ctx, &auth_data_wrapped, auth_data);
459                         data_blob_free(&auth_data_wrapped);
460
461                         if (got_auth_data_pac) {
462                                 return true;
463                         }
464                 }
465
466                 return got_auth_data_pac;
467         }
468 #endif
469         return False;
470 }
471
472  krb5_const_principal get_principal_from_tkt(krb5_ticket *tkt)
473 {
474 #if defined(HAVE_KRB5_TKT_ENC_PART2)
475         return tkt->enc_part2->client;
476 #else
477         return tkt->client;
478 #endif
479 }
480
481 #if !defined(HAVE_KRB5_LOCATE_KDC)
482
483 /* krb5_locate_kdc is an internal MIT symbol. MIT are not yet willing to commit
484  * to a public interface for this functionality, so we have to be able to live
485  * without it if the MIT libraries are hiding their internal symbols.
486  */
487
488 #if defined(KRB5_KRBHST_INIT)
489 /* Heimdal */
490  krb5_error_code smb_krb5_locate_kdc(krb5_context ctx, const krb5_data *realm, struct sockaddr **addr_pp, int *naddrs, int get_masters)
491 {
492         krb5_krbhst_handle hnd;
493         krb5_krbhst_info *hinfo;
494         krb5_error_code rc;
495         int num_kdcs, i;
496         struct sockaddr *sa;
497         struct addrinfo *ai;
498
499         *addr_pp = NULL;
500         *naddrs = 0;
501
502         rc = krb5_krbhst_init(ctx, realm->data, KRB5_KRBHST_KDC, &hnd);
503         if (rc) {
504                 DEBUG(0, ("smb_krb5_locate_kdc: krb5_krbhst_init failed (%s)\n", error_message(rc)));
505                 return rc;
506         }
507
508         for ( num_kdcs = 0; (rc = krb5_krbhst_next(ctx, hnd, &hinfo) == 0); num_kdcs++)
509                 ;
510
511         krb5_krbhst_reset(ctx, hnd);
512
513         if (!num_kdcs) {
514                 DEBUG(0, ("smb_krb5_locate_kdc: zero kdcs found !\n"));
515                 krb5_krbhst_free(ctx, hnd);
516                 return -1;
517         }
518
519         sa = SMB_MALLOC_ARRAY( struct sockaddr, num_kdcs );
520         if (!sa) {
521                 DEBUG(0, ("smb_krb5_locate_kdc: malloc failed\n"));
522                 krb5_krbhst_free(ctx, hnd);
523                 naddrs = 0;
524                 return -1;
525         }
526
527         memset(sa, '\0', sizeof(struct sockaddr) * num_kdcs );
528
529         for (i = 0; i < num_kdcs && (rc = krb5_krbhst_next(ctx, hnd, &hinfo) == 0); i++) {
530
531 #if defined(HAVE_KRB5_KRBHST_GET_ADDRINFO)
532                 rc = krb5_krbhst_get_addrinfo(ctx, hinfo, &ai);
533                 if (rc) {
534                         DEBUG(0,("krb5_krbhst_get_addrinfo failed: %s\n", error_message(rc)));
535                         continue;
536                 }
537 #endif
538                 if (hinfo->ai && hinfo->ai->ai_family == AF_INET) 
539                         memcpy(&sa[i], hinfo->ai->ai_addr, sizeof(struct sockaddr));
540         }
541
542         krb5_krbhst_free(ctx, hnd);
543
544         *naddrs = num_kdcs;
545         *addr_pp = sa;
546         return 0;
547 }
548
549 #else /* ! defined(KRB5_KRBHST_INIT) */
550
551  krb5_error_code smb_krb5_locate_kdc(krb5_context ctx, const krb5_data *realm,
552                 struct sockaddr **addr_pp, int *naddrs, int get_masters)
553 {
554         DEBUG(0, ("unable to explicitly locate the KDC on this platform\n"));
555         return KRB5_KDC_UNREACH;
556 }
557
558 #endif /* KRB5_KRBHST_INIT */
559
560 #else /* ! HAVE_KRB5_LOCATE_KDC */
561
562  krb5_error_code smb_krb5_locate_kdc(krb5_context ctx, const krb5_data *realm,
563                 struct sockaddr **addr_pp, int *naddrs, int get_masters)
564 {
565         return krb5_locate_kdc(ctx, realm, addr_pp, naddrs, get_masters);
566 }
567
568 #endif /* HAVE_KRB5_LOCATE_KDC */
569
570 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
571  void krb5_free_unparsed_name(krb5_context context, char *val)
572 {
573         SAFE_FREE(val);
574 }
575 #endif
576
577  void kerberos_free_data_contents(krb5_context context, krb5_data *pdata)
578 {
579 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
580         if (pdata->data) {
581                 krb5_free_data_contents(context, pdata);
582         }
583 #else
584         SAFE_FREE(pdata->data);
585 #endif
586 }
587
588  void kerberos_set_creds_enctype(krb5_creds *pcreds, int enctype)
589 {
590 #if defined(HAVE_KRB5_KEYBLOCK_IN_CREDS)
591         KRB5_KEY_TYPE((&pcreds->keyblock)) = enctype;
592 #elif defined(HAVE_KRB5_SESSION_IN_CREDS)
593         KRB5_KEY_TYPE((&pcreds->session)) = enctype;
594 #else
595 #error UNKNOWN_KEYBLOCK_MEMBER_IN_KRB5_CREDS_STRUCT
596 #endif
597 }
598
599  bool kerberos_compatible_enctypes(krb5_context context,
600                                   krb5_enctype enctype1,
601                                   krb5_enctype enctype2)
602 {
603 #if defined(HAVE_KRB5_C_ENCTYPE_COMPARE)
604         krb5_boolean similar = 0;
605
606         krb5_c_enctype_compare(context, enctype1, enctype2, &similar);
607         return similar ? True : False;
608 #elif defined(HAVE_KRB5_ENCTYPES_COMPATIBLE_KEYS)
609         return krb5_enctypes_compatible_keys(context, enctype1, enctype2) ? True : False;
610 #endif
611 }
612
613 static bool ads_cleanup_expired_creds(krb5_context context, 
614                                       krb5_ccache  ccache,
615                                       krb5_creds  *credsp)
616 {
617         krb5_error_code retval;
618         const char *cc_type = krb5_cc_get_type(context, ccache);
619
620         DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
621                   cc_type, krb5_cc_get_name(context, ccache),
622                   http_timestring(credsp->times.endtime)));
623
624         /* we will probably need new tickets if the current ones
625            will expire within 10 seconds.
626         */
627         if (credsp->times.endtime >= (time(NULL) + 10))
628                 return False;
629
630         /* heimdal won't remove creds from a file ccache, and 
631            perhaps we shouldn't anyway, since internally we 
632            use memory ccaches, and a FILE one probably means that
633            we're using creds obtained outside of our exectuable
634         */
635         if (strequal(cc_type, "FILE")) {
636                 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
637                 return False;
638         }
639
640         retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
641         if (retval) {
642                 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
643                           error_message(retval)));
644                 /* If we have an error in this, we want to display it,
645                    but continue as though we deleted it */
646         }
647         return True;
648 }
649
650 /*
651   we can't use krb5_mk_req because w2k wants the service to be in a particular format
652 */
653 static krb5_error_code ads_krb5_mk_req(krb5_context context, 
654                                        krb5_auth_context *auth_context, 
655                                        const krb5_flags ap_req_options,
656                                        const char *principal,
657                                        krb5_ccache ccache, 
658                                        krb5_data *outbuf, 
659                                        time_t *expire_time)
660 {
661         krb5_error_code           retval;
662         krb5_principal    server;
663         krb5_creds              * credsp;
664         krb5_creds                creds;
665         krb5_data in_data;
666         bool creds_ready = False;
667         int i = 0, maxtries = 3;
668         
669         ZERO_STRUCT(in_data);
670
671         retval = smb_krb5_parse_name(context, principal, &server);
672         if (retval) {
673                 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
674                 return retval;
675         }
676         
677         /* obtain ticket & session key */
678         ZERO_STRUCT(creds);
679         if ((retval = krb5_copy_principal(context, server, &creds.server))) {
680                 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n", 
681                          error_message(retval)));
682                 goto cleanup_princ;
683         }
684         
685         if ((retval = krb5_cc_get_principal(context, ccache, &creds.client))) {
686                 /* This can commonly fail on smbd startup with no ticket in the cache.
687                  * Report at higher level than 1. */
688                 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n", 
689                          error_message(retval)));
690                 goto cleanup_creds;
691         }
692
693         while (!creds_ready && (i < maxtries)) {
694
695                 if ((retval = krb5_get_credentials(context, 0, ccache, 
696                                                    &creds, &credsp))) {
697                         DEBUG(1,("ads_krb5_mk_req: krb5_get_credentials failed for %s (%s)\n",
698                                  principal, error_message(retval)));
699                         goto cleanup_creds;
700                 }
701
702                 /* cope with ticket being in the future due to clock skew */
703                 if ((unsigned)credsp->times.starttime > time(NULL)) {
704                         time_t t = time(NULL);
705                         int time_offset =(int)((unsigned)credsp->times.starttime-t);
706                         DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
707                         krb5_set_real_time(context, t + time_offset + 1, 0);
708                 }
709
710                 if (!ads_cleanup_expired_creds(context, ccache, credsp)) {
711                         creds_ready = True;
712                 }
713
714                 i++;
715         }
716
717         DEBUG(10,("ads_krb5_mk_req: Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
718                   principal, krb5_cc_get_type(context, ccache), krb5_cc_get_name(context, ccache),
719                   http_timestring((unsigned)credsp->times.endtime), 
720                   (unsigned)credsp->times.endtime));
721
722         if (expire_time) {
723                 *expire_time = (time_t)credsp->times.endtime;
724         }
725
726 #if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_FWD_TGT_CREDS) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY)
727         if( credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE ) {
728                 /* Fetch a forwarded TGT from the KDC so that we can hand off a 2nd ticket
729                  as part of the kerberos exchange. */
730
731                 DEBUG( 3, ("ads_krb5_mk_req: server marked as OK to delegate to, building forwardable TGT\n")  );
732
733                 if( *auth_context == NULL ) {
734                         /* Allocate if it has not yet been allocated. */
735                         retval = krb5_auth_con_init( context, auth_context );
736                         if (retval) {
737                                 DEBUG(1,("ads_krb5_mk_req: krb5_auth_con_init failed (%s)\n",
738                                         error_message(retval)));
739                                 goto cleanup_creds;
740                         }
741                 }
742
743                 retval = krb5_auth_con_setuseruserkey( context, *auth_context, &credsp->keyblock );
744                 if (retval) {
745                         DEBUG(1,("ads_krb5_mk_req: krb5_auth_con_setuseruserkey failed (%s)\n",
746                                 error_message(retval)));
747                         goto cleanup_creds;
748                 }
749
750                 /* Must use a subkey for forwarded tickets. */
751                 retval = krb5_auth_con_setflags( context, *auth_context, KRB5_AUTH_CONTEXT_USE_SUBKEY);
752                 if (retval) {
753                         DEBUG(1,("ads_krb5_mk_req: krb5_auth_con_setflags failed (%s)\n",
754                                 error_message(retval)));
755                         goto cleanup_creds;
756                 }
757
758                 retval = ads_krb5_get_fwd_ticket( context,
759                                                 auth_context,
760                                                 credsp,
761                                                 ccache,
762                                                 &in_data );
763                 if (retval) {
764                         DEBUG( 1, ("ads_krb5_get_fwd_ticket failed (%s)\n", error_message( retval ) ) );
765                         goto cleanup_creds;
766                 }
767
768                 if (retval) {
769                         DEBUG( 1, ("krb5_auth_con_set_req_cksumtype failed (%s)\n",
770                                 error_message( retval ) ) );
771                         goto cleanup_creds;
772                 }
773
774         }
775 #endif
776
777         retval = krb5_mk_req_extended(context, auth_context, ap_req_options, 
778                                       &in_data, credsp, outbuf);
779         if (retval) {
780                 DEBUG(1,("ads_krb5_mk_req: krb5_mk_req_extended failed (%s)\n", 
781                          error_message(retval)));
782         }
783
784         if (in_data.data) {
785                 free( in_data.data );
786                 in_data.length = 0;
787         }
788
789         krb5_free_creds(context, credsp);
790
791 cleanup_creds:
792         krb5_free_cred_contents(context, &creds);
793
794 cleanup_princ:
795         krb5_free_principal(context, server);
796
797         return retval;
798 }
799
800 /*
801   get a kerberos5 ticket for the given service 
802 */
803 int cli_krb5_get_ticket(const char *principal, time_t time_offset, 
804                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5, 
805                         uint32 extra_ap_opts, const char *ccname, 
806                         time_t *tgs_expire)
807
808 {
809         krb5_error_code retval;
810         krb5_data packet;
811         krb5_context context = NULL;
812         krb5_ccache ccdef = NULL;
813         krb5_auth_context auth_context = NULL;
814         krb5_enctype enc_types[] = {
815 #ifdef ENCTYPE_ARCFOUR_HMAC
816                 ENCTYPE_ARCFOUR_HMAC,
817 #endif 
818                 ENCTYPE_DES_CBC_MD5, 
819                 ENCTYPE_DES_CBC_CRC, 
820                 ENCTYPE_NULL};
821
822         initialize_krb5_error_table();
823         retval = krb5_init_context(&context);
824         if (retval) {
825                 DEBUG(1,("cli_krb5_get_ticket: krb5_init_context failed (%s)\n", 
826                          error_message(retval)));
827                 goto failed;
828         }
829
830         if (time_offset != 0) {
831                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
832         }
833
834         if ((retval = krb5_cc_resolve(context, ccname ?
835                         ccname : krb5_cc_default_name(context), &ccdef))) {
836                 DEBUG(1,("cli_krb5_get_ticket: krb5_cc_default failed (%s)\n",
837                          error_message(retval)));
838                 goto failed;
839         }
840
841         if ((retval = krb5_set_default_tgs_ktypes(context, enc_types))) {
842                 DEBUG(1,("cli_krb5_get_ticket: krb5_set_default_tgs_ktypes failed (%s)\n",
843                          error_message(retval)));
844                 goto failed;
845         }
846
847         if ((retval = ads_krb5_mk_req(context, 
848                                         &auth_context, 
849                                         AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
850                                         principal,
851                                         ccdef, &packet,
852                                         tgs_expire))) {
853                 goto failed;
854         }
855
856         get_krb5_smb_session_key(context, auth_context, session_key_krb5, False);
857
858         *ticket = data_blob(packet.data, packet.length);
859
860         kerberos_free_data_contents(context, &packet); 
861
862 failed:
863
864         if ( context ) {
865                 if (ccdef)
866                         krb5_cc_close(context, ccdef);
867                 if (auth_context)
868                         krb5_auth_con_free(context, auth_context);
869                 krb5_free_context(context);
870         }
871                 
872         return retval;
873 }
874
875  bool get_krb5_smb_session_key(krb5_context context, krb5_auth_context auth_context, DATA_BLOB *session_key, bool remote)
876  {
877         krb5_keyblock *skey;
878         krb5_error_code err;
879         bool ret = False;
880
881         if (remote)
882                 err = krb5_auth_con_getremotesubkey(context, auth_context, &skey);
883         else
884                 err = krb5_auth_con_getlocalsubkey(context, auth_context, &skey);
885         if (err == 0 && skey != NULL) {
886                 DEBUG(10, ("Got KRB5 session key of length %d\n",  (int)KRB5_KEY_LENGTH(skey)));
887                 *session_key = data_blob(KRB5_KEY_DATA(skey), KRB5_KEY_LENGTH(skey));
888                 dump_data_pw("KRB5 Session Key:\n", session_key->data, session_key->length);
889
890                 ret = True;
891
892                 krb5_free_keyblock(context, skey);
893         } else {
894                 DEBUG(10, ("KRB5 error getting session key %d\n", err));
895         }
896
897         return ret;
898  }
899
900
901 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
902  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i );
903
904  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i )
905 {
906         static krb5_data kdata;
907
908         kdata.data = (char *)krb5_principal_get_comp_string(context, principal, i);
909         kdata.length = strlen((const char *)kdata.data);
910         return &kdata;
911 }
912 #endif
913
914  krb5_error_code smb_krb5_kt_free_entry(krb5_context context, krb5_keytab_entry *kt_entry)
915 {
916 #if defined(HAVE_KRB5_KT_FREE_ENTRY)
917         return krb5_kt_free_entry(context, kt_entry);
918 #elif defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
919         return krb5_free_keytab_entry_contents(context, kt_entry);
920 #else
921 #error UNKNOWN_KT_FREE_FUNCTION
922 #endif
923 }
924
925  void smb_krb5_checksum_from_pac_sig(krb5_checksum *cksum,
926                                      struct PAC_SIGNATURE_DATA *sig)
927 {
928 #ifdef HAVE_CHECKSUM_IN_KRB5_CHECKSUM
929         cksum->cksumtype        = (krb5_cksumtype)sig->type;
930         cksum->checksum.length  = sig->signature.length;
931         cksum->checksum.data    = sig->signature.data;
932 #else
933         cksum->checksum_type    = (krb5_cksumtype)sig->type;
934         cksum->length           = sig->signature.length;
935         cksum->contents         = sig->signature.data;
936 #endif
937 }
938
939  krb5_error_code smb_krb5_verify_checksum(krb5_context context,
940                                           const krb5_keyblock *keyblock,
941                                          krb5_keyusage usage,
942                                          krb5_checksum *cksum,
943                                          uint8 *data,
944                                          size_t length)
945 {
946         krb5_error_code ret;
947
948         /* verify the checksum */
949
950         /* welcome to the wonderful world of samba's kerberos abstraction layer:
951          * 
952          * function                     heimdal 0.6.1rc3        heimdal 0.7     MIT krb 1.4.2
953          * -----------------------------------------------------------------------------
954          * krb5_c_verify_checksum       -                       works           works
955          * krb5_verify_checksum         works (6 args)          works (6 args)  broken (7 args) 
956          */
957
958 #if defined(HAVE_KRB5_C_VERIFY_CHECKSUM)
959         {
960                 krb5_boolean checksum_valid = False;
961                 krb5_data input;
962
963                 input.data = (char *)data;
964                 input.length = length;
965
966                 ret = krb5_c_verify_checksum(context, 
967                                              keyblock, 
968                                              usage,
969                                              &input, 
970                                              cksum,
971                                              &checksum_valid);
972                 if (ret) {
973                         DEBUG(3,("smb_krb5_verify_checksum: krb5_c_verify_checksum() failed: %s\n", 
974                                 error_message(ret)));
975                         return ret;
976                 }
977
978                 if (!checksum_valid)
979                         ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
980         }
981
982 #elif KRB5_VERIFY_CHECKSUM_ARGS == 6 && defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CRYPTO) && defined(HAVE_KRB5_CRYPTO_DESTROY)
983
984         /* Warning: MIT's krb5_verify_checksum cannot be used as it will use a key
985          * without enctype and it ignores any key_usage types - Guenther */
986
987         {
988
989                 krb5_crypto crypto;
990                 ret = krb5_crypto_init(context,
991                                        keyblock,
992                                        0,
993                                        &crypto);
994                 if (ret) {
995                         DEBUG(0,("smb_krb5_verify_checksum: krb5_crypto_init() failed: %s\n", 
996                                 error_message(ret)));
997                         return ret;
998                 }
999
1000                 ret = krb5_verify_checksum(context,
1001                                            crypto,
1002                                            usage,
1003                                            data,
1004                                            length,
1005                                            cksum);
1006
1007                 krb5_crypto_destroy(context, crypto);
1008         }
1009
1010 #else
1011 #error UNKNOWN_KRB5_VERIFY_CHECKSUM_FUNCTION
1012 #endif
1013
1014         return ret;
1015 }
1016
1017  time_t get_authtime_from_tkt(krb5_ticket *tkt)
1018 {
1019 #if defined(HAVE_KRB5_TKT_ENC_PART2)
1020         return tkt->enc_part2->times.authtime;
1021 #else
1022         return tkt->ticket.authtime;
1023 #endif
1024 }
1025
1026 #ifdef HAVE_KRB5_DECODE_AP_REQ  /* Heimdal */
1027 static int get_kvno_from_ap_req(krb5_ap_req *ap_req)
1028 {
1029 #ifdef HAVE_TICKET_POINTER_IN_KRB5_AP_REQ /* MIT */
1030         if (ap_req->ticket->enc_part.kvno)
1031                 return ap_req->ticket->enc_part.kvno;
1032 #else /* Heimdal */
1033         if (ap_req->ticket.enc_part.kvno) 
1034                 return *ap_req->ticket.enc_part.kvno;
1035 #endif
1036         return 0;
1037 }
1038
1039 static krb5_enctype get_enctype_from_ap_req(krb5_ap_req *ap_req)
1040 {
1041 #ifdef HAVE_ETYPE_IN_ENCRYPTEDDATA /* Heimdal */
1042         return ap_req->ticket.enc_part.etype;
1043 #else /* MIT */
1044         return ap_req->ticket->enc_part.enctype;
1045 #endif
1046 }
1047 #endif  /* HAVE_KRB5_DECODE_AP_REQ */
1048
1049 static krb5_error_code
1050 get_key_from_keytab(krb5_context context,
1051                     krb5_const_principal server,
1052                     krb5_enctype enctype,
1053                     krb5_kvno kvno,
1054                     krb5_keyblock **out_key)
1055 {
1056         krb5_keytab_entry entry;
1057         krb5_error_code ret;
1058         krb5_keytab keytab;
1059         char *name = NULL;
1060
1061         /* We have to open a new keytab handle here, as MIT does
1062            an implicit open/getnext/close on krb5_kt_get_entry. We
1063            may be in the middle of a keytab enumeration when this is
1064            called. JRA. */
1065
1066         ret = smb_krb5_open_keytab(context, NULL, False, &keytab);
1067         if (ret) {
1068                 DEBUG(1,("get_key_from_keytab: smb_krb5_open_keytab failed (%s)\n", error_message(ret)));
1069                 return ret;
1070         }
1071
1072         if ( DEBUGLEVEL >= 10 ) {
1073                 if (smb_krb5_unparse_name(context, server, &name) == 0) {
1074                         DEBUG(10,("get_key_from_keytab: will look for kvno %d, enctype %d and name: %s\n", 
1075                                 kvno, enctype, name));
1076                         SAFE_FREE(name);
1077                 }
1078         }
1079
1080         ret = krb5_kt_get_entry(context,
1081                                 keytab,
1082                                 server,
1083                                 kvno,
1084                                 enctype,
1085                                 &entry);
1086
1087         if (ret) {
1088                 DEBUG(0,("get_key_from_keytab: failed to retrieve key: %s\n", error_message(ret)));
1089                 goto out;
1090         }
1091
1092 #ifdef HAVE_KRB5_KEYTAB_ENTRY_KEYBLOCK /* Heimdal */
1093         ret = krb5_copy_keyblock(context, &entry.keyblock, out_key);
1094 #elif defined(HAVE_KRB5_KEYTAB_ENTRY_KEY) /* MIT */
1095         ret = krb5_copy_keyblock(context, &entry.key, out_key);
1096 #else
1097 #error UNKNOWN_KRB5_KEYTAB_ENTRY_FORMAT
1098 #endif
1099
1100         if (ret) {
1101                 DEBUG(0,("get_key_from_keytab: failed to copy key: %s\n", error_message(ret)));
1102                 goto out;
1103         }
1104                 
1105         smb_krb5_kt_free_entry(context, &entry);
1106         
1107 out:    
1108         krb5_kt_close(context, keytab);
1109         return ret;
1110 }
1111
1112 /* Prototypes */
1113
1114  krb5_error_code smb_krb5_get_keyinfo_from_ap_req(krb5_context context, 
1115                                                  const krb5_data *inbuf, 
1116                                                  krb5_kvno *kvno, 
1117                                                  krb5_enctype *enctype)
1118 {
1119 #ifdef HAVE_KRB5_DECODE_AP_REQ /* Heimdal */
1120         {
1121                 krb5_error_code ret;
1122                 krb5_ap_req ap_req;
1123                 
1124                 ret = krb5_decode_ap_req(context, inbuf, &ap_req);
1125                 if (ret)
1126                         return ret;
1127
1128                 *kvno = get_kvno_from_ap_req(&ap_req);
1129                 *enctype = get_enctype_from_ap_req(&ap_req);
1130
1131                 free_AP_REQ(&ap_req);
1132                 return 0;
1133         }
1134 #endif
1135
1136         /* Possibly not an appropriate error code. */
1137         return KRB5KDC_ERR_BADOPTION;
1138 }
1139
1140  krb5_error_code krb5_rd_req_return_keyblock_from_keytab(krb5_context context,
1141                                                         krb5_auth_context *auth_context,
1142                                                         const krb5_data *inbuf,
1143                                                         krb5_const_principal server,
1144                                                         krb5_keytab keytab,
1145                                                         krb5_flags *ap_req_options,
1146                                                         krb5_ticket **ticket, 
1147                                                         krb5_keyblock **keyblock)
1148 {
1149         krb5_error_code ret;
1150         krb5_kvno kvno;
1151         krb5_enctype enctype;
1152         krb5_keyblock *local_keyblock;
1153
1154         ret = krb5_rd_req(context, 
1155                           auth_context, 
1156                           inbuf, 
1157                           server, 
1158                           keytab, 
1159                           ap_req_options, 
1160                           ticket);
1161         if (ret) {
1162                 return ret;
1163         }
1164         
1165 #ifdef KRB5_TICKET_HAS_KEYINFO
1166         enctype = (*ticket)->enc_part.enctype;
1167         kvno = (*ticket)->enc_part.kvno;
1168 #else
1169         ret = smb_krb5_get_keyinfo_from_ap_req(context, inbuf, &kvno, &enctype);
1170         if (ret) {
1171                 return ret;
1172         }
1173 #endif
1174
1175         ret = get_key_from_keytab(context, 
1176                                   server,
1177                                   enctype,
1178                                   kvno,
1179                                   &local_keyblock);
1180         if (ret) {
1181                 DEBUG(0,("krb5_rd_req_return_keyblock_from_keytab: failed to call get_key_from_keytab\n"));
1182                 goto out;
1183         }
1184
1185 out:
1186         if (ret && local_keyblock != NULL) {
1187                 krb5_free_keyblock(context, local_keyblock);
1188         } else {
1189                 *keyblock = local_keyblock;
1190         }
1191
1192         return ret;
1193 }
1194
1195  krb5_error_code smb_krb5_parse_name_norealm(krb5_context context, 
1196                                             const char *name, 
1197                                             krb5_principal *principal)
1198 {
1199 #ifdef HAVE_KRB5_PARSE_NAME_NOREALM
1200         return smb_krb5_parse_name_norealm_conv(context, name, principal);
1201 #endif
1202
1203         /* we are cheating here because parse_name will in fact set the realm.
1204          * We don't care as the only caller of smb_krb5_parse_name_norealm
1205          * ignores the realm anyway when calling
1206          * smb_krb5_principal_compare_any_realm later - Guenther */
1207
1208         return smb_krb5_parse_name(context, name, principal);
1209 }
1210
1211  bool smb_krb5_principal_compare_any_realm(krb5_context context, 
1212                                           krb5_const_principal princ1, 
1213                                           krb5_const_principal princ2)
1214 {
1215 #ifdef HAVE_KRB5_PRINCIPAL_COMPARE_ANY_REALM
1216
1217         return krb5_principal_compare_any_realm(context, princ1, princ2);
1218
1219 /* krb5_princ_size is a macro in MIT */
1220 #elif defined(HAVE_KRB5_PRINC_SIZE) || defined(krb5_princ_size)
1221
1222         int i, len1, len2;
1223         const krb5_data *p1, *p2;
1224
1225         len1 = krb5_princ_size(context, princ1);
1226         len2 = krb5_princ_size(context, princ2);
1227
1228         if (len1 != len2)
1229                 return False;
1230
1231         for (i = 0; i < len1; i++) {
1232
1233                 p1 = krb5_princ_component(context, CONST_DISCARD(krb5_principal, princ1), i);
1234                 p2 = krb5_princ_component(context, CONST_DISCARD(krb5_principal, princ2), i);
1235
1236                 if (p1->length != p2->length || memcmp(p1->data, p2->data, p1->length))
1237                         return False;
1238         }
1239
1240         return True;
1241 #else
1242 #error NO_SUITABLE_PRINCIPAL_COMPARE_FUNCTION
1243 #endif
1244 }
1245
1246  krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,       /* FILE:/tmp/krb5cc_0 */
1247                                        const char *client_string,       /* gd@BER.SUSE.DE */
1248                                        const char *service_string,      /* krbtgt/BER.SUSE.DE@BER.SUSE.DE */
1249                                        time_t *expire_time)
1250 {
1251         krb5_error_code ret;
1252         krb5_context context = NULL;
1253         krb5_ccache ccache = NULL;
1254         krb5_principal client = NULL;
1255         krb5_creds creds, creds_in, *creds_out = NULL;
1256
1257         ZERO_STRUCT(creds);
1258         ZERO_STRUCT(creds_in);
1259
1260         initialize_krb5_error_table();
1261         ret = krb5_init_context(&context);
1262         if (ret) {
1263                 goto done;
1264         }
1265
1266         if (!ccache_string) {
1267                 ccache_string = krb5_cc_default_name(context);
1268         }
1269
1270         if (!ccache_string) {
1271                 ret = EINVAL;
1272                 goto done;
1273         }
1274
1275         DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
1276
1277         /* FIXME: we should not fall back to defaults */
1278         ret = krb5_cc_resolve(context, CONST_DISCARD(char *, ccache_string), &ccache);
1279         if (ret) {
1280                 goto done;
1281         }
1282
1283         if (client_string) {
1284                 ret = smb_krb5_parse_name(context, client_string, &client);
1285                 if (ret) {
1286                         goto done;
1287                 }
1288         } else {
1289                 ret = krb5_cc_get_principal(context, ccache, &client);
1290                 if (ret) {
1291                         goto done;
1292                 }
1293         }
1294
1295 #ifdef HAVE_KRB5_GET_RENEWED_CREDS      /* MIT */
1296         {
1297                 ret = krb5_get_renewed_creds(context, &creds, client, ccache, CONST_DISCARD(char *, service_string));
1298                 if (ret) {
1299                         DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
1300                         goto done;
1301                 }
1302         }
1303 #elif defined(HAVE_KRB5_GET_KDC_CRED)   /* Heimdal */
1304         {
1305                 krb5_kdc_flags flags;
1306                 krb5_realm *client_realm = NULL;
1307
1308                 ret = krb5_copy_principal(context, client, &creds_in.client);
1309                 if (ret) {
1310                         goto done;
1311                 }
1312
1313                 if (service_string) {
1314                         ret = smb_krb5_parse_name(context, service_string, &creds_in.server);
1315                         if (ret) { 
1316                                 goto done;
1317                         }
1318                 } else {
1319                         /* build tgt service by default */
1320                         client_realm = krb5_princ_realm(context, creds_in.client);
1321                         if (!client_realm) {
1322                                 ret = ENOMEM;
1323                                 goto done;
1324                         }
1325                         ret = krb5_make_principal(context, &creds_in.server, *client_realm, KRB5_TGS_NAME, *client_realm, NULL);
1326                         if (ret) {
1327                                 goto done;
1328                         }
1329                 }
1330
1331                 flags.i = 0;
1332                 flags.b.renewable = flags.b.renew = True;
1333
1334                 ret = krb5_get_kdc_cred(context, ccache, flags, NULL, NULL, &creds_in, &creds_out);
1335                 if (ret) {
1336                         DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
1337                         goto done;
1338                 }
1339
1340                 creds = *creds_out;
1341         }
1342 #else
1343 #error NO_SUITABLE_KRB5_TICKET_RENEW_FUNCTION_AVAILABLE
1344 #endif
1345
1346         /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
1347         ret = krb5_cc_initialize(context, ccache, client);
1348         if (ret) {
1349                 goto done;
1350         }
1351         
1352         ret = krb5_cc_store_cred(context, ccache, &creds);
1353
1354         if (expire_time) {
1355                 *expire_time = (time_t) creds.times.endtime;
1356         }
1357
1358 done:
1359         krb5_free_cred_contents(context, &creds_in);
1360
1361         if (creds_out) {
1362                 krb5_free_creds(context, creds_out);
1363         } else {
1364                 krb5_free_cred_contents(context, &creds);
1365         }
1366
1367         if (client) {
1368                 krb5_free_principal(context, client);
1369         }
1370         if (ccache) {
1371                 krb5_cc_close(context, ccache);
1372         }
1373         if (context) {
1374                 krb5_free_context(context);
1375         }
1376
1377         return ret;
1378 }
1379
1380  krb5_error_code smb_krb5_free_addresses(krb5_context context, smb_krb5_addresses *addr)
1381 {
1382         krb5_error_code ret = 0;
1383         if (addr == NULL) {
1384                 return ret;
1385         }
1386 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1387         krb5_free_addresses(context, addr->addrs);
1388 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1389         ret = krb5_free_addresses(context, addr->addrs);
1390         SAFE_FREE(addr->addrs);
1391 #endif
1392         SAFE_FREE(addr);
1393         addr = NULL;
1394         return ret;
1395 }
1396
1397  krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr)
1398 {
1399         krb5_error_code ret = 0;
1400         nstring buf;
1401 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1402         krb5_address **addrs = NULL;
1403 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1404         krb5_addresses *addrs = NULL;
1405 #endif
1406
1407         *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1408         if (*kerb_addr == NULL) {
1409                 return ENOMEM;
1410         }
1411
1412         put_name(buf, global_myname(), ' ', 0x20);
1413
1414 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1415         {
1416                 int num_addr = 2;
1417
1418                 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1419                 if (addrs == NULL) {
1420                         SAFE_FREE(kerb_addr);
1421                         return ENOMEM;
1422                 }
1423
1424                 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1425
1426                 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1427                 if (addrs[0] == NULL) {
1428                         SAFE_FREE(addrs);
1429                         SAFE_FREE(kerb_addr);
1430                         return ENOMEM;
1431                 }
1432
1433                 addrs[0]->magic = KV5M_ADDRESS;
1434                 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1435                 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1436                 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1437                 if (addrs[0]->contents == NULL) {
1438                         SAFE_FREE(addrs[0]);
1439                         SAFE_FREE(addrs);
1440                         SAFE_FREE(kerb_addr);
1441                         return ENOMEM;
1442                 }
1443
1444                 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1445
1446                 addrs[1] = NULL;
1447         }
1448 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1449         {
1450                 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1451                 if (addrs == NULL) {
1452                         SAFE_FREE(kerb_addr);
1453                         return ENOMEM;
1454                 }
1455
1456                 memset(addrs, 0, sizeof(krb5_addresses));
1457
1458                 addrs->len = 1;
1459                 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1460                 if (addrs->val == NULL) {
1461                         SAFE_FREE(addrs);
1462                         SAFE_FREE(kerb_addr);
1463                         return ENOMEM;
1464                 }
1465
1466                 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1467                 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1468                 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1469                 if (addrs->val[0].address.data == NULL) {
1470                         SAFE_FREE(addrs->val);
1471                         SAFE_FREE(addrs);
1472                         SAFE_FREE(kerb_addr);
1473                         return ENOMEM;
1474                 }
1475
1476                 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1477         }
1478 #else
1479 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1480 #endif
1481         (*kerb_addr)->addrs = addrs;
1482
1483         return ret;
1484 }
1485
1486  void smb_krb5_free_error(krb5_context context, krb5_error *krberror)
1487 {
1488 #ifdef HAVE_KRB5_FREE_ERROR_CONTENTS /* Heimdal */
1489         krb5_free_error_contents(context, krberror);
1490 #else /* MIT */
1491         krb5_free_error(context, krberror);
1492 #endif
1493 }
1494
1495  krb5_error_code handle_krberror_packet(krb5_context context,
1496                                         krb5_data *packet)
1497 {
1498         krb5_error_code ret;
1499         bool got_error_code = False;
1500
1501         DEBUG(10,("handle_krberror_packet: got error packet\n"));
1502         
1503 #ifdef HAVE_E_DATA_POINTER_IN_KRB5_ERROR /* Heimdal */
1504         {
1505                 krb5_error krberror;
1506
1507                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1508                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1509                                 error_message(ret)));
1510                         return ret;
1511                 }
1512
1513                 if (krberror.e_data == NULL || krberror.e_data->data == NULL) {
1514                         ret = (krb5_error_code) krberror.error_code;
1515                         got_error_code = True;
1516                 }
1517
1518                 smb_krb5_free_error(context, &krberror);
1519         }
1520 #else /* MIT */
1521         {
1522                 krb5_error *krberror;
1523
1524                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1525                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1526                                 error_message(ret)));
1527                         return ret;
1528                 }
1529
1530                 if (krberror->e_data.data == NULL) {
1531                         ret = ERROR_TABLE_BASE_krb5 + (krb5_error_code) krberror->error;
1532                         got_error_code = True;
1533                 }
1534                 smb_krb5_free_error(context, krberror);
1535         }
1536 #endif
1537         if (got_error_code) {
1538                 DEBUG(5,("handle_krberror_packet: got KERBERR from kpasswd: %s (%d)\n", 
1539                         error_message(ret), ret));
1540         }
1541         return ret;
1542 }
1543
1544  krb5_error_code smb_krb5_get_init_creds_opt_alloc(krb5_context context,
1545                                             krb5_get_init_creds_opt **opt)
1546 {
1547 #ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_ALLOC
1548         /* Heimdal or modern MIT version */
1549         return krb5_get_init_creds_opt_alloc(context, opt);
1550 #else
1551         /* Historical MIT version */
1552         krb5_get_init_creds_opt *my_opt;
1553
1554         *opt = NULL;
1555
1556         if ((my_opt = SMB_MALLOC_P(krb5_get_init_creds_opt)) == NULL) {
1557                 return ENOMEM;
1558         }
1559
1560         krb5_get_init_creds_opt_init(my_opt);
1561
1562         *opt =  my_opt;
1563         return 0;
1564 #endif /* HAVE_KRB5_GET_INIT_CREDS_OPT_ALLOC  */
1565 }
1566
1567  void smb_krb5_get_init_creds_opt_free(krb5_context context,
1568                                 krb5_get_init_creds_opt *opt)
1569 {
1570 #ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_FREE
1571
1572 #ifdef KRB5_CREDS_OPT_FREE_REQUIRES_CONTEXT
1573         /* Modern MIT or Heimdal version */
1574         krb5_get_init_creds_opt_free(context, opt);
1575 #else
1576         /* Heimdal version */
1577         krb5_get_init_creds_opt_free(opt);
1578 #endif /* KRB5_CREDS_OPT_FREE_REQUIRES_CONTEXT */
1579
1580 #else /* HAVE_KRB5_GET_INIT_CREDS_OPT_FREE */
1581         /* Historical MIT version */
1582         SAFE_FREE(opt);
1583         opt = NULL;
1584 #endif /* HAVE_KRB5_GET_INIT_CREDS_OPT_FREE */
1585 }
1586
1587  krb5_enctype smb_get_enctype_from_kt_entry(const krb5_keytab_entry *kt_entry)
1588 {
1589 #ifdef HAVE_KRB5_KEYTAB_ENTRY_KEY               /* MIT */
1590         return kt_entry->key.enctype;
1591 #elif defined(HAVE_KRB5_KEYTAB_ENTRY_KEYBLOCK)  /* Heimdal */
1592         return kt_entry->keyblock.keytype;
1593 #else
1594 #error UNKNOWN_KRB5_KEYTAB_ENTRY_KEYBLOCK_FORMAT
1595 #endif
1596 }
1597
1598
1599 /* caller needs to free etype_s */
1600  krb5_error_code smb_krb5_enctype_to_string(krb5_context context, 
1601                                             krb5_enctype enctype, 
1602                                             char **etype_s)
1603 {
1604 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1605         return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1606 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1607         char buf[256];
1608         krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1609         if (ret) {
1610                 return ret;
1611         }
1612         *etype_s = SMB_STRDUP(buf);
1613         if (!*etype_s) {
1614                 return ENOMEM;
1615         }
1616         return ret;
1617 #else
1618 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1619 #endif
1620 }
1621
1622  krb5_error_code smb_krb5_mk_error(krb5_context context,
1623                                 krb5_error_code error_code,
1624                                 const krb5_principal server,
1625                                 krb5_data *reply)
1626 {
1627 #ifdef HAVE_SHORT_KRB5_MK_ERROR_INTERFACE /* MIT */
1628         /*
1629          * The MIT interface is *terrible*.
1630          * We have to construct this ourselves...
1631          */
1632         krb5_error e;
1633
1634         memset(&e, 0, sizeof(e));
1635         krb5_us_timeofday(context, &e.stime, &e.susec);
1636         e.server = server;
1637 #if defined(krb5_err_base)
1638         e.error = error_code - krb5_err_base;
1639 #elif defined(ERROR_TABLE_BASE_krb5)
1640         e.error = error_code - ERROR_TABLE_BASE_krb5;
1641 #else
1642         e.error = error_code; /* Almost certainly wrong, but what can we do... ? */
1643 #endif
1644
1645         return krb5_mk_error(context, &e, reply);
1646 #else /* Heimdal. */
1647         return krb5_mk_error(context,
1648                                 error_code,
1649                                 NULL,
1650                                 NULL, /* e_data */
1651                                 NULL,
1652                                 server,
1653                                 NULL,
1654                                 NULL,
1655                                 reply);
1656 #endif
1657 }
1658
1659 /**********************************************************************
1660  * Open a krb5 keytab with flags, handles readonly or readwrite access and
1661  * allows to process non-default keytab names.
1662  * @param context krb5_context 
1663  * @param keytab_name_req string
1664  * @param write_access bool if writable keytab is required
1665  * @param krb5_keytab pointer to krb5_keytab (close with krb5_kt_close())
1666  * @return krb5_error_code
1667 **********************************************************************/
1668
1669 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1670 #ifndef MAX_KEYTAB_NAME_LEN
1671 #define MAX_KEYTAB_NAME_LEN 1100
1672 #endif
1673
1674  krb5_error_code smb_krb5_open_keytab(krb5_context context,
1675                                       const char *keytab_name_req,
1676                                       bool write_access,
1677                                       krb5_keytab *keytab)
1678 {
1679         krb5_error_code ret = 0;
1680         TALLOC_CTX *mem_ctx;
1681         char keytab_string[MAX_KEYTAB_NAME_LEN];
1682         char *kt_str = NULL;
1683         bool found_valid_name = False;
1684         const char *pragma = "FILE";
1685         const char *tmp = NULL;
1686
1687         if (!write_access && !keytab_name_req) {
1688                 /* caller just wants to read the default keytab readonly, so be it */
1689                 return krb5_kt_default(context, keytab);
1690         }
1691
1692         mem_ctx = talloc_init("smb_krb5_open_keytab");
1693         if (!mem_ctx) {
1694                 return ENOMEM;
1695         }
1696
1697 #ifdef HAVE_WRFILE_KEYTAB 
1698         if (write_access) {
1699                 pragma = "WRFILE";
1700         }
1701 #endif
1702
1703         if (keytab_name_req) {
1704
1705                 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1706                         ret = KRB5_CONFIG_NOTENUFSPACE;
1707                         goto out;
1708                 }
1709
1710                 if ((strncmp(keytab_name_req, "WRFILE:/", 8) == 0) || 
1711                     (strncmp(keytab_name_req, "FILE:/", 6) == 0)) {
1712                         tmp = keytab_name_req;
1713                         goto resolve;
1714                 }
1715
1716                 if (keytab_name_req[0] != '/') {
1717                         ret = KRB5_KT_BADNAME;
1718                         goto out;
1719                 }
1720
1721                 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1722                 if (!tmp) {
1723                         ret = ENOMEM;
1724                         goto out;
1725                 }
1726
1727                 goto resolve;
1728         }
1729
1730         /* we need to handle more complex keytab_strings, like:
1731          * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1732
1733         ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1734         if (ret) {
1735                 goto out;
1736         }
1737
1738         DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1739
1740         tmp = talloc_strdup(mem_ctx, keytab_string);
1741         if (!tmp) {
1742                 ret = ENOMEM;
1743                 goto out;
1744         }
1745
1746         if (strncmp(tmp, "ANY:", 4) == 0) {
1747                 tmp += 4;
1748         }
1749
1750         memset(&keytab_string, '\0', sizeof(keytab_string));
1751
1752         while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1753                 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1754                         found_valid_name = True;
1755                         tmp = kt_str;
1756                         tmp += 7;
1757                 }
1758
1759                 if (strncmp(kt_str, "FILE:", 5) == 0) {
1760                         found_valid_name = True;
1761                         tmp = kt_str;
1762                         tmp += 5;
1763                 }
1764
1765                 if (found_valid_name) {
1766                         if (tmp[0] != '/') {
1767                                 ret = KRB5_KT_BADNAME;
1768                                 goto out;
1769                         }
1770
1771                         tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1772                         if (!tmp) {
1773                                 ret = ENOMEM;
1774                                 goto out;
1775                         }
1776                         break;
1777                 }
1778         }
1779
1780         if (!found_valid_name) {
1781                 ret = KRB5_KT_UNKNOWN_TYPE;
1782                 goto out;
1783         }
1784
1785  resolve:
1786         DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1787         ret = krb5_kt_resolve(context, tmp, keytab);
1788
1789  out:
1790         TALLOC_FREE(mem_ctx);
1791         return ret;
1792 }
1793
1794 krb5_error_code smb_krb5_keytab_name(TALLOC_CTX *mem_ctx,
1795                                      krb5_context context,
1796                                      krb5_keytab keytab,
1797                                      const char **keytab_name)
1798 {
1799         char keytab_string[MAX_KEYTAB_NAME_LEN];
1800         krb5_error_code ret = 0;
1801
1802         ret = krb5_kt_get_name(context, keytab,
1803                                keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1804         if (ret) {
1805                 return ret;
1806         }
1807
1808         *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1809         if (!*keytab_name) {
1810                 return ENOMEM;
1811         }
1812
1813         return ret;
1814 }
1815
1816 #if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_FWD_TGT_CREDS) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY)
1817 /**************************************************************
1818 Routine: ads_krb5_get_fwd_ticket
1819  Description:
1820     When a service ticket is flagged as trusted
1821     for delegation we should provide a forwardable
1822     ticket so that the remote host can act on our
1823     behalf.  This is done by taking the 2nd forwardable
1824     TGT and storing it in the GSS-API authenticator
1825     "checksum".  This routine will populate
1826     the krb5_data authenticator with this TGT.
1827  Parameters:
1828     krb5_context context: The kerberos context for this authentication.
1829     krb5_auth_context:    The authentication context.
1830     krb5_creds *credsp:   The ticket credentials (AS-REP).
1831     krb5_ccache ccache:   The credentials cache.
1832     krb5_data &authenticator: The checksum field that will store the TGT, and
1833      authenticator.data must be freed by the caller.
1834
1835  Returns:
1836     krb5_error_code: 0 if no errors, otherwise set.
1837 **************************************************************/
1838
1839 static krb5_error_code ads_krb5_get_fwd_ticket( krb5_context context,
1840                                          krb5_auth_context *auth_context,
1841                                          krb5_creds *credsp,
1842                                          krb5_ccache ccache,
1843                                          krb5_data *authenticator)
1844 {
1845         krb5_data fwdData;
1846         krb5_error_code retval = 0;
1847         char *pChksum = NULL;
1848         char *p = NULL;
1849
1850         ZERO_STRUCT(fwdData);
1851         ZERO_STRUCTP(authenticator);
1852
1853         retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
1854                                 *auth_context,  /* Authentication context [in] */
1855                                 CONST_DISCARD(char *, KRB5_TGS_NAME),  /* Ticket service name ("krbtgt") [in] */
1856                                 credsp->client, /* Client principal for the tgt [in] */
1857                                 credsp->server, /* Server principal for the tgt [in] */
1858                                 ccache,         /* Credential cache to use for storage [in] */
1859                                 1,              /* Turn on for "Forwardable ticket" [in] */
1860                                 &fwdData );     /* Resulting response [out] */
1861
1862
1863         if (retval) {
1864                 DEBUG(1,("ads_krb5_get_fwd_ticket: krb5_fwd_tgt_creds failed (%s)\n", 
1865                         error_message(retval)));
1866                 goto out;
1867         }
1868
1869         if ((unsigned int)GSSAPI_CHECKSUM_SIZE + (unsigned int)fwdData.length <
1870                 (unsigned int)GSSAPI_CHECKSUM_SIZE) {
1871                 retval = EINVAL;
1872                 goto out;
1873         }
1874
1875         /* We're going to allocate a gssChecksum structure with a little
1876            extra data the length of the kerberos credentials length
1877            (APPLICATION 22) so that we can pack it on the end of the structure.
1878         */
1879
1880         pChksum = (char *)SMB_MALLOC(GSSAPI_CHECKSUM_SIZE + fwdData.length );
1881         if (!pChksum) {
1882                 retval = ENOMEM;
1883                 goto out;
1884         }
1885
1886         p = pChksum;
1887
1888         SIVAL(p, 0, GSSAPI_BNDLENGTH);
1889         p += 4;
1890
1891         /* Zero out the bindings fields */
1892         memset(p, '\0', GSSAPI_BNDLENGTH );
1893         p += GSSAPI_BNDLENGTH;
1894
1895         SIVAL(p, 0, GSS_C_DELEG_FLAG );
1896         p += 4;
1897         SSVAL(p, 0, 1 );
1898         p += 2;
1899         SSVAL(p, 0, fwdData.length );
1900         p += 2;
1901
1902         /* Migrate the kerberos KRB_CRED data to the checksum delegation */
1903         memcpy(p, fwdData.data, fwdData.length );
1904         p += fwdData.length;
1905
1906         /* We need to do this in order to allow our GSS-API  */
1907         retval = krb5_auth_con_set_req_cksumtype( context, *auth_context, GSSAPI_CHECKSUM );
1908         if (retval) {
1909                 goto out;
1910         }
1911
1912         /* We now have a service ticket, now turn it into an AP-REQ. */
1913         authenticator->length = ntohs(fwdData.length + GSSAPI_CHECKSUM_SIZE);
1914
1915         /* Caller should call free() when they're done with this. */
1916         authenticator->data = (char *)pChksum;
1917
1918   out:
1919
1920         /* Remove that input data, we never needed it anyway. */
1921         if (fwdData.length > 0) {
1922                 krb5_free_data_contents( context, &fwdData );
1923         }
1924
1925         return retval;
1926 }
1927 #endif
1928
1929 #else /* HAVE_KRB5 */
1930  /* this saves a few linking headaches */
1931  int cli_krb5_get_ticket(const char *principal, time_t time_offset, 
1932                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5, uint32 extra_ap_opts,
1933                         const char *ccname, time_t *tgs_expire) 
1934 {
1935          DEBUG(0,("NO KERBEROS SUPPORT\n"));
1936          return 1;
1937 }
1938
1939 #endif