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