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