r23609: Removing more redundant codepaths out of smb_krb5_renew_ticket().
[sfrench/samba-autobuild/.git] / source / 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
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 2 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, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #define KRB5_PRIVATE    1       /* this file uses PRIVATE interfaces! */
25 #define KRB5_DEPRECATED 1       /* this file uses DEPRECATED interfaces! */
26
27 #include "includes.h"
28
29 #ifdef HAVE_KRB5
30
31 #ifdef HAVE_KRB5_KEYBLOCK_KEYVALUE /* Heimdal */
32 #define KRB5_KEY_TYPE(k)        ((k)->keytype) 
33 #define KRB5_KEY_LENGTH(k)      ((k)->keyvalue.length)
34 #define KRB5_KEY_DATA(k)        ((k)->keyvalue.data)
35 #else /* MIT */
36 #define KRB5_KEY_TYPE(k)        ((k)->enctype)
37 #define KRB5_KEY_LENGTH(k)      ((k)->length)
38 #define KRB5_KEY_DATA(k)        ((k)->contents)
39 #endif /* HAVE_KRB5_KEYBLOCK_KEYVALUE */
40
41 /**************************************************************
42  Wrappers around kerberos string functions that convert from
43  utf8 -> unix charset and vica versa.
44 **************************************************************/
45
46 /**************************************************************
47  krb5_parse_name that takes a UNIX charset.
48 **************************************************************/
49
50  krb5_error_code smb_krb5_parse_name(krb5_context context,
51                                 const char *name, /* in unix charset */
52                                 krb5_principal *principal)
53 {
54         krb5_error_code ret;
55         char *utf8_name;
56
57         if (push_utf8_allocate(&utf8_name, name) == (size_t)-1) {
58                 return ENOMEM;
59         }
60
61         ret = krb5_parse_name(context, utf8_name, principal);
62         SAFE_FREE(utf8_name);
63         return ret;
64 }
65
66 #ifdef HAVE_KRB5_PARSE_NAME_NOREALM
67 /**************************************************************
68  krb5_parse_name_norealm that takes a UNIX charset.
69 **************************************************************/
70
71 static krb5_error_code smb_krb5_parse_name_norealm_conv(krb5_context context,
72                                 const char *name, /* in unix charset */
73                                 krb5_principal *principal)
74 {
75         krb5_error_code ret;
76         char *utf8_name;
77
78         *principal = NULL;
79         if (push_utf8_allocate(&utf8_name, name) == (size_t)-1) {
80                 return ENOMEM;
81         }
82
83         ret = krb5_parse_name_norealm(context, utf8_name, principal);
84         SAFE_FREE(utf8_name);
85         return ret;
86 }
87 #endif
88
89 /**************************************************************
90  krb5_parse_name that returns a UNIX charset name. Must
91  be freed with normal free() call.
92 **************************************************************/
93
94  krb5_error_code smb_krb5_unparse_name(krb5_context context,
95                                         krb5_const_principal principal,
96                                         char **unix_name)
97 {
98         krb5_error_code ret;
99         char *utf8_name;
100
101         *unix_name = NULL;
102         ret = krb5_unparse_name(context, principal, &utf8_name);
103         if (ret) {
104                 return ret;
105         }
106
107         if (pull_utf8_allocate(unix_name, utf8_name)==-1) {
108                 krb5_free_unparsed_name(context, utf8_name);
109                 return ENOMEM;
110         }
111         krb5_free_unparsed_name(context, utf8_name);
112         return 0;
113 }
114
115 #ifndef HAVE_KRB5_SET_REAL_TIME
116 /*
117  * This function is not in the Heimdal mainline.
118  */
119  krb5_error_code krb5_set_real_time(krb5_context context, int32_t seconds, int32_t microseconds)
120 {
121         krb5_error_code ret;
122         int32_t sec, usec;
123
124         ret = krb5_us_timeofday(context, &sec, &usec);
125         if (ret)
126                 return ret;
127
128         context->kdc_sec_offset = seconds - sec;
129         context->kdc_usec_offset = microseconds - usec;
130
131         return 0;
132 }
133 #endif
134
135 #if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
136
137 #if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)
138
139 /* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
140  * to krb5_set_default_tgs_ktypes. See
141  *         http://lists.samba.org/archive/samba-technical/2006-July/048271.html
142  *
143  * If the MIT libraries are not exporting internal symbols, we will end up in
144  * this branch, which is correct. Otherwise we will continue to use the
145  * internal symbol
146  */
147  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
148 {
149     return krb5_set_default_tgs_enctypes(ctx, enc);
150 }
151
152 #elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)
153
154 /* Heimdal */
155  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
156 {
157         return krb5_set_default_in_tkt_etypes(ctx, enc);
158 }
159
160 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */
161
162 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */
163
164 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
165 /* HEIMDAL */
166  void setup_kaddr( krb5_address *pkaddr, struct sockaddr *paddr)
167 {
168         pkaddr->addr_type = KRB5_ADDRESS_INET;
169         pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
170         pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
171 }
172 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
173 /* MIT */
174  void setup_kaddr( krb5_address *pkaddr, struct sockaddr *paddr)
175 {
176         pkaddr->addrtype = ADDRTYPE_INET;
177         pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
178         pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
179 }
180 #else
181 #error UNKNOWN_ADDRTYPE
182 #endif
183
184 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_USE_ENCTYPE) && defined(HAVE_KRB5_STRING_TO_KEY) && defined(HAVE_KRB5_ENCRYPT_BLOCK)
185  int create_kerberos_key_from_string_direct(krb5_context context,
186                                         krb5_principal host_princ,
187                                         krb5_data *password,
188                                         krb5_keyblock *key,
189                                         krb5_enctype enctype)
190 {
191         int ret;
192         krb5_data salt;
193         krb5_encrypt_block eblock;
194
195         ret = krb5_principal2salt(context, host_princ, &salt);
196         if (ret) {
197                 DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
198                 return ret;
199         }
200         krb5_use_enctype(context, &eblock, enctype);
201         ret = krb5_string_to_key(context, &eblock, key, password, &salt);
202         SAFE_FREE(salt.data);
203         return ret;
204 }
205 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
206  int create_kerberos_key_from_string_direct(krb5_context context,
207                                         krb5_principal host_princ,
208                                         krb5_data *password,
209                                         krb5_keyblock *key,
210                                         krb5_enctype enctype)
211 {
212         int ret;
213         krb5_salt salt;
214
215         ret = krb5_get_pw_salt(context, host_princ, &salt);
216         if (ret) {
217                 DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
218                 return ret;
219         }
220         
221         ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, salt, key);
222         krb5_free_salt(context, salt);
223         return ret;
224 }
225 #else
226 #error UNKNOWN_CREATE_KEY_FUNCTIONS
227 #endif
228
229  int create_kerberos_key_from_string(krb5_context context,
230                                         krb5_principal host_princ,
231                                         krb5_data *password,
232                                         krb5_keyblock *key,
233                                         krb5_enctype enctype)
234 {
235         krb5_principal salt_princ = NULL;
236         int ret;
237         /*
238          * Check if we've determined that the KDC is salting keys for this
239          * principal/enctype in a non-obvious way.  If it is, try to match
240          * its behavior.
241          */
242         salt_princ = kerberos_fetch_salt_princ_for_host_princ(context, host_princ, enctype);
243         ret = create_kerberos_key_from_string_direct(context, salt_princ ? salt_princ : host_princ, password, key, enctype);
244         if (salt_princ) {
245                 krb5_free_principal(context, salt_princ);
246         }
247         return ret;
248 }
249
250 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
251  krb5_error_code get_kerberos_allowed_etypes(krb5_context context, 
252                                             krb5_enctype **enctypes)
253 {
254         return krb5_get_permitted_enctypes(context, enctypes);
255 }
256 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
257  krb5_error_code get_kerberos_allowed_etypes(krb5_context context, 
258                                             krb5_enctype **enctypes)
259 {
260         return krb5_get_default_in_tkt_etypes(context, enctypes);
261 }
262 #else
263 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
264 #endif
265
266 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
267  krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
268                                         krb5_auth_context auth_context,
269                                         krb5_keyblock *keyblock)
270 {
271         return krb5_auth_con_setkey(context, auth_context, keyblock);
272 }
273 #endif
274
275 BOOL unwrap_edata_ntstatus(TALLOC_CTX *mem_ctx, 
276                            DATA_BLOB *edata, 
277                            DATA_BLOB *edata_out)
278 {
279         DATA_BLOB edata_contents;
280         ASN1_DATA data;
281         int edata_type;
282
283         if (!edata->length) {
284                 return False;
285         }
286
287         asn1_load(&data, *edata);
288         asn1_start_tag(&data, ASN1_SEQUENCE(0));
289         asn1_start_tag(&data, ASN1_CONTEXT(1));
290         asn1_read_Integer(&data, &edata_type);
291
292         if (edata_type != KRB5_PADATA_PW_SALT) {
293                 DEBUG(0,("edata is not of required type %d but of type %d\n", 
294                         KRB5_PADATA_PW_SALT, edata_type));
295                 asn1_free(&data);
296                 return False;
297         }
298         
299         asn1_start_tag(&data, ASN1_CONTEXT(2));
300         asn1_read_OctetString(&data, &edata_contents);
301         asn1_end_tag(&data);
302         asn1_end_tag(&data);
303         asn1_end_tag(&data);
304         asn1_free(&data);
305
306         *edata_out = data_blob_talloc(mem_ctx, edata_contents.data, edata_contents.length);
307
308         data_blob_free(&edata_contents);
309
310         return True;
311 }
312
313
314 BOOL unwrap_pac(TALLOC_CTX *mem_ctx, DATA_BLOB *auth_data, DATA_BLOB *unwrapped_pac_data)
315 {
316         DATA_BLOB pac_contents;
317         ASN1_DATA data;
318         int data_type;
319
320         if (!auth_data->length) {
321                 return False;
322         }
323
324         asn1_load(&data, *auth_data);
325         asn1_start_tag(&data, ASN1_SEQUENCE(0));
326         asn1_start_tag(&data, ASN1_SEQUENCE(0));
327         asn1_start_tag(&data, ASN1_CONTEXT(0));
328         asn1_read_Integer(&data, &data_type);
329         
330         if (data_type != KRB5_AUTHDATA_WIN2K_PAC ) {
331                 DEBUG(10,("authorization data is not a Windows PAC (type: %d)\n", data_type));
332                 asn1_free(&data);
333                 return False;
334         }
335         
336         asn1_end_tag(&data);
337         asn1_start_tag(&data, ASN1_CONTEXT(1));
338         asn1_read_OctetString(&data, &pac_contents);
339         asn1_end_tag(&data);
340         asn1_end_tag(&data);
341         asn1_end_tag(&data);
342         asn1_free(&data);
343
344         *unwrapped_pac_data = data_blob_talloc(mem_ctx, pac_contents.data, pac_contents.length);
345
346         data_blob_free(&pac_contents);
347
348         return True;
349 }
350
351  BOOL get_auth_data_from_tkt(TALLOC_CTX *mem_ctx, DATA_BLOB *auth_data, krb5_ticket *tkt)
352 {
353         DATA_BLOB auth_data_wrapped;
354         BOOL got_auth_data_pac = False;
355         int i;
356         
357 #if defined(HAVE_KRB5_TKT_ENC_PART2)
358         if (tkt->enc_part2 && tkt->enc_part2->authorization_data && 
359             tkt->enc_part2->authorization_data[0] && 
360             tkt->enc_part2->authorization_data[0]->length)
361         {
362                 for (i = 0; tkt->enc_part2->authorization_data[i] != NULL; i++) {
363                 
364                         if (tkt->enc_part2->authorization_data[i]->ad_type != 
365                             KRB5_AUTHDATA_IF_RELEVANT) {
366                                 DEBUG(10,("get_auth_data_from_tkt: ad_type is %d\n", 
367                                         tkt->enc_part2->authorization_data[i]->ad_type));
368                                 continue;
369                         }
370
371                         auth_data_wrapped = data_blob(tkt->enc_part2->authorization_data[i]->contents,
372                                                       tkt->enc_part2->authorization_data[i]->length);
373
374                         /* check if it is a PAC */
375                         got_auth_data_pac = unwrap_pac(mem_ctx, &auth_data_wrapped, auth_data);
376                         data_blob_free(&auth_data_wrapped);
377                         
378                         if (!got_auth_data_pac) {
379                                 continue;
380                         }
381                 }
382
383                 return got_auth_data_pac;
384         }
385                 
386 #else
387         if (tkt->ticket.authorization_data && 
388             tkt->ticket.authorization_data->len)
389         {
390                 for (i = 0; i < tkt->ticket.authorization_data->len; i++) {
391                         
392                         if (tkt->ticket.authorization_data->val[i].ad_type != 
393                             KRB5_AUTHDATA_IF_RELEVANT) {
394                                 DEBUG(10,("get_auth_data_from_tkt: ad_type is %d\n", 
395                                         tkt->ticket.authorization_data->val[i].ad_type));
396                                 continue;
397                         }
398
399                         auth_data_wrapped = data_blob(tkt->ticket.authorization_data->val[i].ad_data.data,
400                                                       tkt->ticket.authorization_data->val[i].ad_data.length);
401
402                         /* check if it is a PAC */
403                         got_auth_data_pac = unwrap_pac(mem_ctx, &auth_data_wrapped, auth_data);
404                         data_blob_free(&auth_data_wrapped);
405                         
406                         if (!got_auth_data_pac) {
407                                 continue;
408                         }
409                 }
410
411                 return got_auth_data_pac;
412         }
413 #endif
414         return False;
415 }
416
417  krb5_const_principal get_principal_from_tkt(krb5_ticket *tkt)
418 {
419 #if defined(HAVE_KRB5_TKT_ENC_PART2)
420         return tkt->enc_part2->client;
421 #else
422         return tkt->client;
423 #endif
424 }
425
426 #if !defined(HAVE_KRB5_LOCATE_KDC)
427
428 /* krb5_locate_kdc is an internal MIT symbol. MIT are not yet willing to commit
429  * to a public interface for this functionality, so we have to be able to live
430  * without it if the MIT libraries are hiding their internal symbols.
431  */
432
433 #if defined(KRB5_KRBHST_INIT)
434 /* Heimdal */
435  krb5_error_code smb_krb5_locate_kdc(krb5_context ctx, const krb5_data *realm, struct sockaddr **addr_pp, int *naddrs, int get_masters)
436 {
437         krb5_krbhst_handle hnd;
438         krb5_krbhst_info *hinfo;
439         krb5_error_code rc;
440         int num_kdcs, i;
441         struct sockaddr *sa;
442         struct addrinfo *ai;
443
444         *addr_pp = NULL;
445         *naddrs = 0;
446
447         rc = krb5_krbhst_init(ctx, realm->data, KRB5_KRBHST_KDC, &hnd);
448         if (rc) {
449                 DEBUG(0, ("smb_krb5_locate_kdc: krb5_krbhst_init failed (%s)\n", error_message(rc)));
450                 return rc;
451         }
452
453         for ( num_kdcs = 0; (rc = krb5_krbhst_next(ctx, hnd, &hinfo) == 0); num_kdcs++)
454                 ;
455
456         krb5_krbhst_reset(ctx, hnd);
457
458         if (!num_kdcs) {
459                 DEBUG(0, ("smb_krb5_locate_kdc: zero kdcs found !\n"));
460                 krb5_krbhst_free(ctx, hnd);
461                 return -1;
462         }
463
464         sa = SMB_MALLOC_ARRAY( struct sockaddr, num_kdcs );
465         if (!sa) {
466                 DEBUG(0, ("smb_krb5_locate_kdc: malloc failed\n"));
467                 krb5_krbhst_free(ctx, hnd);
468                 naddrs = 0;
469                 return -1;
470         }
471
472         memset(sa, '\0', sizeof(struct sockaddr) * num_kdcs );
473
474         for (i = 0; i < num_kdcs && (rc = krb5_krbhst_next(ctx, hnd, &hinfo) == 0); i++) {
475
476 #if defined(HAVE_KRB5_KRBHST_GET_ADDRINFO)
477                 rc = krb5_krbhst_get_addrinfo(ctx, hinfo, &ai);
478                 if (rc) {
479                         DEBUG(0,("krb5_krbhst_get_addrinfo failed: %s\n", error_message(rc)));
480                         continue;
481                 }
482 #endif
483                 if (hinfo->ai && hinfo->ai->ai_family == AF_INET) 
484                         memcpy(&sa[i], hinfo->ai->ai_addr, sizeof(struct sockaddr));
485         }
486
487         krb5_krbhst_free(ctx, hnd);
488
489         *naddrs = num_kdcs;
490         *addr_pp = sa;
491         return 0;
492 }
493
494 #else /* ! defined(KRB5_KRBHST_INIT) */
495
496  krb5_error_code smb_krb5_locate_kdc(krb5_context ctx, const krb5_data *realm,
497                 struct sockaddr **addr_pp, int *naddrs, int get_masters)
498 {
499         DEBUG(0, ("unable to explicitly locate the KDC on this platform\n"));
500         return KRB5_KDC_UNREACH;
501 }
502
503 #endif /* KRB5_KRBHST_INIT */
504
505 #else /* ! HAVE_KRB5_LOCATE_KDC */
506
507  krb5_error_code smb_krb5_locate_kdc(krb5_context ctx, const krb5_data *realm,
508                 struct sockaddr **addr_pp, int *naddrs, int get_masters)
509 {
510         return krb5_locate_kdc(ctx, realm, addr_pp, naddrs, get_masters);
511 }
512
513 #endif /* HAVE_KRB5_LOCATE_KDC */
514
515 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
516  void krb5_free_unparsed_name(krb5_context context, char *val)
517 {
518         SAFE_FREE(val);
519 }
520 #endif
521
522  void kerberos_free_data_contents(krb5_context context, krb5_data *pdata)
523 {
524 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
525         if (pdata->data) {
526                 krb5_free_data_contents(context, pdata);
527         }
528 #else
529         SAFE_FREE(pdata->data);
530 #endif
531 }
532
533  void kerberos_set_creds_enctype(krb5_creds *pcreds, int enctype)
534 {
535 #if defined(HAVE_KRB5_KEYBLOCK_IN_CREDS)
536         KRB5_KEY_TYPE((&pcreds->keyblock)) = enctype;
537 #elif defined(HAVE_KRB5_SESSION_IN_CREDS)
538         KRB5_KEY_TYPE((&pcreds->session)) = enctype;
539 #else
540 #error UNKNOWN_KEYBLOCK_MEMBER_IN_KRB5_CREDS_STRUCT
541 #endif
542 }
543
544  BOOL kerberos_compatible_enctypes(krb5_context context,
545                                   krb5_enctype enctype1,
546                                   krb5_enctype enctype2)
547 {
548 #if defined(HAVE_KRB5_C_ENCTYPE_COMPARE)
549         krb5_boolean similar = 0;
550
551         krb5_c_enctype_compare(context, enctype1, enctype2, &similar);
552         return similar ? True : False;
553 #elif defined(HAVE_KRB5_ENCTYPES_COMPATIBLE_KEYS)
554         return krb5_enctypes_compatible_keys(context, enctype1, enctype2) ? True : False;
555 #endif
556 }
557
558 static BOOL ads_cleanup_expired_creds(krb5_context context, 
559                                       krb5_ccache  ccache,
560                                       krb5_creds  *credsp)
561 {
562         krb5_error_code retval;
563         const char *cc_type = krb5_cc_get_type(context, ccache);
564
565         DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
566                   cc_type, krb5_cc_get_name(context, ccache),
567                   http_timestring(credsp->times.endtime)));
568
569         /* we will probably need new tickets if the current ones
570            will expire within 10 seconds.
571         */
572         if (credsp->times.endtime >= (time(NULL) + 10))
573                 return False;
574
575         /* heimdal won't remove creds from a file ccache, and 
576            perhaps we shouldn't anyway, since internally we 
577            use memory ccaches, and a FILE one probably means that
578            we're using creds obtained outside of our exectuable
579         */
580         if (strequal(cc_type, "FILE")) {
581                 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
582                 return False;
583         }
584
585         retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
586         if (retval) {
587                 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
588                           error_message(retval)));
589                 /* If we have an error in this, we want to display it,
590                    but continue as though we deleted it */
591         }
592         return True;
593 }
594
595 /*
596   we can't use krb5_mk_req because w2k wants the service to be in a particular format
597 */
598 static krb5_error_code ads_krb5_mk_req(krb5_context context, 
599                                        krb5_auth_context *auth_context, 
600                                        const krb5_flags ap_req_options,
601                                        const char *principal,
602                                        krb5_ccache ccache, 
603                                        krb5_data *outbuf, 
604                                        time_t *expire_time)
605 {
606         krb5_error_code           retval;
607         krb5_principal    server;
608         krb5_creds              * credsp;
609         krb5_creds                creds;
610         krb5_data in_data;
611         BOOL creds_ready = False;
612         int i = 0, maxtries = 3;
613         
614         retval = smb_krb5_parse_name(context, principal, &server);
615         if (retval) {
616                 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
617                 return retval;
618         }
619         
620         /* obtain ticket & session key */
621         ZERO_STRUCT(creds);
622         if ((retval = krb5_copy_principal(context, server, &creds.server))) {
623                 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n", 
624                          error_message(retval)));
625                 goto cleanup_princ;
626         }
627         
628         if ((retval = krb5_cc_get_principal(context, ccache, &creds.client))) {
629                 /* This can commonly fail on smbd startup with no ticket in the cache.
630                  * Report at higher level than 1. */
631                 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n", 
632                          error_message(retval)));
633                 goto cleanup_creds;
634         }
635
636         while (!creds_ready && (i < maxtries)) {
637
638                 if ((retval = krb5_get_credentials(context, 0, ccache, 
639                                                    &creds, &credsp))) {
640                         DEBUG(1,("ads_krb5_mk_req: krb5_get_credentials failed for %s (%s)\n",
641                                  principal, error_message(retval)));
642                         goto cleanup_creds;
643                 }
644
645                 /* cope with ticket being in the future due to clock skew */
646                 if ((unsigned)credsp->times.starttime > time(NULL)) {
647                         time_t t = time(NULL);
648                         int time_offset =(int)((unsigned)credsp->times.starttime-t);
649                         DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
650                         krb5_set_real_time(context, t + time_offset + 1, 0);
651                 }
652
653                 if (!ads_cleanup_expired_creds(context, ccache, credsp)) {
654                         creds_ready = True;
655                 }
656
657                 i++;
658         }
659
660         DEBUG(10,("ads_krb5_mk_req: Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
661                   principal, krb5_cc_get_type(context, ccache), krb5_cc_get_name(context, ccache),
662                   http_timestring((unsigned)credsp->times.endtime), 
663                   (unsigned)credsp->times.endtime));
664
665         if (expire_time) {
666                 *expire_time = (time_t)credsp->times.endtime;
667         }
668
669         in_data.length = 0;
670         retval = krb5_mk_req_extended(context, auth_context, ap_req_options, 
671                                       &in_data, credsp, outbuf);
672         if (retval) {
673                 DEBUG(1,("ads_krb5_mk_req: krb5_mk_req_extended failed (%s)\n", 
674                          error_message(retval)));
675         }
676         
677         krb5_free_creds(context, credsp);
678
679 cleanup_creds:
680         krb5_free_cred_contents(context, &creds);
681
682 cleanup_princ:
683         krb5_free_principal(context, server);
684
685         return retval;
686 }
687
688 /*
689   get a kerberos5 ticket for the given service 
690 */
691 int cli_krb5_get_ticket(const char *principal, time_t time_offset, 
692                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5, 
693                         uint32 extra_ap_opts, const char *ccname, 
694                         time_t *tgs_expire)
695
696 {
697         krb5_error_code retval;
698         krb5_data packet;
699         krb5_context context = NULL;
700         krb5_ccache ccdef = NULL;
701         krb5_auth_context auth_context = NULL;
702         krb5_enctype enc_types[] = {
703 #ifdef ENCTYPE_ARCFOUR_HMAC
704                 ENCTYPE_ARCFOUR_HMAC,
705 #endif 
706                 ENCTYPE_DES_CBC_MD5, 
707                 ENCTYPE_DES_CBC_CRC, 
708                 ENCTYPE_NULL};
709
710         initialize_krb5_error_table();
711         retval = krb5_init_context(&context);
712         if (retval) {
713                 DEBUG(1,("cli_krb5_get_ticket: krb5_init_context failed (%s)\n", 
714                          error_message(retval)));
715                 goto failed;
716         }
717
718         if (time_offset != 0) {
719                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
720         }
721
722         if ((retval = krb5_cc_resolve(context, ccname ?
723                         ccname : krb5_cc_default_name(context), &ccdef))) {
724                 DEBUG(1,("cli_krb5_get_ticket: krb5_cc_default failed (%s)\n",
725                          error_message(retval)));
726                 goto failed;
727         }
728
729         if ((retval = krb5_set_default_tgs_ktypes(context, enc_types))) {
730                 DEBUG(1,("cli_krb5_get_ticket: krb5_set_default_tgs_ktypes failed (%s)\n",
731                          error_message(retval)));
732                 goto failed;
733         }
734
735         if ((retval = ads_krb5_mk_req(context, 
736                                         &auth_context, 
737                                         AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
738                                         principal,
739                                         ccdef, &packet,
740                                         tgs_expire))) {
741                 goto failed;
742         }
743
744         get_krb5_smb_session_key(context, auth_context, session_key_krb5, False);
745
746         *ticket = data_blob(packet.data, packet.length);
747
748         kerberos_free_data_contents(context, &packet); 
749
750 failed:
751
752         if ( context ) {
753                 if (ccdef)
754                         krb5_cc_close(context, ccdef);
755                 if (auth_context)
756                         krb5_auth_con_free(context, auth_context);
757                 krb5_free_context(context);
758         }
759                 
760         return retval;
761 }
762
763  BOOL get_krb5_smb_session_key(krb5_context context, krb5_auth_context auth_context, DATA_BLOB *session_key, BOOL remote)
764  {
765         krb5_keyblock *skey;
766         krb5_error_code err;
767         BOOL ret = False;
768
769         if (remote)
770                 err = krb5_auth_con_getremotesubkey(context, auth_context, &skey);
771         else
772                 err = krb5_auth_con_getlocalsubkey(context, auth_context, &skey);
773         if (err == 0 && skey != NULL) {
774                 DEBUG(10, ("Got KRB5 session key of length %d\n",  (int)KRB5_KEY_LENGTH(skey)));
775                 *session_key = data_blob(KRB5_KEY_DATA(skey), KRB5_KEY_LENGTH(skey));
776                 dump_data_pw("KRB5 Session Key:\n", session_key->data, session_key->length);
777
778                 ret = True;
779
780                 krb5_free_keyblock(context, skey);
781         } else {
782                 DEBUG(10, ("KRB5 error getting session key %d\n", err));
783         }
784
785         return ret;
786  }
787
788
789 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
790  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i );
791
792  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i )
793 {
794         static krb5_data kdata;
795
796         kdata.data = (char *)krb5_principal_get_comp_string(context, principal, i);
797         kdata.length = strlen((const char *)kdata.data);
798         return &kdata;
799 }
800 #endif
801
802  krb5_error_code smb_krb5_kt_free_entry(krb5_context context, krb5_keytab_entry *kt_entry)
803 {
804 #if defined(HAVE_KRB5_KT_FREE_ENTRY)
805         return krb5_kt_free_entry(context, kt_entry);
806 #elif defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
807         return krb5_free_keytab_entry_contents(context, kt_entry);
808 #else
809 #error UNKNOWN_KT_FREE_FUNCTION
810 #endif
811 }
812
813  void smb_krb5_checksum_from_pac_sig(krb5_checksum *cksum, 
814                                     PAC_SIGNATURE_DATA *sig)
815 {
816 #ifdef HAVE_CHECKSUM_IN_KRB5_CHECKSUM
817         cksum->cksumtype        = (krb5_cksumtype)sig->type;
818         cksum->checksum.length  = sig->signature.buf_len;
819         cksum->checksum.data    = sig->signature.buffer;
820 #else
821         cksum->checksum_type    = (krb5_cksumtype)sig->type;
822         cksum->length           = sig->signature.buf_len;
823         cksum->contents         = sig->signature.buffer;
824 #endif
825 }
826
827  krb5_error_code smb_krb5_verify_checksum(krb5_context context,
828                                          krb5_keyblock *keyblock,
829                                          krb5_keyusage usage,
830                                          krb5_checksum *cksum,
831                                          uint8 *data,
832                                          size_t length)
833 {
834         krb5_error_code ret;
835
836         /* verify the checksum */
837
838         /* welcome to the wonderful world of samba's kerberos abstraction layer:
839          * 
840          * function                     heimdal 0.6.1rc3        heimdal 0.7     MIT krb 1.4.2
841          * -----------------------------------------------------------------------------
842          * krb5_c_verify_checksum       -                       works           works
843          * krb5_verify_checksum         works (6 args)          works (6 args)  broken (7 args) 
844          */
845
846 #if defined(HAVE_KRB5_C_VERIFY_CHECKSUM)
847         {
848                 krb5_boolean checksum_valid = False;
849                 krb5_data input;
850
851                 input.data = (char *)data;
852                 input.length = length;
853
854                 ret = krb5_c_verify_checksum(context, 
855                                              keyblock, 
856                                              usage,
857                                              &input, 
858                                              cksum,
859                                              &checksum_valid);
860                 if (ret) {
861                         DEBUG(3,("smb_krb5_verify_checksum: krb5_c_verify_checksum() failed: %s\n", 
862                                 error_message(ret)));
863                         return ret;
864                 }
865
866                 if (!checksum_valid)
867                         ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
868         }
869
870 #elif KRB5_VERIFY_CHECKSUM_ARGS == 6 && defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CRYPTO) && defined(HAVE_KRB5_CRYPTO_DESTROY)
871
872         /* Warning: MIT's krb5_verify_checksum cannot be used as it will use a key
873          * without enctype and it ignores any key_usage types - Guenther */
874
875         {
876
877                 krb5_crypto crypto;
878                 ret = krb5_crypto_init(context,
879                                        keyblock,
880                                        0,
881                                        &crypto);
882                 if (ret) {
883                         DEBUG(0,("smb_krb5_verify_checksum: krb5_crypto_init() failed: %s\n", 
884                                 error_message(ret)));
885                         return ret;
886                 }
887
888                 ret = krb5_verify_checksum(context,
889                                            crypto,
890                                            usage,
891                                            data,
892                                            length,
893                                            cksum);
894
895                 krb5_crypto_destroy(context, crypto);
896         }
897
898 #else
899 #error UNKNOWN_KRB5_VERIFY_CHECKSUM_FUNCTION
900 #endif
901
902         return ret;
903 }
904
905  time_t get_authtime_from_tkt(krb5_ticket *tkt)
906 {
907 #if defined(HAVE_KRB5_TKT_ENC_PART2)
908         return tkt->enc_part2->times.authtime;
909 #else
910         return tkt->ticket.authtime;
911 #endif
912 }
913
914 #ifdef HAVE_KRB5_DECODE_AP_REQ  /* Heimdal */
915 static int get_kvno_from_ap_req(krb5_ap_req *ap_req)
916 {
917 #ifdef HAVE_TICKET_POINTER_IN_KRB5_AP_REQ /* MIT */
918         if (ap_req->ticket->enc_part.kvno)
919                 return ap_req->ticket->enc_part.kvno;
920 #else /* Heimdal */
921         if (ap_req->ticket.enc_part.kvno) 
922                 return *ap_req->ticket.enc_part.kvno;
923 #endif
924         return 0;
925 }
926
927 static krb5_enctype get_enctype_from_ap_req(krb5_ap_req *ap_req)
928 {
929 #ifdef HAVE_ETYPE_IN_ENCRYPTEDDATA /* Heimdal */
930         return ap_req->ticket.enc_part.etype;
931 #else /* MIT */
932         return ap_req->ticket->enc_part.enctype;
933 #endif
934 }
935 #endif  /* HAVE_KRB5_DECODE_AP_REQ */
936
937 static krb5_error_code
938 get_key_from_keytab(krb5_context context,
939                     krb5_const_principal server,
940                     krb5_enctype enctype,
941                     krb5_kvno kvno,
942                     krb5_keyblock **out_key)
943 {
944         krb5_keytab_entry entry;
945         krb5_error_code ret;
946         krb5_keytab keytab;
947         char *name = NULL;
948
949         /* We have to open a new keytab handle here, as MIT does
950            an implicit open/getnext/close on krb5_kt_get_entry. We
951            may be in the middle of a keytab enumeration when this is
952            called. JRA. */
953
954         ret = krb5_kt_default(context, &keytab);
955         if (ret) {
956                 DEBUG(0,("get_key_from_keytab: failed to open keytab: %s\n", error_message(ret)));
957                 return ret;
958         }
959
960         if ( DEBUGLEVEL >= 10 ) {
961                 if (smb_krb5_unparse_name(context, server, &name) == 0) {
962                         DEBUG(10,("get_key_from_keytab: will look for kvno %d, enctype %d and name: %s\n", 
963                                 kvno, enctype, name));
964                         SAFE_FREE(name);
965                 }
966         }
967
968         ret = krb5_kt_get_entry(context,
969                                 keytab,
970                                 server,
971                                 kvno,
972                                 enctype,
973                                 &entry);
974
975         if (ret) {
976                 DEBUG(0,("get_key_from_keytab: failed to retrieve key: %s\n", error_message(ret)));
977                 goto out;
978         }
979
980 #ifdef HAVE_KRB5_KEYTAB_ENTRY_KEYBLOCK /* Heimdal */
981         ret = krb5_copy_keyblock(context, &entry.keyblock, out_key);
982 #elif defined(HAVE_KRB5_KEYTAB_ENTRY_KEY) /* MIT */
983         ret = krb5_copy_keyblock(context, &entry.key, out_key);
984 #else
985 #error UNKNOWN_KRB5_KEYTAB_ENTRY_FORMAT
986 #endif
987
988         if (ret) {
989                 DEBUG(0,("get_key_from_keytab: failed to copy key: %s\n", error_message(ret)));
990                 goto out;
991         }
992                 
993         smb_krb5_kt_free_entry(context, &entry);
994         
995 out:    
996         krb5_kt_close(context, keytab);
997         return ret;
998 }
999
1000 /* Prototypes */
1001
1002  krb5_error_code smb_krb5_get_keyinfo_from_ap_req(krb5_context context, 
1003                                                  const krb5_data *inbuf, 
1004                                                  krb5_kvno *kvno, 
1005                                                  krb5_enctype *enctype)
1006 {
1007 #ifdef HAVE_KRB5_DECODE_AP_REQ /* Heimdal */
1008         {
1009                 krb5_error_code ret;
1010                 krb5_ap_req ap_req;
1011                 
1012                 ret = krb5_decode_ap_req(context, inbuf, &ap_req);
1013                 if (ret)
1014                         return ret;
1015
1016                 *kvno = get_kvno_from_ap_req(&ap_req);
1017                 *enctype = get_enctype_from_ap_req(&ap_req);
1018
1019                 free_AP_REQ(&ap_req);
1020                 return 0;
1021         }
1022 #endif
1023
1024         /* Possibly not an appropriate error code. */
1025         return KRB5KDC_ERR_BADOPTION;
1026 }
1027
1028  krb5_error_code krb5_rd_req_return_keyblock_from_keytab(krb5_context context,
1029                                                         krb5_auth_context *auth_context,
1030                                                         const krb5_data *inbuf,
1031                                                         krb5_const_principal server,
1032                                                         krb5_keytab keytab,
1033                                                         krb5_flags *ap_req_options,
1034                                                         krb5_ticket **ticket, 
1035                                                         krb5_keyblock **keyblock)
1036 {
1037         krb5_error_code ret;
1038         krb5_kvno kvno;
1039         krb5_enctype enctype;
1040         krb5_keyblock *local_keyblock;
1041
1042         ret = krb5_rd_req(context, 
1043                           auth_context, 
1044                           inbuf, 
1045                           server, 
1046                           keytab, 
1047                           ap_req_options, 
1048                           ticket);
1049         if (ret) {
1050                 return ret;
1051         }
1052         
1053 #ifdef KRB5_TICKET_HAS_KEYINFO
1054         enctype = (*ticket)->enc_part.enctype;
1055         kvno = (*ticket)->enc_part.kvno;
1056 #else
1057         ret = smb_krb5_get_keyinfo_from_ap_req(context, inbuf, &kvno, &enctype);
1058         if (ret) {
1059                 return ret;
1060         }
1061 #endif
1062
1063         ret = get_key_from_keytab(context, 
1064                                   server,
1065                                   enctype,
1066                                   kvno,
1067                                   &local_keyblock);
1068         if (ret) {
1069                 DEBUG(0,("krb5_rd_req_return_keyblock_from_keytab: failed to call get_key_from_keytab\n"));
1070                 goto out;
1071         }
1072
1073 out:
1074         if (ret && local_keyblock != NULL) {
1075                 krb5_free_keyblock(context, local_keyblock);
1076         } else {
1077                 *keyblock = local_keyblock;
1078         }
1079
1080         return ret;
1081 }
1082
1083  krb5_error_code smb_krb5_parse_name_norealm(krb5_context context, 
1084                                             const char *name, 
1085                                             krb5_principal *principal)
1086 {
1087 #ifdef HAVE_KRB5_PARSE_NAME_NOREALM
1088         return smb_krb5_parse_name_norealm_conv(context, name, principal);
1089 #endif
1090
1091         /* we are cheating here because parse_name will in fact set the realm.
1092          * We don't care as the only caller of smb_krb5_parse_name_norealm
1093          * ignores the realm anyway when calling
1094          * smb_krb5_principal_compare_any_realm later - Guenther */
1095
1096         return smb_krb5_parse_name(context, name, principal);
1097 }
1098
1099  BOOL smb_krb5_principal_compare_any_realm(krb5_context context, 
1100                                           krb5_const_principal princ1, 
1101                                           krb5_const_principal princ2)
1102 {
1103 #ifdef HAVE_KRB5_PRINCIPAL_COMPARE_ANY_REALM
1104
1105         return krb5_principal_compare_any_realm(context, princ1, princ2);
1106
1107 /* krb5_princ_size is a macro in MIT */
1108 #elif defined(HAVE_KRB5_PRINC_SIZE) || defined(krb5_princ_size)
1109
1110         int i, len1, len2;
1111         const krb5_data *p1, *p2;
1112
1113         len1 = krb5_princ_size(context, princ1);
1114         len2 = krb5_princ_size(context, princ2);
1115
1116         if (len1 != len2)
1117                 return False;
1118
1119         for (i = 0; i < len1; i++) {
1120
1121                 p1 = krb5_princ_component(context, CONST_DISCARD(krb5_principal, princ1), i);
1122                 p2 = krb5_princ_component(context, CONST_DISCARD(krb5_principal, princ2), i);
1123
1124                 if (p1->length != p2->length || memcmp(p1->data, p2->data, p1->length))
1125                         return False;
1126         }
1127
1128         return True;
1129 #else
1130 #error NO_SUITABLE_PRINCIPAL_COMPARE_FUNCTION
1131 #endif
1132 }
1133
1134  krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,       /* FILE:/tmp/krb5cc_0 */
1135                                        const char *client_string,       /* gd@BER.SUSE.DE */
1136                                        const char *service_string,      /* krbtgt/BER.SUSE.DE@BER.SUSE.DE */
1137                                        time_t *expire_time)
1138 {
1139         krb5_error_code ret;
1140         krb5_context context = NULL;
1141         krb5_ccache ccache = NULL;
1142         krb5_principal client = NULL;
1143         krb5_creds creds, creds_in, *creds_out = NULL;
1144
1145         ZERO_STRUCT(creds);
1146         ZERO_STRUCT(creds_in);
1147
1148         initialize_krb5_error_table();
1149         ret = krb5_init_context(&context);
1150         if (ret) {
1151                 goto done;
1152         }
1153
1154         if (!ccache_string) {
1155                 ccache_string = krb5_cc_default_name(context);
1156         }
1157
1158         if (!ccache_string) {
1159                 ret = EINVAL;
1160                 goto done;
1161         }
1162
1163         DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
1164
1165         /* FIXME: we should not fall back to defaults */
1166         ret = krb5_cc_resolve(context, CONST_DISCARD(char *, ccache_string), &ccache);
1167         if (ret) {
1168                 goto done;
1169         }
1170
1171         if (client_string) {
1172                 ret = smb_krb5_parse_name(context, client_string, &client);
1173                 if (ret) {
1174                         goto done;
1175                 }
1176         } else {
1177                 ret = krb5_cc_get_principal(context, ccache, &client);
1178                 if (ret) {
1179                         goto done;
1180                 }
1181         }
1182
1183 #ifdef HAVE_KRB5_GET_RENEWED_CREDS      /* MIT */
1184         {
1185                 ret = krb5_get_renewed_creds(context, &creds, client, ccache, CONST_DISCARD(char *, service_string));
1186                 if (ret) {
1187                         DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
1188                         goto done;
1189                 }
1190         }
1191 #elif defined(HAVE_KRB5_GET_KDC_CRED)   /* Heimdal */
1192         {
1193                 krb5_kdc_flags flags;
1194                 krb5_realm *client_realm = NULL;
1195
1196                 ret = krb5_copy_principal(context, client, &creds_in.client);
1197                 if (ret) {
1198                         goto done;
1199                 }
1200
1201                 if (service_string) {
1202                         ret = smb_krb5_parse_name(context, service_string, &creds_in.server);
1203                         if (ret) { 
1204                                 goto done;
1205                         }
1206                 } else {
1207                         /* build tgt service by default */
1208                         client_realm = krb5_princ_realm(context, creds_in.client);
1209                         if (!client_realm) {
1210                                 ret = ENOMEM;
1211                                 goto done;
1212                         }
1213                         ret = krb5_make_principal(context, &creds_in.server, *client_realm, KRB5_TGS_NAME, *client_realm, NULL);
1214                         if (ret) {
1215                                 goto done;
1216                         }
1217                 }
1218
1219                 flags.i = 0;
1220                 flags.b.renewable = flags.b.renew = True;
1221
1222                 ret = krb5_get_kdc_cred(context, ccache, flags, NULL, NULL, &creds_in, &creds_out);
1223                 if (ret) {
1224                         DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
1225                         goto done;
1226                 }
1227
1228                 creds = *creds_out;
1229         }
1230 #else
1231 #error NO_SUITABLE_KRB5_TICKET_RENEW_FUNCTION_AVAILABLE
1232 #endif
1233
1234         /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
1235         ret = krb5_cc_initialize(context, ccache, client);
1236         if (ret) {
1237                 goto done;
1238         }
1239         
1240         ret = krb5_cc_store_cred(context, ccache, &creds);
1241
1242         if (expire_time) {
1243                 *expire_time = (time_t) creds.times.endtime;
1244         }
1245
1246 done:
1247         krb5_free_cred_contents(context, &creds_in);
1248
1249         if (creds_out) {
1250                 krb5_free_creds(context, creds_out);
1251         } else {
1252                 krb5_free_cred_contents(context, &creds);
1253         }
1254
1255         if (client) {
1256                 krb5_free_principal(context, client);
1257         }
1258         if (ccache) {
1259                 krb5_cc_close(context, ccache);
1260         }
1261         if (context) {
1262                 krb5_free_context(context);
1263         }
1264
1265         return ret;
1266 }
1267
1268  krb5_error_code smb_krb5_free_addresses(krb5_context context, smb_krb5_addresses *addr)
1269 {
1270         krb5_error_code ret = 0;
1271         if (addr == NULL) {
1272                 return ret;
1273         }
1274 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1275         krb5_free_addresses(context, addr->addrs);
1276 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1277         ret = krb5_free_addresses(context, addr->addrs);
1278         SAFE_FREE(addr->addrs);
1279 #endif
1280         SAFE_FREE(addr);
1281         addr = NULL;
1282         return ret;
1283 }
1284
1285  krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr)
1286 {
1287         krb5_error_code ret = 0;
1288         nstring buf;
1289 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1290         krb5_address **addrs = NULL;
1291 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1292         krb5_addresses *addrs = NULL;
1293 #endif
1294
1295         *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1296         if (*kerb_addr == NULL) {
1297                 return ENOMEM;
1298         }
1299
1300         put_name(buf, global_myname(), ' ', 0x20);
1301
1302 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1303         {
1304                 int num_addr = 2;
1305
1306                 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1307                 if (addrs == NULL) {
1308                         SAFE_FREE(kerb_addr);
1309                         return ENOMEM;
1310                 }
1311
1312                 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1313
1314                 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1315                 if (addrs[0] == NULL) {
1316                         SAFE_FREE(addrs);
1317                         SAFE_FREE(kerb_addr);
1318                         return ENOMEM;
1319                 }
1320
1321                 addrs[0]->magic = KV5M_ADDRESS;
1322                 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1323                 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1324                 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1325                 if (addrs[0]->contents == NULL) {
1326                         SAFE_FREE(addrs[0]);
1327                         SAFE_FREE(addrs);
1328                         SAFE_FREE(kerb_addr);
1329                         return ENOMEM;
1330                 }
1331
1332                 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1333
1334                 addrs[1] = NULL;
1335         }
1336 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1337         {
1338                 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1339                 if (addrs == NULL) {
1340                         SAFE_FREE(kerb_addr);
1341                         return ENOMEM;
1342                 }
1343
1344                 memset(addrs, 0, sizeof(krb5_addresses));
1345
1346                 addrs->len = 1;
1347                 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1348                 if (addrs->val == NULL) {
1349                         SAFE_FREE(addrs);
1350                         SAFE_FREE(kerb_addr);
1351                         return ENOMEM;
1352                 }
1353
1354                 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1355                 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1356                 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1357                 if (addrs->val[0].address.data == NULL) {
1358                         SAFE_FREE(addrs->val);
1359                         SAFE_FREE(addrs);
1360                         SAFE_FREE(kerb_addr);
1361                         return ENOMEM;
1362                 }
1363
1364                 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1365         }
1366 #else
1367 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1368 #endif
1369         (*kerb_addr)->addrs = addrs;
1370
1371         return ret;
1372 }
1373
1374  void smb_krb5_free_error(krb5_context context, krb5_error *krberror)
1375 {
1376 #ifdef HAVE_KRB5_FREE_ERROR_CONTENTS /* Heimdal */
1377         krb5_free_error_contents(context, krberror);
1378 #else /* MIT */
1379         krb5_free_error(context, krberror);
1380 #endif
1381 }
1382
1383  krb5_error_code handle_krberror_packet(krb5_context context,
1384                                         krb5_data *packet)
1385 {
1386         krb5_error_code ret;
1387         BOOL got_error_code = False;
1388
1389         DEBUG(10,("handle_krberror_packet: got error packet\n"));
1390         
1391 #ifdef HAVE_E_DATA_POINTER_IN_KRB5_ERROR /* Heimdal */
1392         {
1393                 krb5_error krberror;
1394
1395                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1396                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1397                                 error_message(ret)));
1398                         return ret;
1399                 }
1400
1401                 if (krberror.e_data == NULL || krberror.e_data->data == NULL) {
1402                         ret = (krb5_error_code) krberror.error_code;
1403                         got_error_code = True;
1404                 }
1405
1406                 smb_krb5_free_error(context, &krberror);
1407         }
1408 #else /* MIT */
1409         {
1410                 krb5_error *krberror;
1411
1412                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1413                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1414                                 error_message(ret)));
1415                         return ret;
1416                 }
1417
1418                 if (krberror->e_data.data == NULL) {
1419                         ret = ERROR_TABLE_BASE_krb5 + (krb5_error_code) krberror->error;
1420                         got_error_code = True;
1421                 }
1422                 smb_krb5_free_error(context, krberror);
1423         }
1424 #endif
1425         if (got_error_code) {
1426                 DEBUG(5,("handle_krberror_packet: got KERBERR from kpasswd: %s (%d)\n", 
1427                         error_message(ret), ret));
1428         }
1429         return ret;
1430 }
1431
1432  krb5_error_code smb_krb5_get_init_creds_opt_alloc(krb5_context context,
1433                                             krb5_get_init_creds_opt **opt)
1434 {
1435 #ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_ALLOC
1436         /* Heimdal or modern MIT version */
1437         return krb5_get_init_creds_opt_alloc(context, opt);
1438 #else
1439         /* Historical MIT version */
1440         krb5_get_init_creds_opt *my_opt;
1441
1442         *opt = NULL;
1443
1444         if ((my_opt = SMB_MALLOC_P(krb5_get_init_creds_opt)) == NULL) {
1445                 return ENOMEM;
1446         }
1447
1448         krb5_get_init_creds_opt_init(my_opt);
1449
1450         *opt =  my_opt;
1451         return 0;
1452 #endif /* HAVE_KRB5_GET_INIT_CREDS_OPT_ALLOC  */
1453 }
1454
1455  void smb_krb5_get_init_creds_opt_free(krb5_context context,
1456                                 krb5_get_init_creds_opt *opt)
1457 {
1458 #ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_FREE
1459
1460 #ifdef KRB5_CREDS_OPT_FREE_REQUIRES_CONTEXT
1461         /* Modern MIT or Heimdal version */
1462         krb5_get_init_creds_opt_free(context, opt);
1463 #else
1464         /* Heimdal version */
1465         krb5_get_init_creds_opt_free(opt);
1466 #endif /* KRB5_CREDS_OPT_FREE_REQUIRES_CONTEXT */
1467
1468 #else /* HAVE_KRB5_GET_INIT_CREDS_OPT_FREE */
1469         /* Historical MIT version */
1470         SAFE_FREE(opt);
1471         opt = NULL;
1472 #endif /* HAVE_KRB5_GET_INIT_CREDS_OPT_FREE */
1473 }
1474
1475  krb5_enctype smb_get_enctype_from_kt_entry(const krb5_keytab_entry *kt_entry)
1476 {
1477 #ifdef HAVE_KRB5_KEYTAB_ENTRY_KEY               /* MIT */
1478         return kt_entry->key.enctype;
1479 #elif defined(HAVE_KRB5_KEYTAB_ENTRY_KEYBLOCK)  /* Heimdal */
1480         return kt_entry->keyblock.keytype;
1481 #else
1482 #error UNKNOWN_KRB5_KEYTAB_ENTRY_KEYBLOCK_FORMAT
1483 #endif
1484 }
1485
1486
1487 /* caller needs to free etype_s */
1488  krb5_error_code smb_krb5_enctype_to_string(krb5_context context, 
1489                                             krb5_enctype enctype, 
1490                                             char **etype_s)
1491 {
1492 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1493         return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1494 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1495         char buf[256];
1496         krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1497         if (ret) {
1498                 return ret;
1499         }
1500         *etype_s = SMB_STRDUP(buf);
1501         if (!*etype_s) {
1502                 return ENOMEM;
1503         }
1504         return ret;
1505 #else
1506 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1507 #endif
1508 }
1509
1510  krb5_error_code smb_krb5_mk_error(krb5_context context,
1511                                 krb5_error_code error_code,
1512                                 const krb5_principal server,
1513                                 krb5_data *reply)
1514 {
1515 #ifdef HAVE_SHORT_KRB5_MK_ERROR_INTERFACE /* MIT */
1516         /*
1517          * The MIT interface is *terrible*.
1518          * We have to construct this ourselves...
1519          */
1520         krb5_error e;
1521
1522         memset(&e, 0, sizeof(e));
1523         krb5_us_timeofday(context, &e.stime, &e.susec);
1524         e.server = server;
1525 #if defined(krb5_err_base)
1526         e.error = error_code - krb5_err_base;
1527 #elif defined(ERROR_TABLE_BASE_krb5)
1528         e.error = error_code - ERROR_TABLE_BASE_krb5;
1529 #else
1530         e.error = error_code; /* Almost certainly wrong, but what can we do... ? */
1531 #endif
1532
1533         return krb5_mk_error(context, &e, reply);
1534 #else /* Heimdal. */
1535         return krb5_mk_error(context,
1536                                 error_code,
1537                                 NULL,
1538                                 NULL, /* e_data */
1539                                 NULL,
1540                                 server,
1541                                 NULL,
1542                                 NULL,
1543                                 reply);
1544 #endif
1545 }
1546
1547 #else /* HAVE_KRB5 */
1548  /* this saves a few linking headaches */
1549  int cli_krb5_get_ticket(const char *principal, time_t time_offset, 
1550                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5, uint32 extra_ap_opts,
1551                         const char *ccname, time_t *tgs_expire) 
1552 {
1553          DEBUG(0,("NO KERBEROS SUPPORT\n"));
1554          return 1;
1555 }
1556
1557 #endif