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