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