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