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