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