lib/krb5_wrap: add krb5_copy_data_contents.
[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  * @brief copy a buffer into a krb5_data struct
739  *
740  * @param[in] p                 The krb5_data
741  * @param[in] data              The data to copy
742  * @param[in] length            The length of the data to copy
743  * @return krb5_error_code
744  *
745  * Caller has to free krb5_data with kerberos_free_data_contents().
746  */
747
748 krb5_error_code krb5_copy_data_contents(krb5_data *p,
749                                         const void *data,
750                                         size_t len)
751 {
752 #if defined(HAVE_KRB5_DATA_COPY)
753         return krb5_data_copy(p, data, len);
754 #else
755         if (len) {
756                 p->data = malloc(len);
757                 if (p->data == NULL) {
758                         return ENOMEM;
759                 }
760                 memmove(p->data, data, len);
761         } else {
762                 p->data = NULL;
763         }
764         p->length = len;
765         p->magic = KV5M_DATA;
766         return 0;
767 #endif
768 }
769
770 /*
771   get a kerberos5 ticket for the given service
772 */
773 int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
774                         const char *principal, time_t time_offset,
775                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
776                         uint32_t extra_ap_opts, const char *ccname,
777                         time_t *tgs_expire,
778                         const char *impersonate_princ_s)
779
780 {
781         krb5_error_code retval;
782         krb5_data packet;
783         krb5_context context = NULL;
784         krb5_ccache ccdef = NULL;
785         krb5_auth_context auth_context = NULL;
786         krb5_enctype enc_types[] = {
787 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
788                 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
789 #endif
790 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
791                 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
792 #endif
793                 ENCTYPE_ARCFOUR_HMAC,
794                 ENCTYPE_DES_CBC_MD5,
795                 ENCTYPE_DES_CBC_CRC,
796                 ENCTYPE_NULL};
797
798         initialize_krb5_error_table();
799         retval = krb5_init_context(&context);
800         if (retval) {
801                 DEBUG(1, ("krb5_init_context failed (%s)\n",
802                          error_message(retval)));
803                 goto failed;
804         }
805
806         if (time_offset != 0) {
807                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
808         }
809
810         if ((retval = krb5_cc_resolve(context, ccname ?
811                         ccname : krb5_cc_default_name(context), &ccdef))) {
812                 DEBUG(1, ("krb5_cc_default failed (%s)\n",
813                          error_message(retval)));
814                 goto failed;
815         }
816
817         if ((retval = krb5_set_default_tgs_ktypes(context, enc_types))) {
818                 DEBUG(1, ("krb5_set_default_tgs_ktypes failed (%s)\n",
819                          error_message(retval)));
820                 goto failed;
821         }
822
823         retval = ads_krb5_mk_req(context, &auth_context,
824                                 AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
825                                 principal, ccdef, &packet,
826                                 tgs_expire, impersonate_princ_s);
827         if (retval) {
828                 goto failed;
829         }
830
831         get_krb5_smb_session_key(mem_ctx, context, auth_context,
832                                  session_key_krb5, false);
833
834         *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
835
836         kerberos_free_data_contents(context, &packet);
837
838 failed:
839
840         if (context) {
841                 if (ccdef)
842                         krb5_cc_close(context, ccdef);
843                 if (auth_context)
844                         krb5_auth_con_free(context, auth_context);
845                 krb5_free_context(context);
846         }
847
848         return retval;
849 }
850
851 bool get_krb5_smb_session_key(TALLOC_CTX *mem_ctx,
852                               krb5_context context,
853                               krb5_auth_context auth_context,
854                               DATA_BLOB *session_key, bool remote)
855 {
856         krb5_keyblock *skey = NULL;
857         krb5_error_code err = 0;
858         bool ret = false;
859
860         if (remote) {
861                 err = krb5_auth_con_getremotesubkey(context,
862                                                     auth_context, &skey);
863         } else {
864                 err = krb5_auth_con_getlocalsubkey(context,
865                                                    auth_context, &skey);
866         }
867
868         if (err || skey == NULL) {
869                 DEBUG(10, ("KRB5 error getting session key %d\n", err));
870                 goto done;
871         }
872
873         DEBUG(10, ("Got KRB5 session key of length %d\n",
874                    (int)KRB5_KEY_LENGTH(skey)));
875
876         *session_key = data_blob_talloc(mem_ctx,
877                                          KRB5_KEY_DATA(skey),
878                                          KRB5_KEY_LENGTH(skey));
879         dump_data_pw("KRB5 Session Key:\n",
880                      session_key->data,
881                      session_key->length);
882
883         ret = true;
884
885 done:
886         if (skey) {
887                 krb5_free_keyblock(context, skey);
888         }
889
890         return ret;
891 }
892
893
894 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
895  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i );
896
897  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i )
898 {
899         static krb5_data kdata;
900
901         kdata.data = discard_const_p(char, krb5_principal_get_comp_string(context, principal, i));
902         kdata.length = strlen((const char *)kdata.data);
903         return &kdata;
904 }
905 #endif
906
907 /*
908  * @brief Get talloced string component of a principal
909  *
910  * @param[in] mem_ctx           The TALLOC_CTX
911  * @param[in] context           The krb5_context
912  * @param[in] principal         The principal
913  * @param[in] component         The component
914  * @return string component
915  *
916  * Caller must talloc_free if the return value is not NULL.
917  *
918  */
919
920 /* caller has to free returned string with free() */
921 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
922                                          krb5_context context,
923                                          krb5_const_principal principal,
924                                          unsigned int component)
925 {
926 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
927         return talloc_strdup(mem_ctx, krb5_principal_get_comp_string(context, principal, component));
928 #else
929         krb5_data *data;
930
931         if (component >= krb5_princ_size(context, principal)) {
932                 return NULL;
933         }
934
935         data = krb5_princ_component(context, principal, component);
936         if (data == NULL) {
937                 return NULL;
938         }
939
940         return talloc_strndup(mem_ctx, data->data, data->length);
941 #endif
942 }
943
944 /* Prototypes */
945
946  krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,       /* FILE:/tmp/krb5cc_0 */
947                                        const char *client_string,       /* gd@BER.SUSE.DE */
948                                        const char *service_string,      /* krbtgt/BER.SUSE.DE@BER.SUSE.DE */
949                                        time_t *expire_time)
950 {
951         krb5_error_code ret;
952         krb5_context context = NULL;
953         krb5_ccache ccache = NULL;
954         krb5_principal client = NULL;
955         krb5_creds creds, creds_in;
956
957         ZERO_STRUCT(creds);
958         ZERO_STRUCT(creds_in);
959
960         initialize_krb5_error_table();
961         ret = krb5_init_context(&context);
962         if (ret) {
963                 goto done;
964         }
965
966         if (!ccache_string) {
967                 ccache_string = krb5_cc_default_name(context);
968         }
969
970         if (!ccache_string) {
971                 ret = EINVAL;
972                 goto done;
973         }
974
975         DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
976
977         /* FIXME: we should not fall back to defaults */
978         ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
979         if (ret) {
980                 goto done;
981         }
982
983         if (client_string) {
984                 ret = smb_krb5_parse_name(context, client_string, &client);
985                 if (ret) {
986                         goto done;
987                 }
988         } else {
989                 ret = krb5_cc_get_principal(context, ccache, &client);
990                 if (ret) {
991                         goto done;
992                 }
993         }
994
995         ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
996         if (ret) {
997                 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
998                 goto done;
999         }
1000
1001         /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
1002         ret = krb5_cc_initialize(context, ccache, client);
1003         if (ret) {
1004                 goto done;
1005         }
1006
1007         ret = krb5_cc_store_cred(context, ccache, &creds);
1008
1009         if (expire_time) {
1010                 *expire_time = (time_t) creds.times.endtime;
1011         }
1012
1013 done:
1014         krb5_free_cred_contents(context, &creds_in);
1015         krb5_free_cred_contents(context, &creds);
1016
1017         if (client) {
1018                 krb5_free_principal(context, client);
1019         }
1020         if (ccache) {
1021                 krb5_cc_close(context, ccache);
1022         }
1023         if (context) {
1024                 krb5_free_context(context);
1025         }
1026
1027         return ret;
1028 }
1029
1030  krb5_error_code smb_krb5_free_addresses(krb5_context context, smb_krb5_addresses *addr)
1031 {
1032         krb5_error_code ret = 0;
1033         if (addr == NULL) {
1034                 return ret;
1035         }
1036 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1037         krb5_free_addresses(context, addr->addrs);
1038 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1039         ret = krb5_free_addresses(context, addr->addrs);
1040         SAFE_FREE(addr->addrs);
1041 #endif
1042         SAFE_FREE(addr);
1043         addr = NULL;
1044         return ret;
1045 }
1046
1047 #define MAX_NETBIOSNAME_LEN 16
1048  krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
1049                                                    const char *netbios_name)
1050 {
1051         krb5_error_code ret = 0;
1052         char buf[MAX_NETBIOSNAME_LEN];
1053         int len;
1054 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1055         krb5_address **addrs = NULL;
1056 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1057         krb5_addresses *addrs = NULL;
1058 #endif
1059
1060         *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1061         if (*kerb_addr == NULL) {
1062                 return ENOMEM;
1063         }
1064
1065         /* temporarily duplicate put_name() code here to avoid dependency
1066          * issues for a 5 lines function */
1067         len = strlen(netbios_name);
1068         memcpy(buf, netbios_name,
1069                 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
1070         if (len < MAX_NETBIOSNAME_LEN - 1) {
1071                 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
1072         }
1073         buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
1074
1075 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1076         {
1077                 int num_addr = 2;
1078
1079                 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1080                 if (addrs == NULL) {
1081                         SAFE_FREE(*kerb_addr);
1082                         return ENOMEM;
1083                 }
1084
1085                 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1086
1087                 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1088                 if (addrs[0] == NULL) {
1089                         SAFE_FREE(addrs);
1090                         SAFE_FREE(*kerb_addr);
1091                         return ENOMEM;
1092                 }
1093
1094                 addrs[0]->magic = KV5M_ADDRESS;
1095                 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1096                 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1097                 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1098                 if (addrs[0]->contents == NULL) {
1099                         SAFE_FREE(addrs[0]);
1100                         SAFE_FREE(addrs);
1101                         SAFE_FREE(*kerb_addr);
1102                         return ENOMEM;
1103                 }
1104
1105                 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1106
1107                 addrs[1] = NULL;
1108         }
1109 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1110         {
1111                 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1112                 if (addrs == NULL) {
1113                         SAFE_FREE(*kerb_addr);
1114                         return ENOMEM;
1115                 }
1116
1117                 memset(addrs, 0, sizeof(krb5_addresses));
1118
1119                 addrs->len = 1;
1120                 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1121                 if (addrs->val == NULL) {
1122                         SAFE_FREE(addrs);
1123                         SAFE_FREE(kerb_addr);
1124                         return ENOMEM;
1125                 }
1126
1127                 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1128                 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1129                 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1130                 if (addrs->val[0].address.data == NULL) {
1131                         SAFE_FREE(addrs->val);
1132                         SAFE_FREE(addrs);
1133                         SAFE_FREE(*kerb_addr);
1134                         return ENOMEM;
1135                 }
1136
1137                 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1138         }
1139 #else
1140 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1141 #endif
1142         (*kerb_addr)->addrs = addrs;
1143
1144         return ret;
1145 }
1146
1147  void smb_krb5_free_error(krb5_context context, krb5_error *krberror)
1148 {
1149 #ifdef HAVE_KRB5_FREE_ERROR_CONTENTS /* Heimdal */
1150         krb5_free_error_contents(context, krberror);
1151 #else /* MIT */
1152         krb5_free_error(context, krberror);
1153 #endif
1154 }
1155
1156  krb5_error_code handle_krberror_packet(krb5_context context,
1157                                         krb5_data *packet)
1158 {
1159         krb5_error_code ret;
1160         bool got_error_code = false;
1161
1162         DEBUG(10,("handle_krberror_packet: got error packet\n"));
1163
1164 #ifdef HAVE_E_DATA_POINTER_IN_KRB5_ERROR /* Heimdal */
1165         {
1166                 krb5_error krberror;
1167
1168                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1169                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1170                                 error_message(ret)));
1171                         return ret;
1172                 }
1173
1174                 if (krberror.e_data == NULL || krberror.e_data->data == NULL) {
1175                         ret = (krb5_error_code) krberror.error_code;
1176                         got_error_code = true;
1177                 }
1178
1179                 smb_krb5_free_error(context, &krberror);
1180         }
1181 #else /* MIT */
1182         {
1183                 krb5_error *krberror;
1184
1185                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1186                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1187                                 error_message(ret)));
1188                         return ret;
1189                 }
1190
1191                 if (krberror->e_data.data == NULL) {
1192 #if defined(ERROR_TABLE_BASE_krb5)
1193                         ret = ERROR_TABLE_BASE_krb5 + (krb5_error_code) krberror->error;
1194 #else
1195                         ret = (krb5_error_code)krberror->error;
1196 #endif
1197                         got_error_code = true;
1198                 }
1199                 smb_krb5_free_error(context, krberror);
1200         }
1201 #endif
1202         if (got_error_code) {
1203                 DEBUG(5,("handle_krberror_packet: got KERBERR from kpasswd: %s (%d)\n", 
1204                         error_message(ret), ret));
1205         }
1206         return ret;
1207 }
1208
1209 krb5_error_code smb_krb5_get_init_creds_opt_alloc(krb5_context context,
1210                                             krb5_get_init_creds_opt **opt)
1211 {
1212         /* Heimdal or modern MIT version */
1213         return krb5_get_init_creds_opt_alloc(context, opt);
1214 }
1215
1216 void smb_krb5_get_init_creds_opt_free(krb5_context context,
1217                                 krb5_get_init_creds_opt *opt)
1218 {
1219         /* Modern MIT or Heimdal version */
1220         krb5_get_init_creds_opt_free(context, opt);
1221 }
1222
1223 krb5_enctype smb_get_enctype_from_kt_entry(krb5_keytab_entry *kt_entry)
1224 {
1225         return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1226 }
1227
1228 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1229                                         krb5_keytab_entry *kt_entry)
1230 {
1231 /* Try krb5_free_keytab_entry_contents first, since
1232  * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1233  * krb5_kt_free_entry but only has a prototype for the first, while the
1234  * second is considered private.
1235  */
1236 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1237         return krb5_free_keytab_entry_contents(context, kt_entry);
1238 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1239         return krb5_kt_free_entry(context, kt_entry);
1240 #else
1241 #error UNKNOWN_KT_FREE_FUNCTION
1242 #endif
1243 }
1244
1245
1246 /* caller needs to free etype_s */
1247 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1248                                            krb5_enctype enctype,
1249                                            char **etype_s)
1250 {
1251 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1252         return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1253 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1254         char buf[256];
1255         krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1256         if (ret) {
1257                 return ret;
1258         }
1259         *etype_s = SMB_STRDUP(buf);
1260         if (!*etype_s) {
1261                 return ENOMEM;
1262         }
1263         return ret;
1264 #else
1265 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1266 #endif
1267 }
1268
1269 /**********************************************************************
1270  * Open a krb5 keytab with flags, handles readonly or readwrite access and
1271  * allows to process non-default keytab names.
1272  * @param context krb5_context
1273  * @param keytab_name_req string
1274  * @param write_access bool if writable keytab is required
1275  * @param krb5_keytab pointer to krb5_keytab (close with krb5_kt_close())
1276  * @return krb5_error_code
1277 **********************************************************************/
1278
1279 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1280 #ifndef MAX_KEYTAB_NAME_LEN
1281 #define MAX_KEYTAB_NAME_LEN 1100
1282 #endif
1283
1284 krb5_error_code smb_krb5_open_keytab(krb5_context context,
1285                                      const char *keytab_name_req,
1286                                      bool write_access,
1287                                      krb5_keytab *keytab)
1288 {
1289         krb5_error_code ret = 0;
1290         TALLOC_CTX *mem_ctx;
1291         char keytab_string[MAX_KEYTAB_NAME_LEN];
1292         char *kt_str = NULL;
1293         bool found_valid_name = false;
1294         const char *pragma = "FILE";
1295         const char *tmp = NULL;
1296
1297         if (!write_access && !keytab_name_req) {
1298                 /* caller just wants to read the default keytab readonly, so be it */
1299                 return krb5_kt_default(context, keytab);
1300         }
1301
1302         mem_ctx = talloc_init("smb_krb5_open_keytab");
1303         if (!mem_ctx) {
1304                 return ENOMEM;
1305         }
1306
1307 #ifdef HAVE_WRFILE_KEYTAB
1308         if (write_access) {
1309                 pragma = "WRFILE";
1310         }
1311 #endif
1312
1313         if (keytab_name_req) {
1314
1315                 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1316                         ret = KRB5_CONFIG_NOTENUFSPACE;
1317                         goto out;
1318                 }
1319
1320                 if ((strncmp(keytab_name_req, "WRFILE:/", 8) == 0) ||
1321                     (strncmp(keytab_name_req, "FILE:/", 6) == 0)) {
1322                         tmp = keytab_name_req;
1323                         goto resolve;
1324                 }
1325
1326                 if (keytab_name_req[0] != '/') {
1327                         ret = KRB5_KT_BADNAME;
1328                         goto out;
1329                 }
1330
1331                 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1332                 if (!tmp) {
1333                         ret = ENOMEM;
1334                         goto out;
1335                 }
1336
1337                 goto resolve;
1338         }
1339
1340         /* we need to handle more complex keytab_strings, like:
1341          * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1342
1343         ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1344         if (ret) {
1345                 goto out;
1346         }
1347
1348         DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1349
1350         tmp = talloc_strdup(mem_ctx, keytab_string);
1351         if (!tmp) {
1352                 ret = ENOMEM;
1353                 goto out;
1354         }
1355
1356         if (strncmp(tmp, "ANY:", 4) == 0) {
1357                 tmp += 4;
1358         }
1359
1360         memset(&keytab_string, '\0', sizeof(keytab_string));
1361
1362         while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1363                 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1364                         found_valid_name = true;
1365                         tmp = kt_str;
1366                         tmp += 7;
1367                 }
1368
1369                 if (strncmp(kt_str, "FILE:", 5) == 0) {
1370                         found_valid_name = true;
1371                         tmp = kt_str;
1372                         tmp += 5;
1373                 }
1374
1375                 if (tmp[0] == '/') {
1376                         /* Treat as a FILE: keytab definition. */
1377                         found_valid_name = true;
1378                 }
1379
1380                 if (found_valid_name) {
1381                         if (tmp[0] != '/') {
1382                                 ret = KRB5_KT_BADNAME;
1383                                 goto out;
1384                         }
1385
1386                         tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1387                         if (!tmp) {
1388                                 ret = ENOMEM;
1389                                 goto out;
1390                         }
1391                         break;
1392                 }
1393         }
1394
1395         if (!found_valid_name) {
1396                 ret = KRB5_KT_UNKNOWN_TYPE;
1397                 goto out;
1398         }
1399
1400  resolve:
1401         DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1402         ret = krb5_kt_resolve(context, tmp, keytab);
1403
1404  out:
1405         TALLOC_FREE(mem_ctx);
1406         return ret;
1407 }
1408
1409 krb5_error_code smb_krb5_keytab_name(TALLOC_CTX *mem_ctx,
1410                                      krb5_context context,
1411                                      krb5_keytab keytab,
1412                                      const char **keytab_name)
1413 {
1414         char keytab_string[MAX_KEYTAB_NAME_LEN];
1415         krb5_error_code ret = 0;
1416
1417         ret = krb5_kt_get_name(context, keytab,
1418                                keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1419         if (ret) {
1420                 return ret;
1421         }
1422
1423         *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1424         if (!*keytab_name) {
1425                 return ENOMEM;
1426         }
1427
1428         return ret;
1429 }
1430
1431 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1432     defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1433     defined(HAVE_KRB5_GET_CREDS)
1434 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1435                                                              krb5_ccache ccache,
1436                                                              krb5_principal me,
1437                                                              krb5_principal server,
1438                                                              krb5_principal impersonate_princ,
1439                                                              krb5_creds **out_creds)
1440 {
1441         krb5_error_code ret;
1442         krb5_get_creds_opt opt;
1443
1444         ret = krb5_get_creds_opt_alloc(context, &opt);
1445         if (ret) {
1446                 goto done;
1447         }
1448         krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1449
1450         if (impersonate_princ) {
1451                 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1452                                                          impersonate_princ);
1453                 if (ret) {
1454                         goto done;
1455                 }
1456         }
1457
1458         ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1459         if (ret) {
1460                 goto done;
1461         }
1462
1463  done:
1464         if (opt) {
1465                 krb5_get_creds_opt_free(context, opt);
1466         }
1467         return ret;
1468 }
1469 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1470
1471 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1472
1473 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1474 krb5_error_code KRB5_CALLCONV
1475 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1476                               krb5_ccache ccache, krb5_creds *in_creds,
1477                               krb5_data *subject_cert,
1478                               krb5_creds **out_creds);
1479 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1480
1481 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1482                                                          krb5_ccache ccache,
1483                                                          krb5_principal me,
1484                                                          krb5_principal server,
1485                                                          krb5_principal impersonate_princ,
1486                                                          krb5_creds **out_creds)
1487 {
1488         krb5_error_code ret;
1489         krb5_creds in_creds;
1490
1491         ZERO_STRUCT(in_creds);
1492
1493         if (impersonate_princ) {
1494
1495                 in_creds.server = me;
1496                 in_creds.client = impersonate_princ;
1497
1498                 ret = krb5_get_credentials_for_user(context,
1499                                                     0, /* krb5_flags options */
1500                                                     ccache,
1501                                                     &in_creds,
1502                                                     NULL, /* krb5_data *subject_cert */
1503                                                     out_creds);
1504         } else {
1505                 in_creds.client = me;
1506                 in_creds.server = server;
1507
1508                 ret = krb5_get_credentials(context, 0, ccache,
1509                                            &in_creds, out_creds);
1510         }
1511
1512         return ret;
1513 }
1514 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1515
1516 /*
1517  * smb_krb5_get_credentials
1518  *
1519  * @brief Get krb5 credentials for a server
1520  *
1521  * @param[in] context           An initialized krb5_context
1522  * @param[in] ccache            An initialized krb5_ccache
1523  * @param[in] me                The krb5_principal of the caller
1524  * @param[in] server            The krb5_principal of the requested service
1525  * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1526  * @param[out] out_creds        The returned krb5_creds structure
1527  * @return krb5_error_code
1528  *
1529  */
1530 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1531                                          krb5_ccache ccache,
1532                                          krb5_principal me,
1533                                          krb5_principal server,
1534                                          krb5_principal impersonate_princ,
1535                                          krb5_creds **out_creds)
1536 {
1537         krb5_error_code ret;
1538         krb5_creds *creds = NULL;
1539
1540         if (out_creds != NULL) {
1541                 *out_creds = NULL;
1542         }
1543
1544         if (impersonate_princ) {
1545 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1546                 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1547 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1548                 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1549 #else
1550                 ret = ENOTSUP;
1551 #endif
1552         } else {
1553                 krb5_creds in_creds;
1554
1555                 ZERO_STRUCT(in_creds);
1556
1557                 in_creds.client = me;
1558                 in_creds.server = server;
1559
1560                 ret = krb5_get_credentials(context, 0, ccache,
1561                                            &in_creds, &creds);
1562         }
1563         if (ret) {
1564                 goto done;
1565         }
1566
1567         if (out_creds) {
1568                 *out_creds = creds;
1569         }
1570
1571  done:
1572         if (creds && ret) {
1573                 krb5_free_creds(context, creds);
1574         }
1575
1576         return ret;
1577 }
1578
1579 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
1580                                                 krb5_enctype enctype,
1581                                                 const void *data,
1582                                                 size_t length,
1583                                                 krb5_keyblock *key)
1584 {
1585 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
1586         return krb5_keyblock_init(context, enctype, data, length, key);
1587 #else
1588         memset(key, 0, sizeof(krb5_keyblock));
1589         KRB5_KEY_DATA(key) = SMB_MALLOC(length);
1590         if (NULL == KRB5_KEY_DATA(key)) {
1591                 return ENOMEM;
1592         }
1593         memcpy(KRB5_KEY_DATA(key), data, length);
1594         KRB5_KEY_LENGTH(key) = length;
1595         KRB5_KEY_TYPE(key) = enctype;
1596         return 0;
1597 #endif
1598 }
1599
1600 /*
1601   simulate a kinit, putting the tgt in the given credentials cache.
1602   Orignally by remus@snapserver.com
1603
1604   This version is built to use a keyblock, rather than needing the
1605   original password.
1606
1607   The impersonate_principal is the principal if NULL, or the principal
1608   to impersonate
1609
1610   The target_service defaults to the krbtgt if NULL, but could be
1611    kpasswd/realm or the local service (if we are doing s4u2self)
1612 */
1613 krb5_error_code kerberos_kinit_keyblock_cc(krb5_context ctx, krb5_ccache cc,
1614                                            krb5_principal principal,
1615                                            krb5_keyblock *keyblock,
1616                                            const char *target_service,
1617                                            krb5_get_init_creds_opt *krb_options,
1618                                            time_t *expire_time,
1619                                            time_t *kdc_time)
1620 {
1621         krb5_error_code code = 0;
1622         krb5_creds my_creds;
1623
1624 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
1625         code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
1626                                             keyblock, 0, target_service,
1627                                             krb_options);
1628 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
1629 {
1630 #define SMB_CREDS_KEYTAB "MEMORY:tmp_smb_creds_XXXXXX"
1631         char tmp_name[sizeof(SMB_CREDS_KEYTAB)];
1632         krb5_keytab_entry entry;
1633         krb5_keytab keytab;
1634         mode_t mask;
1635
1636         memset(&entry, 0, sizeof(entry));
1637         entry.principal = principal;
1638         *(KRB5_KT_KEY(&entry)) = *keyblock;
1639
1640         memcpy(tmp_name, SMB_CREDS_KEYTAB, sizeof(SMB_CREDS_KEYTAB));
1641         mask = umask(S_IRWXO | S_IRWXG);
1642         mktemp(tmp_name);
1643         umask(mask);
1644         if (tmp_name[0] == 0) {
1645                 return KRB5_KT_BADNAME;
1646         }
1647         code = krb5_kt_resolve(ctx, tmp_name, &keytab);
1648         if (code) {
1649                 return code;
1650         }
1651
1652         code = krb5_kt_add_entry(ctx, keytab, &entry);
1653         if (code) {
1654                 (void)krb5_kt_close(ctx, keytab);
1655                 goto done;
1656         }
1657
1658         code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
1659                                           keytab, 0, target_service,
1660                                           krb_options);
1661         (void)krb5_kt_close(ctx, keytab);
1662 }
1663 #else
1664 #error krb5_get_init_creds_keyblock not available!
1665 #endif
1666         if (code) {
1667                 return code;
1668         }
1669
1670         code = krb5_cc_initialize(ctx, cc, principal);
1671         if (code) {
1672                 goto done;
1673         }
1674
1675         code = krb5_cc_store_cred(ctx, cc, &my_creds);
1676         if (code) {
1677                 goto done;
1678         }
1679
1680         if (expire_time) {
1681                 *expire_time = (time_t) my_creds.times.endtime;
1682         }
1683
1684         if (kdc_time) {
1685                 *kdc_time = (time_t) my_creds.times.starttime;
1686         }
1687
1688         code = 0;
1689 done:
1690         krb5_free_cred_contents(ctx, &my_creds);
1691         return code;
1692 }
1693
1694 krb5_error_code kerberos_kinit_password_cc(krb5_context ctx, krb5_ccache cc,
1695                                            krb5_principal principal,
1696                                            const char *password,
1697                                            const char *target_service,
1698                                            krb5_get_init_creds_opt *krb_options,
1699                                            time_t *expire_time,
1700                                            time_t *kdc_time)
1701 {
1702         krb5_error_code code = 0;
1703         krb5_creds my_creds;
1704
1705         code = krb5_get_init_creds_password(ctx, &my_creds, principal,
1706                                             password, NULL, NULL, 0,
1707                                             target_service, krb_options);
1708         if (code) {
1709                 return code;
1710         }
1711
1712         code = krb5_cc_initialize(ctx, cc, principal);
1713         if (code) {
1714                 goto done;
1715         }
1716
1717         code = krb5_cc_store_cred(ctx, cc, &my_creds);
1718         if (code) {
1719                 goto done;
1720         }
1721
1722         if (expire_time) {
1723                 *expire_time = (time_t) my_creds.times.endtime;
1724         }
1725
1726         if (kdc_time) {
1727                 *kdc_time = (time_t) my_creds.times.starttime;
1728         }
1729
1730         code = 0;
1731 done:
1732         krb5_free_cred_contents(ctx, &my_creds);
1733         return code;
1734 }
1735
1736 #ifdef SAMBA4_USES_HEIMDAL
1737 /*
1738   simulate a kinit, putting the tgt in the given credentials cache.
1739   Orignally by remus@snapserver.com
1740
1741   The impersonate_principal is the principal
1742
1743   The self_service, should be the local service (for S4U2Self if
1744   impersonate_principal is given).
1745
1746   The target_service defaults to the krbtgt if NULL, but could be
1747   kpasswd/realm or a remote service (for S4U2Proxy)
1748
1749 */
1750 krb5_error_code kerberos_kinit_s4u2_cc(krb5_context ctx,
1751                                         krb5_ccache store_cc,
1752                                         krb5_principal init_principal,
1753                                         const char *init_password,
1754                                         krb5_principal impersonate_principal,
1755                                         const char *self_service,
1756                                         const char *target_service,
1757                                         krb5_get_init_creds_opt *krb_options,
1758                                         time_t *expire_time,
1759                                         time_t *kdc_time)
1760 {
1761         krb5_error_code code = 0;
1762         krb5_get_creds_opt options;
1763         krb5_principal store_principal;
1764         krb5_creds store_creds;
1765         krb5_creds *s4u2self_creds;
1766         Ticket s4u2self_ticket;
1767         size_t s4u2self_ticketlen;
1768         krb5_creds *s4u2proxy_creds;
1769         krb5_principal self_princ;
1770         bool s4u2proxy;
1771         krb5_principal target_princ;
1772         krb5_ccache tmp_cc;
1773         const char *self_realm;
1774         krb5_principal blacklist_principal = NULL;
1775         krb5_principal whitelist_principal = NULL;
1776
1777         code = krb5_get_init_creds_password(ctx, &store_creds,
1778                                             init_principal,
1779                                             init_password,
1780                                             NULL, NULL,
1781                                             0,
1782                                             NULL,
1783                                             krb_options);
1784         if (code != 0) {
1785                 return code;
1786         }
1787
1788         store_principal = init_principal;
1789
1790         /*
1791          * We are trying S4U2Self now:
1792          *
1793          * As we do not want to expose our TGT in the
1794          * krb5_ccache, which is also holds the impersonated creds.
1795          *
1796          * Some low level krb5/gssapi function might use the TGT
1797          * identity and let the client act as our machine account.
1798          *
1799          * We need to avoid that and use a temporary krb5_ccache
1800          * in order to pass our TGT to the krb5_get_creds() function.
1801          */
1802         code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
1803         if (code != 0) {
1804                 krb5_free_cred_contents(ctx, &store_creds);
1805                 return code;
1806         }
1807
1808         code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
1809         if (code != 0) {
1810                 krb5_cc_destroy(ctx, tmp_cc);
1811                 krb5_free_cred_contents(ctx, &store_creds);
1812                 return code;
1813         }
1814
1815         code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
1816         if (code != 0) {
1817                 krb5_free_cred_contents(ctx, &store_creds);
1818                 krb5_cc_destroy(ctx, tmp_cc);
1819                 return code;
1820         }
1821
1822         /*
1823          * we need to remember the client principal of our
1824          * TGT and make sure the KDC does not return this
1825          * in the impersonated tickets. This can happen
1826          * if the KDC does not support S4U2Self and S4U2Proxy.
1827          */
1828         blacklist_principal = store_creds.client;
1829         store_creds.client = NULL;
1830         krb5_free_cred_contents(ctx, &store_creds);
1831
1832         /*
1833          * Check if we also need S4U2Proxy or if S4U2Self is
1834          * enough in order to get a ticket for the target.
1835          */
1836         if (target_service == NULL) {
1837                 s4u2proxy = false;
1838         } else if (strcmp(target_service, self_service) == 0) {
1839                 s4u2proxy = false;
1840         } else {
1841                 s4u2proxy = true;
1842         }
1843
1844         /*
1845          * For S4U2Self we need our own service principal,
1846          * which belongs to our own realm (available on
1847          * our client principal).
1848          */
1849         self_realm = krb5_principal_get_realm(ctx, init_principal);
1850
1851         code = krb5_parse_name(ctx, self_service, &self_princ);
1852         if (code != 0) {
1853                 krb5_free_principal(ctx, blacklist_principal);
1854                 krb5_cc_destroy(ctx, tmp_cc);
1855                 return code;
1856         }
1857
1858         code = krb5_principal_set_realm(ctx, self_princ, self_realm);
1859         if (code != 0) {
1860                 krb5_free_principal(ctx, blacklist_principal);
1861                 krb5_free_principal(ctx, self_princ);
1862                 krb5_cc_destroy(ctx, tmp_cc);
1863                 return code;
1864         }
1865
1866         code = krb5_get_creds_opt_alloc(ctx, &options);
1867         if (code != 0) {
1868                 krb5_free_principal(ctx, blacklist_principal);
1869                 krb5_free_principal(ctx, self_princ);
1870                 krb5_cc_destroy(ctx, tmp_cc);
1871                 return code;
1872         }
1873
1874         if (s4u2proxy) {
1875                 /*
1876                  * If we want S4U2Proxy, we need the forwardable flag
1877                  * on the S4U2Self ticket.
1878                  */
1879                 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
1880         }
1881
1882         code = krb5_get_creds_opt_set_impersonate(ctx, options,
1883                                                   impersonate_principal);
1884         if (code != 0) {
1885                 krb5_get_creds_opt_free(ctx, options);
1886                 krb5_free_principal(ctx, blacklist_principal);
1887                 krb5_free_principal(ctx, self_princ);
1888                 krb5_cc_destroy(ctx, tmp_cc);
1889                 return code;
1890         }
1891
1892         code = krb5_get_creds(ctx, options, tmp_cc,
1893                               self_princ, &s4u2self_creds);
1894         krb5_get_creds_opt_free(ctx, options);
1895         krb5_free_principal(ctx, self_princ);
1896         if (code != 0) {
1897                 krb5_free_principal(ctx, blacklist_principal);
1898                 krb5_cc_destroy(ctx, tmp_cc);
1899                 return code;
1900         }
1901
1902         if (!s4u2proxy) {
1903                 krb5_cc_destroy(ctx, tmp_cc);
1904
1905                 /*
1906                  * Now make sure we store the impersonated principal
1907                  * and creds instead of the TGT related stuff
1908                  * in the krb5_ccache of the caller.
1909                  */
1910                 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
1911                                                 &store_creds);
1912                 krb5_free_creds(ctx, s4u2self_creds);
1913                 if (code != 0) {
1914                         return code;
1915                 }
1916
1917                 /*
1918                  * It's important to store the principal the KDC
1919                  * returned, as otherwise the caller would not find
1920                  * the S4U2Self ticket in the krb5_ccache lookup.
1921                  */
1922                 store_principal = store_creds.client;
1923                 goto store;
1924         }
1925
1926         /*
1927          * We are trying S4U2Proxy:
1928          *
1929          * We need the ticket from the S4U2Self step
1930          * and our TGT in order to get the delegated ticket.
1931          */
1932         code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
1933                              s4u2self_creds->ticket.length,
1934                              &s4u2self_ticket,
1935                              &s4u2self_ticketlen);
1936         if (code != 0) {
1937                 krb5_free_creds(ctx, s4u2self_creds);
1938                 krb5_free_principal(ctx, blacklist_principal);
1939                 krb5_cc_destroy(ctx, tmp_cc);
1940                 return code;
1941         }
1942
1943         /*
1944          * we need to remember the client principal of the
1945          * S4U2Self stage and as it needs to match the one we
1946          * will get for the S4U2Proxy stage. We need this
1947          * in order to detect KDCs which does not support S4U2Proxy.
1948          */
1949         whitelist_principal = s4u2self_creds->client;
1950         s4u2self_creds->client = NULL;
1951         krb5_free_creds(ctx, s4u2self_creds);
1952
1953         /*
1954          * For S4U2Proxy we also got a target service principal,
1955          * which also belongs to our own realm (available on
1956          * our client principal).
1957          */
1958         code = krb5_parse_name(ctx, target_service, &target_princ);
1959         if (code != 0) {
1960                 free_Ticket(&s4u2self_ticket);
1961                 krb5_free_principal(ctx, whitelist_principal);
1962                 krb5_free_principal(ctx, blacklist_principal);
1963                 krb5_cc_destroy(ctx, tmp_cc);
1964                 return code;
1965         }
1966
1967         code = krb5_principal_set_realm(ctx, target_princ, self_realm);
1968         if (code != 0) {
1969                 free_Ticket(&s4u2self_ticket);
1970                 krb5_free_principal(ctx, target_princ);
1971                 krb5_free_principal(ctx, whitelist_principal);
1972                 krb5_free_principal(ctx, blacklist_principal);
1973                 krb5_cc_destroy(ctx, tmp_cc);
1974                 return code;
1975         }
1976
1977         code = krb5_get_creds_opt_alloc(ctx, &options);
1978         if (code != 0) {
1979                 free_Ticket(&s4u2self_ticket);
1980                 krb5_free_principal(ctx, target_princ);
1981                 krb5_free_principal(ctx, whitelist_principal);
1982                 krb5_free_principal(ctx, blacklist_principal);
1983                 krb5_cc_destroy(ctx, tmp_cc);
1984                 return code;
1985         }
1986
1987         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
1988         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
1989
1990         code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
1991         free_Ticket(&s4u2self_ticket);
1992         if (code != 0) {
1993                 krb5_get_creds_opt_free(ctx, options);
1994                 krb5_free_principal(ctx, target_princ);
1995                 krb5_free_principal(ctx, whitelist_principal);
1996                 krb5_free_principal(ctx, blacklist_principal);
1997                 krb5_cc_destroy(ctx, tmp_cc);
1998                 return code;
1999         }
2000
2001         code = krb5_get_creds(ctx, options, tmp_cc,
2002                               target_princ, &s4u2proxy_creds);
2003         krb5_get_creds_opt_free(ctx, options);
2004         krb5_free_principal(ctx, target_princ);
2005         krb5_cc_destroy(ctx, tmp_cc);
2006         if (code != 0) {
2007                 krb5_free_principal(ctx, whitelist_principal);
2008                 krb5_free_principal(ctx, blacklist_principal);
2009                 return code;
2010         }
2011
2012         /*
2013          * Now make sure we store the impersonated principal
2014          * and creds instead of the TGT related stuff
2015          * in the krb5_ccache of the caller.
2016          */
2017         code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2018                                         &store_creds);
2019         krb5_free_creds(ctx, s4u2proxy_creds);
2020         if (code != 0) {
2021                 krb5_free_principal(ctx, whitelist_principal);
2022                 krb5_free_principal(ctx, blacklist_principal);
2023                 return code;
2024         }
2025
2026         /*
2027          * It's important to store the principal the KDC
2028          * returned, as otherwise the caller would not find
2029          * the S4U2Self ticket in the krb5_ccache lookup.
2030          */
2031         store_principal = store_creds.client;
2032
2033  store:
2034         if (blacklist_principal &&
2035             krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2036                 char *sp = NULL;
2037                 char *ip = NULL;
2038
2039                 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2040                 if (code != 0) {
2041                         sp = NULL;
2042                 }
2043                 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2044                 if (code != 0) {
2045                         ip = NULL;
2046                 }
2047                 DEBUG(1, ("kerberos_kinit_password_cc: "
2048                           "KDC returned self principal[%s] while impersonating [%s]\n",
2049                           sp?sp:"<no memory>",
2050                           ip?ip:"<no memory>"));
2051
2052                 SAFE_FREE(sp);
2053                 SAFE_FREE(ip);
2054
2055                 krb5_free_principal(ctx, whitelist_principal);
2056                 krb5_free_principal(ctx, blacklist_principal);
2057                 krb5_free_cred_contents(ctx, &store_creds);
2058                 return KRB5_FWD_BAD_PRINCIPAL;
2059         }
2060         if (blacklist_principal) {
2061                 krb5_free_principal(ctx, blacklist_principal);
2062         }
2063
2064         if (whitelist_principal &&
2065             !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2066                 char *sp = NULL;
2067                 char *ep = NULL;
2068
2069                 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2070                 if (code != 0) {
2071                         sp = NULL;
2072                 }
2073                 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2074                 if (code != 0) {
2075                         ep = NULL;
2076                 }
2077                 DEBUG(1, ("kerberos_kinit_password_cc: "
2078                           "KDC returned wrong principal[%s] we expected [%s]\n",
2079                           sp?sp:"<no memory>",
2080                           ep?ep:"<no memory>"));
2081
2082                 SAFE_FREE(sp);
2083                 SAFE_FREE(ep);
2084
2085                 krb5_free_principal(ctx, whitelist_principal);
2086                 krb5_free_cred_contents(ctx, &store_creds);
2087                 return KRB5_FWD_BAD_PRINCIPAL;
2088         }
2089         if (whitelist_principal) {
2090                 krb5_free_principal(ctx, whitelist_principal);
2091         }
2092
2093         code = krb5_cc_initialize(ctx, store_cc, store_principal);
2094         if (code != 0) {
2095                 krb5_free_cred_contents(ctx, &store_creds);
2096                 return code;
2097         }
2098
2099         code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2100         if (code != 0) {
2101                 krb5_free_cred_contents(ctx, &store_creds);
2102                 return code;
2103         }
2104
2105         if (expire_time) {
2106                 *expire_time = (time_t) store_creds.times.endtime;
2107         }
2108
2109         if (kdc_time) {
2110                 *kdc_time = (time_t) store_creds.times.starttime;
2111         }
2112
2113         krb5_free_cred_contents(ctx, &store_creds);
2114
2115         return 0;
2116 }
2117 #endif
2118
2119 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2120 krb5_error_code smb_krb5_make_principal(krb5_context context,
2121                                         krb5_principal *principal,
2122                                         const char *_realm, ...)
2123 {
2124         krb5_error_code code;
2125         bool free_realm;
2126         char *realm;
2127         va_list ap;
2128
2129         if (_realm) {
2130                 realm = _realm;
2131                 free_realm = false;
2132         } else {
2133                 code = krb5_get_default_realm(context, &realm);
2134                 if (code) {
2135                         return code;
2136                 }
2137                 free_realm = true;
2138         }
2139
2140         va_start(ap, _realm);
2141         code = krb5_build_principal_alloc_va(context, principal,
2142                                              strlen(realm), realm,
2143                                              ap);
2144         va_end(ap);
2145
2146         if (free_realm) {
2147                 krb5_free_default_realm(context, realm);
2148         }
2149
2150         return code;
2151 }
2152 #endif
2153
2154 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2155 /**
2156  * @brief Get the lifetime of the initial ticket in the cache.
2157  *
2158  * @param[in]  context  The kerberos context.
2159  *
2160  * @param[in]  id       The credential cache to get the ticket lifetime.
2161  *
2162  * @param[out] t        A pointer to a time value to store the lifetime.
2163  *
2164  * @return              0 on success, a krb5_error_code on error.
2165  */
2166 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2167                                          krb5_ccache id,
2168                                          time_t *t)
2169 {
2170         krb5_cc_cursor cursor;
2171         krb5_error_code kerr;
2172         krb5_creds cred;
2173         krb5_timestamp now;
2174
2175         *t = 0;
2176
2177         kerr = krb5_timeofday(context, &now);
2178         if (kerr) {
2179                 return kerr;
2180         }
2181
2182         kerr = krb5_cc_start_seq_get(context, id, &cursor);
2183         if (kerr) {
2184                 return kerr;
2185         }
2186
2187         while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2188 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2189                 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2190 #else
2191                 if (cred.flags.b.initial) {
2192 #endif
2193                         if (now < cred.times.endtime) {
2194                                 *t = (time_t) (cred.times.endtime - now);
2195                         }
2196                         krb5_free_cred_contents(context, &cred);
2197                         break;
2198                 }
2199                 krb5_free_cred_contents(context, &cred);
2200         }
2201
2202         krb5_cc_end_seq_get(context, id, &cursor);
2203
2204         return kerr;
2205 }
2206 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2207
2208 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2209 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2210 {
2211         free_Checksum(cksum);
2212 }
2213 #endif
2214
2215 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2216                                            DATA_BLOB *pac_data,
2217                                            krb5_context context,
2218                                            const krb5_keyblock *keyblock,
2219                                            uint32_t *sig_type,
2220                                            DATA_BLOB *sig_blob)
2221 {
2222         krb5_error_code ret;
2223         krb5_checksum cksum;
2224 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2225         krb5_crypto crypto;
2226
2227
2228         ret = krb5_crypto_init(context,
2229                                keyblock,
2230                                0,
2231                                &crypto);
2232         if (ret) {
2233                 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2234                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2235                 return ret;
2236         }
2237         ret = krb5_create_checksum(context,
2238                                    crypto,
2239                                    KRB5_KU_OTHER_CKSUM,
2240                                    0,
2241                                    pac_data->data,
2242                                    pac_data->length,
2243                                    &cksum);
2244         if (ret) {
2245                 DEBUG(2, ("PAC Verification failed: %s\n",
2246                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2247         }
2248
2249         krb5_crypto_destroy(context, crypto);
2250
2251         if (ret) {
2252                 return ret;
2253         }
2254
2255         *sig_type = cksum.cksumtype;
2256         *sig_blob = data_blob_talloc(mem_ctx,
2257                                         cksum.checksum.data,
2258                                         cksum.checksum.length);
2259 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2260         krb5_data input;
2261
2262         input.data = (char *)pac_data->data;
2263         input.length = pac_data->length;
2264
2265         ret = krb5_c_make_checksum(context,
2266                                    0,
2267                                    keyblock,
2268                                    KRB5_KEYUSAGE_APP_DATA_CKSUM,
2269                                    &input,
2270                                    &cksum);
2271         if (ret) {
2272                 DEBUG(2, ("PAC Verification failed: %s\n",
2273                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2274                 return ret;
2275         }
2276
2277         *sig_type = cksum.checksum_type;
2278         *sig_blob = data_blob_talloc(mem_ctx,
2279                                         cksum.contents,
2280                                         cksum.length);
2281
2282 #else
2283 #error krb5_create_checksum or krb5_c_make_checksum not available
2284 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2285         smb_krb5_free_checksum_contents(context, &cksum);
2286
2287         return 0;
2288 }
2289
2290
2291 /*
2292  * smb_krb5_principal_get_realm
2293  *
2294  * @brief Get realm of a principal
2295  *
2296  * @param[in] context           The krb5_context
2297  * @param[in] principal         The principal
2298  * @return pointer to the realm
2299  *
2300  */
2301
2302 char *smb_krb5_principal_get_realm(krb5_context context,
2303                                    krb5_principal principal)
2304 {
2305 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2306         return discard_const_p(char, krb5_principal_get_realm(context, principal));
2307 #elif defined(krb5_princ_realm) /* MIT */
2308         krb5_data *realm;
2309         realm = krb5_princ_realm(context, principal);
2310         return discard_const_p(char, realm->data);
2311 #else
2312         return NULL;
2313 #endif
2314 }
2315
2316 /************************************************************************
2317  Routine to get the default realm from the kerberos credentials cache.
2318  Caller must free if the return value is not NULL.
2319 ************************************************************************/
2320
2321 static char *smb_krb5_get_default_realm_from_ccache(TALLOC_CTX *mem_ctx)
2322 {
2323         char *realm = NULL;
2324         krb5_context ctx = NULL;
2325         krb5_ccache cc = NULL;
2326         krb5_principal princ = NULL;
2327
2328         initialize_krb5_error_table();
2329         if (krb5_init_context(&ctx)) {
2330                 return NULL;
2331         }
2332
2333         DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2334                 "Trying to read krb5 cache: %s\n",
2335                 krb5_cc_default_name(ctx)));
2336         if (krb5_cc_default(ctx, &cc)) {
2337                 DEBUG(0,("kerberos_get_default_realm_from_ccache: "
2338                         "failed to read default cache\n"));
2339                 goto out;
2340         }
2341         if (krb5_cc_get_principal(ctx, cc, &princ)) {
2342                 DEBUG(0,("kerberos_get_default_realm_from_ccache: "
2343                         "failed to get default principal\n"));
2344                 goto out;
2345         }
2346
2347 #if defined(HAVE_KRB5_PRINCIPAL_GET_REALM)
2348         realm = talloc_strdup(mem_ctx, krb5_principal_get_realm(ctx, princ));
2349 #elif defined(HAVE_KRB5_PRINC_REALM)
2350         {
2351                 krb5_data *realm_data = krb5_princ_realm(ctx, princ);
2352                 realm = talloc_strndup(mem_ctx, realm_data->data, realm_data->length);
2353         }
2354 #endif
2355
2356   out:
2357
2358         if (ctx) {
2359                 if (princ) {
2360                         krb5_free_principal(ctx, princ);
2361                 }
2362                 if (cc) {
2363                         krb5_cc_close(ctx, cc);
2364                 }
2365                 krb5_free_context(ctx);
2366         }
2367
2368         return realm;
2369 }
2370
2371 /************************************************************************
2372  Routine to get the realm from a given DNS name.
2373 ************************************************************************/
2374
2375 static char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2376                                                 const char *hostname)
2377 {
2378 #if defined(HAVE_KRB5_REALM_TYPE)
2379         /* Heimdal. */
2380         krb5_realm *realm_list = NULL;
2381 #else
2382         /* MIT */
2383         char **realm_list = NULL;
2384 #endif
2385         char *realm = NULL;
2386         krb5_error_code kerr;
2387         krb5_context ctx = NULL;
2388
2389         initialize_krb5_error_table();
2390         if (krb5_init_context(&ctx)) {
2391                 return NULL;
2392         }
2393
2394         kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
2395         if (kerr != 0) {
2396                 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
2397                         "failed %s\n",
2398                         hostname ? hostname : "(NULL)",
2399                         error_message(kerr) ));
2400                 goto out;
2401         }
2402
2403         if (realm_list && realm_list[0]) {
2404                 realm = talloc_strdup(mem_ctx, realm_list[0]);
2405         }
2406
2407   out:
2408
2409         if (ctx) {
2410                 if (realm_list) {
2411                         krb5_free_host_realm(ctx, realm_list);
2412                         realm_list = NULL;
2413                 }
2414                 krb5_free_context(ctx);
2415                 ctx = NULL;
2416         }
2417         return realm;
2418 }
2419
2420 char *kerberos_get_principal_from_service_hostname(TALLOC_CTX *mem_ctx,
2421                                                    const char *service,
2422                                                    const char *remote_name,
2423                                                    const char *default_realm)
2424 {
2425         char *realm = NULL;
2426         char *host = NULL;
2427         char *principal;
2428         host = strchr_m(remote_name, '.');
2429         if (host) {
2430                 /* DNS name. */
2431                 realm = smb_krb5_get_realm_from_hostname(talloc_tos(),
2432                                                          remote_name);
2433         } else {
2434                 /* NetBIOS name - use our realm. */
2435                 realm = smb_krb5_get_default_realm_from_ccache(talloc_tos());
2436         }
2437
2438         if (realm == NULL || *realm == '\0') {
2439                 realm = talloc_strdup(talloc_tos(), default_realm);
2440                 if (!realm) {
2441                         return NULL;
2442                 }
2443                 DEBUG(3,("kerberos_get_principal_from_service_hostname: "
2444                          "cannot get realm from, "
2445                          "desthost %s or default ccache. Using default "
2446                          "smb.conf realm %s\n",
2447                          remote_name,
2448                          realm));
2449         }
2450
2451         principal = talloc_asprintf(mem_ctx,
2452                                     "%s/%s@%s",
2453                                     service, remote_name,
2454                                     realm);
2455         TALLOC_FREE(realm);
2456         return principal;
2457 }
2458
2459 char *smb_get_krb5_error_message(krb5_context context,
2460                                  krb5_error_code code,
2461                                  TALLOC_CTX *mem_ctx)
2462 {
2463         char *ret;
2464
2465 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
2466         const char *context_error = krb5_get_error_message(context, code);
2467         if (context_error) {
2468                 ret = talloc_asprintf(mem_ctx, "%s: %s",
2469                                         error_message(code), context_error);
2470                 krb5_free_error_message(context, context_error);
2471                 return ret;
2472         }
2473 #endif
2474         ret = talloc_strdup(mem_ctx, error_message(code));
2475         return ret;
2476 }
2477
2478
2479 /**
2480 * @brief Return the kerberos library setting for "libdefaults:allow_weak_crypto"
2481 *
2482 * @param context        The krb5_context
2483 *
2484 * @return krb5_boolean
2485 *
2486 * Function returns true if weak crypto is allowd, false if not
2487 */
2488
2489 krb5_boolean smb_krb5_get_allowed_weak_crypto(krb5_context context)
2490 #if defined(HAVE_KRB5_CONFIG_GET_BOOL_DEFAULT)
2491 {
2492         return krb5_config_get_bool_default(context,
2493                                             NULL,
2494                                             FALSE,
2495                                             "libdefaults",
2496                                             "allow_weak_crypto",
2497                                             NULL);
2498 }
2499 #elif defined(HAVE_PROFILE_H) && defined(HAVE_KRB5_GET_PROFILE)
2500 {
2501 #include <profile.h>
2502         krb5_error_code ret;
2503         krb5_boolean ret_default = false;
2504         profile_t profile;
2505         int ret_profile;
2506
2507         ret = krb5_get_profile(context,
2508                                &profile);
2509         if (ret) {
2510                 return ret_default;
2511         }
2512
2513         ret = profile_get_boolean(profile,
2514                                   "libdefaults",
2515                                   "allow_weak_crypto",
2516                                   NULL, /* subsubname */
2517                                   ret_default, /* def_val */
2518                                   &ret_profile /* *ret_default */);
2519         if (ret) {
2520                 return ret_default;
2521         }
2522
2523         profile_release(profile);
2524
2525         return ret_profile;
2526 }
2527 #else
2528 #error UNKNOWN_KRB5_CONFIG_ROUTINES
2529 #endif
2530
2531 #else /* HAVE_KRB5 */
2532  /* this saves a few linking headaches */
2533  int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
2534                         const char *principal, time_t time_offset,
2535                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
2536                         uint32_t extra_ap_opts,
2537                         const char *ccname, time_t *tgs_expire,
2538                         const char *impersonate_princ_s)
2539 {
2540          DEBUG(0,("NO KERBEROS SUPPORT\n"));
2541          return 1;
2542 }
2543
2544 #endif /* HAVE_KRB5 */