lib:krb5_wrap:krb5_samba: increase debug level for smb_krb5_get_default_realm_from_cc...
[samba.git] / lib / krb5_wrap / krb5_samba.c
1 /*
2    Unix SMB/CIFS implementation.
3    simple kerberos5 routines for active directory
4    Copyright (C) Andrew Tridgell 2001
5    Copyright (C) Luke Howard 2002-2003
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
7    Copyright (C) Guenther Deschner 2005-2009
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "system/filesys.h"
25 #include "krb5_samba.h"
26 #include "lib/util/asn1.h"
27
28 #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 omitted, 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_const_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 #ifdef HAVE_KRB5_AUTH_CON_GETRECVSUBKEY
870                 err = krb5_auth_con_getrecvsubkey(context,
871                                                   auth_context,
872                                                   &skey);
873 #else /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
874                 err = krb5_auth_con_getremotesubkey(context,
875                                                     auth_context, &skey);
876 #endif /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
877         } else {
878 #ifdef HAVE_KRB5_AUTH_CON_GETSENDSUBKEY
879                 err = krb5_auth_con_getsendsubkey(context,
880                                                   auth_context,
881                                                   &skey);
882 #else /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
883                 err = krb5_auth_con_getlocalsubkey(context,
884                                                    auth_context, &skey);
885 #endif /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
886         }
887
888         if (err || skey == NULL) {
889                 DEBUG(10, ("KRB5 error getting session key %d\n", err));
890                 goto done;
891         }
892
893         DEBUG(10, ("Got KRB5 session key of length %d\n",
894                    (int)KRB5_KEY_LENGTH(skey)));
895
896         *session_key = data_blob_talloc(mem_ctx,
897                                          KRB5_KEY_DATA(skey),
898                                          KRB5_KEY_LENGTH(skey));
899         dump_data_pw("KRB5 Session Key:\n",
900                      session_key->data,
901                      session_key->length);
902
903         ret = true;
904
905 done:
906         if (skey) {
907                 krb5_free_keyblock(context, skey);
908         }
909
910         return ret;
911 }
912
913
914 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
915  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i );
916
917  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i )
918 {
919         static krb5_data kdata;
920
921         kdata.data = discard_const_p(char, krb5_principal_get_comp_string(context, principal, i));
922         kdata.length = strlen((const char *)kdata.data);
923         return &kdata;
924 }
925 #endif
926
927 /*
928  * @brief Get talloced string component of a principal
929  *
930  * @param[in] mem_ctx           The TALLOC_CTX
931  * @param[in] context           The krb5_context
932  * @param[in] principal         The principal
933  * @param[in] component         The component
934  * @return string component
935  *
936  * Caller must talloc_free if the return value is not NULL.
937  *
938  */
939
940 /* caller has to free returned string with talloc_free() */
941 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
942                                          krb5_context context,
943                                          krb5_const_principal principal,
944                                          unsigned int component)
945 {
946 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
947         return talloc_strdup(mem_ctx, krb5_principal_get_comp_string(context, principal, component));
948 #else
949         krb5_data *data;
950
951         if (component >= krb5_princ_size(context, principal)) {
952                 return NULL;
953         }
954
955         data = krb5_princ_component(context, principal, component);
956         if (data == NULL) {
957                 return NULL;
958         }
959
960         return talloc_strndup(mem_ctx, data->data, data->length);
961 #endif
962 }
963
964 /* Prototypes */
965
966  krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,       /* FILE:/tmp/krb5cc_0 */
967                                        const char *client_string,       /* gd@BER.SUSE.DE */
968                                        const char *service_string,      /* krbtgt/BER.SUSE.DE@BER.SUSE.DE */
969                                        time_t *expire_time)
970 {
971         krb5_error_code ret;
972         krb5_context context = NULL;
973         krb5_ccache ccache = NULL;
974         krb5_principal client = NULL;
975         krb5_creds creds, creds_in;
976
977         ZERO_STRUCT(creds);
978         ZERO_STRUCT(creds_in);
979
980         initialize_krb5_error_table();
981         ret = krb5_init_context(&context);
982         if (ret) {
983                 goto done;
984         }
985
986         if (!ccache_string) {
987                 ccache_string = krb5_cc_default_name(context);
988         }
989
990         if (!ccache_string) {
991                 ret = EINVAL;
992                 goto done;
993         }
994
995         DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
996
997         /* FIXME: we should not fall back to defaults */
998         ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
999         if (ret) {
1000                 goto done;
1001         }
1002
1003         if (client_string) {
1004                 ret = smb_krb5_parse_name(context, client_string, &client);
1005                 if (ret) {
1006                         goto done;
1007                 }
1008         } else {
1009                 ret = krb5_cc_get_principal(context, ccache, &client);
1010                 if (ret) {
1011                         goto done;
1012                 }
1013         }
1014
1015         ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
1016         if (ret) {
1017                 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
1018                 goto done;
1019         }
1020
1021         /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
1022         ret = krb5_cc_initialize(context, ccache, client);
1023         if (ret) {
1024                 goto done;
1025         }
1026
1027         ret = krb5_cc_store_cred(context, ccache, &creds);
1028
1029         if (expire_time) {
1030                 *expire_time = (time_t) creds.times.endtime;
1031         }
1032
1033 done:
1034         krb5_free_cred_contents(context, &creds_in);
1035         krb5_free_cred_contents(context, &creds);
1036
1037         if (client) {
1038                 krb5_free_principal(context, client);
1039         }
1040         if (ccache) {
1041                 krb5_cc_close(context, ccache);
1042         }
1043         if (context) {
1044                 krb5_free_context(context);
1045         }
1046
1047         return ret;
1048 }
1049
1050  krb5_error_code smb_krb5_free_addresses(krb5_context context, smb_krb5_addresses *addr)
1051 {
1052         krb5_error_code ret = 0;
1053         if (addr == NULL) {
1054                 return ret;
1055         }
1056 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1057         krb5_free_addresses(context, addr->addrs);
1058 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1059         ret = krb5_free_addresses(context, addr->addrs);
1060         SAFE_FREE(addr->addrs);
1061 #endif
1062         SAFE_FREE(addr);
1063         addr = NULL;
1064         return ret;
1065 }
1066
1067 #define MAX_NETBIOSNAME_LEN 16
1068  krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
1069                                                    const char *netbios_name)
1070 {
1071         krb5_error_code ret = 0;
1072         char buf[MAX_NETBIOSNAME_LEN];
1073         int len;
1074 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1075         krb5_address **addrs = NULL;
1076 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1077         krb5_addresses *addrs = NULL;
1078 #endif
1079
1080         *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1081         if (*kerb_addr == NULL) {
1082                 return ENOMEM;
1083         }
1084
1085         /* temporarily duplicate put_name() code here to avoid dependency
1086          * issues for a 5 lines function */
1087         len = strlen(netbios_name);
1088         memcpy(buf, netbios_name,
1089                 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
1090         if (len < MAX_NETBIOSNAME_LEN - 1) {
1091                 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
1092         }
1093         buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
1094
1095 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1096         {
1097                 int num_addr = 2;
1098
1099                 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1100                 if (addrs == NULL) {
1101                         SAFE_FREE(*kerb_addr);
1102                         return ENOMEM;
1103                 }
1104
1105                 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1106
1107                 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1108                 if (addrs[0] == NULL) {
1109                         SAFE_FREE(addrs);
1110                         SAFE_FREE(*kerb_addr);
1111                         return ENOMEM;
1112                 }
1113
1114                 addrs[0]->magic = KV5M_ADDRESS;
1115                 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1116                 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1117                 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1118                 if (addrs[0]->contents == NULL) {
1119                         SAFE_FREE(addrs[0]);
1120                         SAFE_FREE(addrs);
1121                         SAFE_FREE(*kerb_addr);
1122                         return ENOMEM;
1123                 }
1124
1125                 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1126
1127                 addrs[1] = NULL;
1128         }
1129 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1130         {
1131                 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1132                 if (addrs == NULL) {
1133                         SAFE_FREE(*kerb_addr);
1134                         return ENOMEM;
1135                 }
1136
1137                 memset(addrs, 0, sizeof(krb5_addresses));
1138
1139                 addrs->len = 1;
1140                 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1141                 if (addrs->val == NULL) {
1142                         SAFE_FREE(addrs);
1143                         SAFE_FREE(kerb_addr);
1144                         return ENOMEM;
1145                 }
1146
1147                 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1148                 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1149                 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1150                 if (addrs->val[0].address.data == NULL) {
1151                         SAFE_FREE(addrs->val);
1152                         SAFE_FREE(addrs);
1153                         SAFE_FREE(*kerb_addr);
1154                         return ENOMEM;
1155                 }
1156
1157                 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1158         }
1159 #else
1160 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1161 #endif
1162         (*kerb_addr)->addrs = addrs;
1163
1164         return ret;
1165 }
1166
1167  void smb_krb5_free_error(krb5_context context, krb5_error *krberror)
1168 {
1169 #ifdef HAVE_KRB5_FREE_ERROR_CONTENTS /* Heimdal */
1170         krb5_free_error_contents(context, krberror);
1171 #else /* MIT */
1172         krb5_free_error(context, krberror);
1173 #endif
1174 }
1175
1176  krb5_error_code handle_krberror_packet(krb5_context context,
1177                                         krb5_data *packet)
1178 {
1179         krb5_error_code ret;
1180         bool got_error_code = false;
1181
1182         DEBUG(10,("handle_krberror_packet: got error packet\n"));
1183
1184 #ifdef HAVE_E_DATA_POINTER_IN_KRB5_ERROR /* Heimdal */
1185         {
1186                 krb5_error krberror;
1187
1188                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1189                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1190                                 error_message(ret)));
1191                         return ret;
1192                 }
1193
1194                 if (krberror.e_data == NULL || krberror.e_data->data == NULL) {
1195                         ret = (krb5_error_code) krberror.error_code;
1196                         got_error_code = true;
1197                 }
1198
1199                 smb_krb5_free_error(context, &krberror);
1200         }
1201 #else /* MIT */
1202         {
1203                 krb5_error *krberror;
1204
1205                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1206                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1207                                 error_message(ret)));
1208                         return ret;
1209                 }
1210
1211                 if (krberror->e_data.data == NULL) {
1212 #if defined(ERROR_TABLE_BASE_krb5)
1213                         ret = ERROR_TABLE_BASE_krb5 + (krb5_error_code) krberror->error;
1214 #else
1215                         ret = (krb5_error_code)krberror->error;
1216 #endif
1217                         got_error_code = true;
1218                 }
1219                 smb_krb5_free_error(context, krberror);
1220         }
1221 #endif
1222         if (got_error_code) {
1223                 DEBUG(5,("handle_krberror_packet: got KERBERR from kpasswd: %s (%d)\n", 
1224                         error_message(ret), ret));
1225         }
1226         return ret;
1227 }
1228
1229 krb5_error_code smb_krb5_get_init_creds_opt_alloc(krb5_context context,
1230                                             krb5_get_init_creds_opt **opt)
1231 {
1232         /* Heimdal or modern MIT version */
1233         return krb5_get_init_creds_opt_alloc(context, opt);
1234 }
1235
1236 void smb_krb5_get_init_creds_opt_free(krb5_context context,
1237                                 krb5_get_init_creds_opt *opt)
1238 {
1239         /* Modern MIT or Heimdal version */
1240         krb5_get_init_creds_opt_free(context, opt);
1241 }
1242
1243 krb5_enctype smb_get_enctype_from_kt_entry(krb5_keytab_entry *kt_entry)
1244 {
1245         return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1246 }
1247
1248 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1249                                         krb5_keytab_entry *kt_entry)
1250 {
1251 /* Try krb5_free_keytab_entry_contents first, since
1252  * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1253  * krb5_kt_free_entry but only has a prototype for the first, while the
1254  * second is considered private.
1255  */
1256 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1257         return krb5_free_keytab_entry_contents(context, kt_entry);
1258 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1259         return krb5_kt_free_entry(context, kt_entry);
1260 #else
1261 #error UNKNOWN_KT_FREE_FUNCTION
1262 #endif
1263 }
1264
1265
1266 /* caller needs to free etype_s */
1267 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1268                                            krb5_enctype enctype,
1269                                            char **etype_s)
1270 {
1271 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1272         return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1273 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1274         char buf[256];
1275         krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1276         if (ret) {
1277                 return ret;
1278         }
1279         *etype_s = SMB_STRDUP(buf);
1280         if (!*etype_s) {
1281                 return ENOMEM;
1282         }
1283         return ret;
1284 #else
1285 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1286 #endif
1287 }
1288
1289 /**********************************************************************
1290  * Open a krb5 keytab with flags, handles readonly or readwrite access and
1291  * allows one to process non-default keytab names.
1292  * @param context krb5_context
1293  * @param keytab_name_req string
1294  * @param write_access bool if writable keytab is required
1295  * @param krb5_keytab pointer to krb5_keytab (close with krb5_kt_close())
1296  * @return krb5_error_code
1297 **********************************************************************/
1298
1299 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1300 #ifndef MAX_KEYTAB_NAME_LEN
1301 #define MAX_KEYTAB_NAME_LEN 1100
1302 #endif
1303
1304 krb5_error_code smb_krb5_open_keytab_relative(krb5_context context,
1305                                               const char *keytab_name_req,
1306                                               bool write_access,
1307                                               krb5_keytab *keytab)
1308 {
1309         krb5_error_code ret = 0;
1310         TALLOC_CTX *mem_ctx;
1311         char keytab_string[MAX_KEYTAB_NAME_LEN];
1312         char *kt_str = NULL;
1313         bool found_valid_name = false;
1314         const char *pragma = "FILE";
1315         const char *tmp = NULL;
1316
1317         if (!write_access && !keytab_name_req) {
1318                 /* caller just wants to read the default keytab readonly, so be it */
1319                 return krb5_kt_default(context, keytab);
1320         }
1321
1322         mem_ctx = talloc_init("smb_krb5_open_keytab");
1323         if (!mem_ctx) {
1324                 return ENOMEM;
1325         }
1326
1327 #ifdef HAVE_WRFILE_KEYTAB
1328         if (write_access) {
1329                 pragma = "WRFILE";
1330         }
1331 #endif
1332
1333         if (keytab_name_req) {
1334
1335                 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1336                         ret = KRB5_CONFIG_NOTENUFSPACE;
1337                         goto out;
1338                 }
1339
1340                 if ((strncmp(keytab_name_req, "WRFILE:/", 8) == 0) ||
1341                     (strncmp(keytab_name_req, "FILE:/", 6) == 0)) {
1342                         tmp = keytab_name_req;
1343                         goto resolve;
1344                 }
1345
1346                 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1347                 if (!tmp) {
1348                         ret = ENOMEM;
1349                         goto out;
1350                 }
1351
1352                 goto resolve;
1353         }
1354
1355         /* we need to handle more complex keytab_strings, like:
1356          * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1357
1358         ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1359         if (ret) {
1360                 goto out;
1361         }
1362
1363         DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1364
1365         tmp = talloc_strdup(mem_ctx, keytab_string);
1366         if (!tmp) {
1367                 ret = ENOMEM;
1368                 goto out;
1369         }
1370
1371         if (strncmp(tmp, "ANY:", 4) == 0) {
1372                 tmp += 4;
1373         }
1374
1375         memset(&keytab_string, '\0', sizeof(keytab_string));
1376
1377         while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1378                 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1379                         found_valid_name = true;
1380                         tmp = kt_str;
1381                         tmp += 7;
1382                 }
1383
1384                 if (strncmp(kt_str, "FILE:", 5) == 0) {
1385                         found_valid_name = true;
1386                         tmp = kt_str;
1387                         tmp += 5;
1388                 }
1389
1390                 if (tmp[0] == '/') {
1391                         /* Treat as a FILE: keytab definition. */
1392                         found_valid_name = true;
1393                 }
1394
1395                 if (found_valid_name) {
1396                         if (tmp[0] != '/') {
1397                                 ret = KRB5_KT_BADNAME;
1398                                 goto out;
1399                         }
1400
1401                         tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1402                         if (!tmp) {
1403                                 ret = ENOMEM;
1404                                 goto out;
1405                         }
1406                         break;
1407                 }
1408         }
1409
1410         if (!found_valid_name) {
1411                 ret = KRB5_KT_UNKNOWN_TYPE;
1412                 goto out;
1413         }
1414
1415  resolve:
1416         DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1417         ret = krb5_kt_resolve(context, tmp, keytab);
1418
1419  out:
1420         TALLOC_FREE(mem_ctx);
1421         return ret;
1422 }
1423
1424 krb5_error_code smb_krb5_open_keytab(krb5_context context,
1425                                      const char *keytab_name_req,
1426                                      bool write_access,
1427                                      krb5_keytab *keytab)
1428 {
1429         if (keytab_name_req != NULL) {
1430                 if (keytab_name_req[0] != '/') {
1431                         return KRB5_KT_BADNAME;
1432                 }
1433         }
1434
1435         return smb_krb5_open_keytab_relative(context,
1436                                              keytab_name_req,
1437                                              write_access,
1438                                              keytab);
1439 }
1440
1441 krb5_error_code smb_krb5_keytab_name(TALLOC_CTX *mem_ctx,
1442                                      krb5_context context,
1443                                      krb5_keytab keytab,
1444                                      const char **keytab_name)
1445 {
1446         char keytab_string[MAX_KEYTAB_NAME_LEN];
1447         krb5_error_code ret = 0;
1448
1449         ret = krb5_kt_get_name(context, keytab,
1450                                keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1451         if (ret) {
1452                 return ret;
1453         }
1454
1455         *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1456         if (!*keytab_name) {
1457                 return ENOMEM;
1458         }
1459
1460         return ret;
1461 }
1462
1463 /**
1464  * @brief Seek and delete old entries in a keytab based on the passed
1465  *        principal.
1466  *
1467  * @param[in]  context       The KRB5 context to use.
1468  *
1469  * @param[in]  keytab        The keytab to operate on.
1470  *
1471  * @param[in]  kvno          The kvnco to use.
1472  *
1473  * @param[in]  princ_s       The principal as a string to search for.
1474  *
1475  * @param[in]  princ         The principal as a krb5_principal to search for.
1476  *
1477  * @param[in]  flush         Weather to flush the complete keytab.
1478  *
1479  * @param[in]  keep_old_entries Keep the entry with the previous kvno.
1480  *
1481  * @retval 0 on Sucess
1482  *
1483  * @return An appropriate KRB5 error code.
1484  */
1485 krb5_error_code smb_krb5_kt_seek_and_delete_old_entries(krb5_context context,
1486                                                         krb5_keytab keytab,
1487                                                         krb5_kvno kvno,
1488                                                         krb5_enctype enctype,
1489                                                         const char *princ_s,
1490                                                         krb5_principal princ,
1491                                                         bool flush,
1492                                                         bool keep_old_entries)
1493 {
1494         krb5_error_code ret;
1495         krb5_kt_cursor cursor;
1496         krb5_kt_cursor zero_csr;
1497         krb5_keytab_entry kt_entry;
1498         krb5_keytab_entry zero_kt_entry;
1499         char *ktprinc = NULL;
1500         krb5_kvno old_kvno = kvno - 1;
1501         TALLOC_CTX *tmp_ctx;
1502
1503         ZERO_STRUCT(cursor);
1504         ZERO_STRUCT(zero_csr);
1505         ZERO_STRUCT(kt_entry);
1506         ZERO_STRUCT(zero_kt_entry);
1507
1508         ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1509         if (ret == KRB5_KT_END || ret == ENOENT ) {
1510                 /* no entries */
1511                 return 0;
1512         }
1513
1514         tmp_ctx = talloc_new(NULL);
1515         if (tmp_ctx == NULL) {
1516                 return ENOMEM;
1517         }
1518
1519         DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1520         while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1521                 bool name_ok = false;
1522                 krb5_enctype kt_entry_enctype =
1523                         smb_get_enctype_from_kt_entry(&kt_entry);
1524
1525                 if (!flush && (princ_s != NULL)) {
1526                         ret = smb_krb5_unparse_name(tmp_ctx, context,
1527                                                     kt_entry.principal,
1528                                                     &ktprinc);
1529                         if (ret) {
1530                                 DEBUG(1, (__location__
1531                                           ": smb_krb5_unparse_name failed "
1532                                           "(%s)\n", error_message(ret)));
1533                                 goto out;
1534                         }
1535
1536 #ifdef HAVE_KRB5_KT_COMPARE
1537                         name_ok = krb5_kt_compare(context, &kt_entry,
1538                                                   princ, 0, 0);
1539 #else
1540                         name_ok = (strcmp(ktprinc, princ_s) == 0);
1541 #endif
1542
1543                         if (!name_ok) {
1544                                 DEBUG(10, (__location__ ": ignoring keytab "
1545                                            "entry principal %s, kvno = %d\n",
1546                                            ktprinc, kt_entry.vno));
1547
1548                                 /* Not a match,
1549                                  * just free this entry and continue. */
1550                                 ret = smb_krb5_kt_free_entry(context,
1551                                                              &kt_entry);
1552                                 ZERO_STRUCT(kt_entry);
1553                                 if (ret) {
1554                                         DEBUG(1, (__location__
1555                                                   ": smb_krb5_kt_free_entry "
1556                                                   "failed (%s)\n",
1557                                                   error_message(ret)));
1558                                         goto out;
1559                                 }
1560
1561                                 TALLOC_FREE(ktprinc);
1562                                 continue;
1563                         }
1564
1565                         TALLOC_FREE(ktprinc);
1566                 }
1567
1568                 /*------------------------------------------------------------
1569                  * Save the entries with kvno - 1. This is what microsoft does
1570                  * to allow people with existing sessions that have kvno - 1
1571                  * to still work. Otherwise, when the password for the machine
1572                  * changes, all kerberizied sessions will 'break' until either
1573                  * the client reboots or the client's session key expires and
1574                  * they get a new session ticket with the new kvno.
1575                  * Some keytab files only store the kvno in 8bits, limit
1576                  * the compare accordingly.
1577                  */
1578
1579                 if (!flush && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1580                         DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1581                                   "entry for principal: %s.\n",
1582                                   old_kvno, princ_s));
1583                         continue;
1584                 }
1585
1586                 if (keep_old_entries) {
1587                         DEBUG(5, (__location__ ": Saving old (kvno %d) "
1588                                   "entry for principal: %s.\n",
1589                                   kvno, princ_s));
1590                         continue;
1591                 }
1592
1593                 if (!flush &&
1594                     (kt_entry.vno == kvno) &&
1595                     (kt_entry_enctype != enctype))
1596                 {
1597                         DEBUG(5, (__location__ ": Saving entry with kvno [%d] "
1598                                   "enctype [%d] for principal: %s.\n",
1599                                   kvno, kt_entry_enctype, princ_s));
1600                         continue;
1601                 }
1602
1603                 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1604                           "(kvno %d) - trying to remove it.\n",
1605                           princ_s, kt_entry.vno));
1606
1607                 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1608                 ZERO_STRUCT(cursor);
1609                 if (ret) {
1610                         DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1611                                   "failed (%s)\n", error_message(ret)));
1612                         goto out;
1613                 }
1614                 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1615                 if (ret) {
1616                         DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1617                                   "failed (%s)\n", error_message(ret)));
1618                         goto out;
1619                 }
1620
1621                 DEBUG(5, (__location__ ": removed old entry for principal: "
1622                           "%s (kvno %d).\n", princ_s, kt_entry.vno));
1623
1624                 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1625                 if (ret) {
1626                         DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1627                                   "(%s)\n", error_message(ret)));
1628                         goto out;
1629                 }
1630                 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1631                 ZERO_STRUCT(kt_entry);
1632                 if (ret) {
1633                         DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1634                                   "failed (%s)\n", error_message(ret)));
1635                         goto out;
1636                 }
1637         }
1638
1639 out:
1640         talloc_free(tmp_ctx);
1641         if (memcmp(&zero_kt_entry, &kt_entry, sizeof(krb5_keytab_entry))) {
1642                 smb_krb5_kt_free_entry(context, &kt_entry);
1643         }
1644         if (memcmp(&cursor, &zero_csr, sizeof(krb5_kt_cursor)) != 0) {
1645                 krb5_kt_end_seq_get(context, keytab, &cursor);
1646         }
1647         return ret;
1648 }
1649
1650 /**
1651  * @brief Add a keytab entry for the given principal
1652  *
1653  * @param[in]  context       The krb5 context to use.
1654  *
1655  * @param[in]  keytab        The keytab to add the entry to.
1656  *
1657  * @param[in]  kvno          The kvno to use.
1658  *
1659  * @param[in]  princ_s       The principal as a string.
1660  *
1661  * @param[in]  salt_principal The salt principal to salt the password with.
1662  *                            Only needed for keys which support salting.
1663  *                            If no salt is used set no_salt to false and
1664  *                            pass NULL here.
1665  *
1666  * @param[in]  enctype        The encryption type of the keytab entry.
1667  *
1668  * @param[in]  password       The password of the keytab entry.
1669  *
1670  * @param[in]  no_salt        If the password should not be salted. Normally
1671  *                            this is only set to false for encryption types
1672  *                            which do not support salting like RC4.
1673  *
1674  * @param[in]  keep_old_entries Wether to keep or delte old keytab entries.
1675  *
1676  * @retval 0 on Success
1677  *
1678  * @return A corresponding KRB5 error code.
1679  *
1680  * @see smb_krb5_open_keytab()
1681  */
1682 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1683                                       krb5_keytab keytab,
1684                                       krb5_kvno kvno,
1685                                       const char *princ_s,
1686                                       const char *salt_principal,
1687                                       krb5_enctype enctype,
1688                                       krb5_data *password,
1689                                       bool no_salt,
1690                                       bool keep_old_entries)
1691 {
1692         krb5_error_code ret;
1693         krb5_keytab_entry kt_entry;
1694         krb5_principal princ = NULL;
1695         krb5_keyblock *keyp;
1696
1697         ZERO_STRUCT(kt_entry);
1698
1699         ret = smb_krb5_parse_name(context, princ_s, &princ);
1700         if (ret) {
1701                 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1702                           "failed (%s)\n", princ_s, error_message(ret)));
1703                 goto out;
1704         }
1705
1706         /* Seek and delete old keytab entries */
1707         ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1708                                                       keytab,
1709                                                       kvno,
1710                                                       enctype,
1711                                                       princ_s,
1712                                                       princ,
1713                                                       false,
1714                                                       keep_old_entries);
1715         if (ret) {
1716                 goto out;
1717         }
1718
1719         /* If we get here, we have deleted all the old entries with kvno's
1720          * not equal to the current kvno-1. */
1721
1722         keyp = KRB5_KT_KEY(&kt_entry);
1723
1724         if (no_salt) {
1725                 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1726                 if (KRB5_KEY_DATA(keyp) == NULL) {
1727                         ret = ENOMEM;
1728                         goto out;
1729                 }
1730                 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1731                 KRB5_KEY_LENGTH(keyp) = password->length;
1732                 KRB5_KEY_TYPE(keyp) = enctype;
1733         } else {
1734                 krb5_principal salt_princ = NULL;
1735
1736                 /* Now add keytab entries for all encryption types */
1737                 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1738                 if (ret) {
1739                         DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1740                                     salt_principal, error_message(ret));
1741                         goto out;
1742                 }
1743
1744                 ret = smb_krb5_create_key_from_string(context,
1745                                                       salt_princ,
1746                                                       NULL,
1747                                                       password,
1748                                                       enctype,
1749                                                       keyp);
1750                 krb5_free_principal(context, salt_princ);
1751                 if (ret != 0) {
1752                         goto out;
1753                 }
1754         }
1755
1756         kt_entry.principal = princ;
1757         kt_entry.vno       = kvno;
1758
1759         DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1760                   "encryption type (%d) and version (%d)\n",
1761                   princ_s, enctype, kt_entry.vno));
1762         ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1763         krb5_free_keyblock_contents(context, keyp);
1764         ZERO_STRUCT(kt_entry);
1765         if (ret) {
1766                 DEBUG(1, (__location__ ": adding entry to keytab "
1767                           "failed (%s)\n", error_message(ret)));
1768                 goto out;
1769         }
1770
1771 out:
1772         if (princ) {
1773                 krb5_free_principal(context, princ);
1774         }
1775
1776         return ret;
1777 }
1778
1779 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1780     defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1781     defined(HAVE_KRB5_GET_CREDS)
1782 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1783                                                              krb5_ccache ccache,
1784                                                              krb5_principal me,
1785                                                              krb5_principal server,
1786                                                              krb5_principal impersonate_princ,
1787                                                              krb5_creds **out_creds)
1788 {
1789         krb5_error_code ret;
1790         krb5_get_creds_opt opt;
1791
1792         ret = krb5_get_creds_opt_alloc(context, &opt);
1793         if (ret) {
1794                 goto done;
1795         }
1796         krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1797
1798         if (impersonate_princ) {
1799                 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1800                                                          impersonate_princ);
1801                 if (ret) {
1802                         goto done;
1803                 }
1804         }
1805
1806         ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1807         if (ret) {
1808                 goto done;
1809         }
1810
1811  done:
1812         if (opt) {
1813                 krb5_get_creds_opt_free(context, opt);
1814         }
1815         return ret;
1816 }
1817 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1818
1819 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1820
1821 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1822 krb5_error_code KRB5_CALLCONV
1823 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1824                               krb5_ccache ccache, krb5_creds *in_creds,
1825                               krb5_data *subject_cert,
1826                               krb5_creds **out_creds);
1827 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1828
1829 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1830                                                          krb5_ccache ccache,
1831                                                          krb5_principal me,
1832                                                          krb5_principal server,
1833                                                          krb5_principal impersonate_princ,
1834                                                          krb5_creds **out_creds)
1835 {
1836         krb5_error_code ret;
1837         krb5_creds in_creds;
1838
1839         ZERO_STRUCT(in_creds);
1840
1841         if (impersonate_princ) {
1842
1843                 in_creds.server = me;
1844                 in_creds.client = impersonate_princ;
1845
1846                 ret = krb5_get_credentials_for_user(context,
1847                                                     0, /* krb5_flags options */
1848                                                     ccache,
1849                                                     &in_creds,
1850                                                     NULL, /* krb5_data *subject_cert */
1851                                                     out_creds);
1852         } else {
1853                 in_creds.client = me;
1854                 in_creds.server = server;
1855
1856                 ret = krb5_get_credentials(context, 0, ccache,
1857                                            &in_creds, out_creds);
1858         }
1859
1860         return ret;
1861 }
1862 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1863
1864 /*
1865  * smb_krb5_get_credentials
1866  *
1867  * @brief Get krb5 credentials for a server
1868  *
1869  * @param[in] context           An initialized krb5_context
1870  * @param[in] ccache            An initialized krb5_ccache
1871  * @param[in] me                The krb5_principal of the caller
1872  * @param[in] server            The krb5_principal of the requested service
1873  * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1874  * @param[out] out_creds        The returned krb5_creds structure
1875  * @return krb5_error_code
1876  *
1877  */
1878 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1879                                          krb5_ccache ccache,
1880                                          krb5_principal me,
1881                                          krb5_principal server,
1882                                          krb5_principal impersonate_princ,
1883                                          krb5_creds **out_creds)
1884 {
1885         krb5_error_code ret;
1886         krb5_creds *creds = NULL;
1887
1888         if (out_creds != NULL) {
1889                 *out_creds = NULL;
1890         }
1891
1892         if (impersonate_princ) {
1893 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1894                 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1895 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1896                 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1897 #else
1898                 ret = ENOTSUP;
1899 #endif
1900         } else {
1901                 krb5_creds in_creds;
1902
1903                 ZERO_STRUCT(in_creds);
1904
1905                 in_creds.client = me;
1906                 in_creds.server = server;
1907
1908                 ret = krb5_get_credentials(context, 0, ccache,
1909                                            &in_creds, &creds);
1910         }
1911         if (ret) {
1912                 goto done;
1913         }
1914
1915         if (out_creds) {
1916                 *out_creds = creds;
1917         }
1918
1919  done:
1920         if (creds && ret) {
1921                 krb5_free_creds(context, creds);
1922         }
1923
1924         return ret;
1925 }
1926
1927 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
1928                                                 krb5_enctype enctype,
1929                                                 const void *data,
1930                                                 size_t length,
1931                                                 krb5_keyblock *key)
1932 {
1933 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
1934         return krb5_keyblock_init(context, enctype, data, length, key);
1935 #else
1936         memset(key, 0, sizeof(krb5_keyblock));
1937         KRB5_KEY_DATA(key) = SMB_MALLOC(length);
1938         if (NULL == KRB5_KEY_DATA(key)) {
1939                 return ENOMEM;
1940         }
1941         memcpy(KRB5_KEY_DATA(key), data, length);
1942         KRB5_KEY_LENGTH(key) = length;
1943         KRB5_KEY_TYPE(key) = enctype;
1944         return 0;
1945 #endif
1946 }
1947
1948 /*
1949   simulate a kinit, putting the tgt in the given credentials cache.
1950   Orignally by remus@snapserver.com
1951
1952   This version is built to use a keyblock, rather than needing the
1953   original password.
1954
1955   The impersonate_principal is the principal if NULL, or the principal
1956   to impersonate
1957
1958   The target_service defaults to the krbtgt if NULL, but could be
1959    kpasswd/realm or the local service (if we are doing s4u2self)
1960 */
1961 krb5_error_code kerberos_kinit_keyblock_cc(krb5_context ctx, krb5_ccache cc,
1962                                            krb5_principal principal,
1963                                            krb5_keyblock *keyblock,
1964                                            const char *target_service,
1965                                            krb5_get_init_creds_opt *krb_options,
1966                                            time_t *expire_time,
1967                                            time_t *kdc_time)
1968 {
1969         krb5_error_code code = 0;
1970         krb5_creds my_creds;
1971
1972 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
1973         code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
1974                                             keyblock, 0, target_service,
1975                                             krb_options);
1976 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
1977 {
1978 #define SMB_CREDS_KEYTAB "MEMORY:tmp_smb_creds_XXXXXX"
1979         char tmp_name[sizeof(SMB_CREDS_KEYTAB)];
1980         krb5_keytab_entry entry;
1981         krb5_keytab keytab;
1982         mode_t mask;
1983
1984         memset(&entry, 0, sizeof(entry));
1985         entry.principal = principal;
1986         *(KRB5_KT_KEY(&entry)) = *keyblock;
1987
1988         memcpy(tmp_name, SMB_CREDS_KEYTAB, sizeof(SMB_CREDS_KEYTAB));
1989         mask = umask(S_IRWXO | S_IRWXG);
1990         mktemp(tmp_name);
1991         umask(mask);
1992         if (tmp_name[0] == 0) {
1993                 return KRB5_KT_BADNAME;
1994         }
1995         code = krb5_kt_resolve(ctx, tmp_name, &keytab);
1996         if (code) {
1997                 return code;
1998         }
1999
2000         code = krb5_kt_add_entry(ctx, keytab, &entry);
2001         if (code) {
2002                 (void)krb5_kt_close(ctx, keytab);
2003                 goto done;
2004         }
2005
2006         code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
2007                                           keytab, 0, target_service,
2008                                           krb_options);
2009         (void)krb5_kt_close(ctx, keytab);
2010 }
2011 #else
2012 #error krb5_get_init_creds_keyblock not available!
2013 #endif
2014         if (code) {
2015                 return code;
2016         }
2017
2018 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2019         /*
2020          * We need to store the principal as returned from the KDC to the
2021          * credentials cache. If we don't do that the KRB5 library is not
2022          * able to find the tickets it is looking for
2023          */
2024         principal = my_creds.client;
2025 #endif
2026         code = krb5_cc_initialize(ctx, cc, principal);
2027         if (code) {
2028                 goto done;
2029         }
2030
2031         code = krb5_cc_store_cred(ctx, cc, &my_creds);
2032         if (code) {
2033                 goto done;
2034         }
2035
2036         if (expire_time) {
2037                 *expire_time = (time_t) my_creds.times.endtime;
2038         }
2039
2040         if (kdc_time) {
2041                 *kdc_time = (time_t) my_creds.times.starttime;
2042         }
2043
2044         code = 0;
2045 done:
2046         krb5_free_cred_contents(ctx, &my_creds);
2047         return code;
2048 }
2049
2050 krb5_error_code kerberos_kinit_password_cc(krb5_context ctx, krb5_ccache cc,
2051                                            krb5_principal principal,
2052                                            const char *password,
2053                                            const char *target_service,
2054                                            krb5_get_init_creds_opt *krb_options,
2055                                            time_t *expire_time,
2056                                            time_t *kdc_time)
2057 {
2058         krb5_error_code code = 0;
2059         krb5_creds my_creds;
2060
2061         code = krb5_get_init_creds_password(ctx, &my_creds, principal,
2062                                             password, NULL, NULL, 0,
2063                                             target_service, krb_options);
2064         if (code) {
2065                 return code;
2066         }
2067
2068 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2069         /*
2070          * We need to store the principal as returned from the KDC to the
2071          * credentials cache. If we don't do that the KRB5 library is not
2072          * able to find the tickets it is looking for
2073          */
2074         principal = my_creds.client;
2075 #endif
2076         code = krb5_cc_initialize(ctx, cc, principal);
2077         if (code) {
2078                 goto done;
2079         }
2080
2081         code = krb5_cc_store_cred(ctx, cc, &my_creds);
2082         if (code) {
2083                 goto done;
2084         }
2085
2086         if (expire_time) {
2087                 *expire_time = (time_t) my_creds.times.endtime;
2088         }
2089
2090         if (kdc_time) {
2091                 *kdc_time = (time_t) my_creds.times.starttime;
2092         }
2093
2094         code = 0;
2095 done:
2096         krb5_free_cred_contents(ctx, &my_creds);
2097         return code;
2098 }
2099
2100 #ifdef SAMBA4_USES_HEIMDAL
2101 /*
2102   simulate a kinit, putting the tgt in the given credentials cache.
2103   Orignally by remus@snapserver.com
2104
2105   The impersonate_principal is the principal
2106
2107   The self_service, should be the local service (for S4U2Self if
2108   impersonate_principal is given).
2109
2110   The target_service defaults to the krbtgt if NULL, but could be
2111   kpasswd/realm or a remote service (for S4U2Proxy)
2112
2113 */
2114 krb5_error_code kerberos_kinit_s4u2_cc(krb5_context ctx,
2115                                         krb5_ccache store_cc,
2116                                         krb5_principal init_principal,
2117                                         const char *init_password,
2118                                         krb5_principal impersonate_principal,
2119                                         const char *self_service,
2120                                         const char *target_service,
2121                                         krb5_get_init_creds_opt *krb_options,
2122                                         time_t *expire_time,
2123                                         time_t *kdc_time)
2124 {
2125         krb5_error_code code = 0;
2126         krb5_get_creds_opt options;
2127         krb5_principal store_principal;
2128         krb5_creds store_creds;
2129         krb5_creds *s4u2self_creds;
2130         Ticket s4u2self_ticket;
2131         size_t s4u2self_ticketlen;
2132         krb5_creds *s4u2proxy_creds;
2133         krb5_principal self_princ;
2134         bool s4u2proxy;
2135         krb5_principal target_princ;
2136         krb5_ccache tmp_cc;
2137         const char *self_realm;
2138         krb5_principal blacklist_principal = NULL;
2139         krb5_principal whitelist_principal = NULL;
2140
2141         code = krb5_get_init_creds_password(ctx, &store_creds,
2142                                             init_principal,
2143                                             init_password,
2144                                             NULL, NULL,
2145                                             0,
2146                                             NULL,
2147                                             krb_options);
2148         if (code != 0) {
2149                 return code;
2150         }
2151
2152         store_principal = init_principal;
2153
2154         /*
2155          * We are trying S4U2Self now:
2156          *
2157          * As we do not want to expose our TGT in the
2158          * krb5_ccache, which is also holds the impersonated creds.
2159          *
2160          * Some low level krb5/gssapi function might use the TGT
2161          * identity and let the client act as our machine account.
2162          *
2163          * We need to avoid that and use a temporary krb5_ccache
2164          * in order to pass our TGT to the krb5_get_creds() function.
2165          */
2166         code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
2167         if (code != 0) {
2168                 krb5_free_cred_contents(ctx, &store_creds);
2169                 return code;
2170         }
2171
2172         code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
2173         if (code != 0) {
2174                 krb5_cc_destroy(ctx, tmp_cc);
2175                 krb5_free_cred_contents(ctx, &store_creds);
2176                 return code;
2177         }
2178
2179         code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
2180         if (code != 0) {
2181                 krb5_free_cred_contents(ctx, &store_creds);
2182                 krb5_cc_destroy(ctx, tmp_cc);
2183                 return code;
2184         }
2185
2186         /*
2187          * we need to remember the client principal of our
2188          * TGT and make sure the KDC does not return this
2189          * in the impersonated tickets. This can happen
2190          * if the KDC does not support S4U2Self and S4U2Proxy.
2191          */
2192         blacklist_principal = store_creds.client;
2193         store_creds.client = NULL;
2194         krb5_free_cred_contents(ctx, &store_creds);
2195
2196         /*
2197          * Check if we also need S4U2Proxy or if S4U2Self is
2198          * enough in order to get a ticket for the target.
2199          */
2200         if (target_service == NULL) {
2201                 s4u2proxy = false;
2202         } else if (strcmp(target_service, self_service) == 0) {
2203                 s4u2proxy = false;
2204         } else {
2205                 s4u2proxy = true;
2206         }
2207
2208         /*
2209          * For S4U2Self we need our own service principal,
2210          * which belongs to our own realm (available on
2211          * our client principal).
2212          */
2213         self_realm = krb5_principal_get_realm(ctx, init_principal);
2214
2215         code = krb5_parse_name(ctx, self_service, &self_princ);
2216         if (code != 0) {
2217                 krb5_free_principal(ctx, blacklist_principal);
2218                 krb5_cc_destroy(ctx, tmp_cc);
2219                 return code;
2220         }
2221
2222         code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2223         if (code != 0) {
2224                 krb5_free_principal(ctx, blacklist_principal);
2225                 krb5_free_principal(ctx, self_princ);
2226                 krb5_cc_destroy(ctx, tmp_cc);
2227                 return code;
2228         }
2229
2230         code = krb5_get_creds_opt_alloc(ctx, &options);
2231         if (code != 0) {
2232                 krb5_free_principal(ctx, blacklist_principal);
2233                 krb5_free_principal(ctx, self_princ);
2234                 krb5_cc_destroy(ctx, tmp_cc);
2235                 return code;
2236         }
2237
2238         if (s4u2proxy) {
2239                 /*
2240                  * If we want S4U2Proxy, we need the forwardable flag
2241                  * on the S4U2Self ticket.
2242                  */
2243                 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2244         }
2245
2246         code = krb5_get_creds_opt_set_impersonate(ctx, options,
2247                                                   impersonate_principal);
2248         if (code != 0) {
2249                 krb5_get_creds_opt_free(ctx, options);
2250                 krb5_free_principal(ctx, blacklist_principal);
2251                 krb5_free_principal(ctx, self_princ);
2252                 krb5_cc_destroy(ctx, tmp_cc);
2253                 return code;
2254         }
2255
2256         code = krb5_get_creds(ctx, options, tmp_cc,
2257                               self_princ, &s4u2self_creds);
2258         krb5_get_creds_opt_free(ctx, options);
2259         krb5_free_principal(ctx, self_princ);
2260         if (code != 0) {
2261                 krb5_free_principal(ctx, blacklist_principal);
2262                 krb5_cc_destroy(ctx, tmp_cc);
2263                 return code;
2264         }
2265
2266         if (!s4u2proxy) {
2267                 krb5_cc_destroy(ctx, tmp_cc);
2268
2269                 /*
2270                  * Now make sure we store the impersonated principal
2271                  * and creds instead of the TGT related stuff
2272                  * in the krb5_ccache of the caller.
2273                  */
2274                 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2275                                                 &store_creds);
2276                 krb5_free_creds(ctx, s4u2self_creds);
2277                 if (code != 0) {
2278                         return code;
2279                 }
2280
2281                 /*
2282                  * It's important to store the principal the KDC
2283                  * returned, as otherwise the caller would not find
2284                  * the S4U2Self ticket in the krb5_ccache lookup.
2285                  */
2286                 store_principal = store_creds.client;
2287                 goto store;
2288         }
2289
2290         /*
2291          * We are trying S4U2Proxy:
2292          *
2293          * We need the ticket from the S4U2Self step
2294          * and our TGT in order to get the delegated ticket.
2295          */
2296         code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2297                              s4u2self_creds->ticket.length,
2298                              &s4u2self_ticket,
2299                              &s4u2self_ticketlen);
2300         if (code != 0) {
2301                 krb5_free_creds(ctx, s4u2self_creds);
2302                 krb5_free_principal(ctx, blacklist_principal);
2303                 krb5_cc_destroy(ctx, tmp_cc);
2304                 return code;
2305         }
2306
2307         /*
2308          * we need to remember the client principal of the
2309          * S4U2Self stage and as it needs to match the one we
2310          * will get for the S4U2Proxy stage. We need this
2311          * in order to detect KDCs which does not support S4U2Proxy.
2312          */
2313         whitelist_principal = s4u2self_creds->client;
2314         s4u2self_creds->client = NULL;
2315         krb5_free_creds(ctx, s4u2self_creds);
2316
2317         /*
2318          * For S4U2Proxy we also got a target service principal,
2319          * which also belongs to our own realm (available on
2320          * our client principal).
2321          */
2322         code = krb5_parse_name(ctx, target_service, &target_princ);
2323         if (code != 0) {
2324                 free_Ticket(&s4u2self_ticket);
2325                 krb5_free_principal(ctx, whitelist_principal);
2326                 krb5_free_principal(ctx, blacklist_principal);
2327                 krb5_cc_destroy(ctx, tmp_cc);
2328                 return code;
2329         }
2330
2331         code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2332         if (code != 0) {
2333                 free_Ticket(&s4u2self_ticket);
2334                 krb5_free_principal(ctx, target_princ);
2335                 krb5_free_principal(ctx, whitelist_principal);
2336                 krb5_free_principal(ctx, blacklist_principal);
2337                 krb5_cc_destroy(ctx, tmp_cc);
2338                 return code;
2339         }
2340
2341         code = krb5_get_creds_opt_alloc(ctx, &options);
2342         if (code != 0) {
2343                 free_Ticket(&s4u2self_ticket);
2344                 krb5_free_principal(ctx, target_princ);
2345                 krb5_free_principal(ctx, whitelist_principal);
2346                 krb5_free_principal(ctx, blacklist_principal);
2347                 krb5_cc_destroy(ctx, tmp_cc);
2348                 return code;
2349         }
2350
2351         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2352         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2353
2354         code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2355         free_Ticket(&s4u2self_ticket);
2356         if (code != 0) {
2357                 krb5_get_creds_opt_free(ctx, options);
2358                 krb5_free_principal(ctx, target_princ);
2359                 krb5_free_principal(ctx, whitelist_principal);
2360                 krb5_free_principal(ctx, blacklist_principal);
2361                 krb5_cc_destroy(ctx, tmp_cc);
2362                 return code;
2363         }
2364
2365         code = krb5_get_creds(ctx, options, tmp_cc,
2366                               target_princ, &s4u2proxy_creds);
2367         krb5_get_creds_opt_free(ctx, options);
2368         krb5_free_principal(ctx, target_princ);
2369         krb5_cc_destroy(ctx, tmp_cc);
2370         if (code != 0) {
2371                 krb5_free_principal(ctx, whitelist_principal);
2372                 krb5_free_principal(ctx, blacklist_principal);
2373                 return code;
2374         }
2375
2376         /*
2377          * Now make sure we store the impersonated principal
2378          * and creds instead of the TGT related stuff
2379          * in the krb5_ccache of the caller.
2380          */
2381         code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2382                                         &store_creds);
2383         krb5_free_creds(ctx, s4u2proxy_creds);
2384         if (code != 0) {
2385                 krb5_free_principal(ctx, whitelist_principal);
2386                 krb5_free_principal(ctx, blacklist_principal);
2387                 return code;
2388         }
2389
2390         /*
2391          * It's important to store the principal the KDC
2392          * returned, as otherwise the caller would not find
2393          * the S4U2Self ticket in the krb5_ccache lookup.
2394          */
2395         store_principal = store_creds.client;
2396
2397  store:
2398         if (blacklist_principal &&
2399             krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2400                 char *sp = NULL;
2401                 char *ip = NULL;
2402
2403                 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2404                 if (code != 0) {
2405                         sp = NULL;
2406                 }
2407                 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2408                 if (code != 0) {
2409                         ip = NULL;
2410                 }
2411                 DEBUG(1, ("kerberos_kinit_password_cc: "
2412                           "KDC returned self principal[%s] while impersonating [%s]\n",
2413                           sp?sp:"<no memory>",
2414                           ip?ip:"<no memory>"));
2415
2416                 SAFE_FREE(sp);
2417                 SAFE_FREE(ip);
2418
2419                 krb5_free_principal(ctx, whitelist_principal);
2420                 krb5_free_principal(ctx, blacklist_principal);
2421                 krb5_free_cred_contents(ctx, &store_creds);
2422                 return KRB5_FWD_BAD_PRINCIPAL;
2423         }
2424         if (blacklist_principal) {
2425                 krb5_free_principal(ctx, blacklist_principal);
2426         }
2427
2428         if (whitelist_principal &&
2429             !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2430                 char *sp = NULL;
2431                 char *ep = NULL;
2432
2433                 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2434                 if (code != 0) {
2435                         sp = NULL;
2436                 }
2437                 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2438                 if (code != 0) {
2439                         ep = NULL;
2440                 }
2441                 DEBUG(1, ("kerberos_kinit_password_cc: "
2442                           "KDC returned wrong principal[%s] we expected [%s]\n",
2443                           sp?sp:"<no memory>",
2444                           ep?ep:"<no memory>"));
2445
2446                 SAFE_FREE(sp);
2447                 SAFE_FREE(ep);
2448
2449                 krb5_free_principal(ctx, whitelist_principal);
2450                 krb5_free_cred_contents(ctx, &store_creds);
2451                 return KRB5_FWD_BAD_PRINCIPAL;
2452         }
2453         if (whitelist_principal) {
2454                 krb5_free_principal(ctx, whitelist_principal);
2455         }
2456
2457         code = krb5_cc_initialize(ctx, store_cc, store_principal);
2458         if (code != 0) {
2459                 krb5_free_cred_contents(ctx, &store_creds);
2460                 return code;
2461         }
2462
2463         code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2464         if (code != 0) {
2465                 krb5_free_cred_contents(ctx, &store_creds);
2466                 return code;
2467         }
2468
2469         if (expire_time) {
2470                 *expire_time = (time_t) store_creds.times.endtime;
2471         }
2472
2473         if (kdc_time) {
2474                 *kdc_time = (time_t) store_creds.times.starttime;
2475         }
2476
2477         krb5_free_cred_contents(ctx, &store_creds);
2478
2479         return 0;
2480 }
2481 #endif
2482
2483 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2484 krb5_error_code smb_krb5_make_principal(krb5_context context,
2485                                         krb5_principal *principal,
2486                                         const char *_realm, ...)
2487 {
2488         krb5_error_code code;
2489         bool free_realm;
2490         char *realm;
2491         va_list ap;
2492
2493         if (_realm) {
2494                 realm = discard_const_p(char, _realm);
2495                 free_realm = false;
2496         } else {
2497                 code = krb5_get_default_realm(context, &realm);
2498                 if (code) {
2499                         return code;
2500                 }
2501                 free_realm = true;
2502         }
2503
2504         va_start(ap, _realm);
2505         code = krb5_build_principal_alloc_va(context, principal,
2506                                              strlen(realm), realm,
2507                                              ap);
2508         va_end(ap);
2509
2510         if (free_realm) {
2511                 krb5_free_default_realm(context, realm);
2512         }
2513
2514         return code;
2515 }
2516 #endif
2517
2518 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2519 /**
2520  * @brief Get the lifetime of the initial ticket in the cache.
2521  *
2522  * @param[in]  context  The kerberos context.
2523  *
2524  * @param[in]  id       The credential cache to get the ticket lifetime.
2525  *
2526  * @param[out] t        A pointer to a time value to store the lifetime.
2527  *
2528  * @return              0 on success, a krb5_error_code on error.
2529  */
2530 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2531                                          krb5_ccache id,
2532                                          time_t *t)
2533 {
2534         krb5_cc_cursor cursor;
2535         krb5_error_code kerr;
2536         krb5_creds cred;
2537         krb5_timestamp now;
2538
2539         *t = 0;
2540
2541         kerr = krb5_timeofday(context, &now);
2542         if (kerr) {
2543                 return kerr;
2544         }
2545
2546         kerr = krb5_cc_start_seq_get(context, id, &cursor);
2547         if (kerr) {
2548                 return kerr;
2549         }
2550
2551         while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2552 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2553                 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2554 #else
2555                 if (cred.flags.b.initial) {
2556 #endif
2557                         if (now < cred.times.endtime) {
2558                                 *t = (time_t) (cred.times.endtime - now);
2559                         }
2560                         krb5_free_cred_contents(context, &cred);
2561                         break;
2562                 }
2563                 krb5_free_cred_contents(context, &cred);
2564         }
2565
2566         krb5_cc_end_seq_get(context, id, &cursor);
2567
2568         return kerr;
2569 }
2570 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2571
2572 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2573 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2574 {
2575         free_Checksum(cksum);
2576 }
2577 #endif
2578
2579 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2580                                            DATA_BLOB *pac_data,
2581                                            krb5_context context,
2582                                            const krb5_keyblock *keyblock,
2583                                            uint32_t *sig_type,
2584                                            DATA_BLOB *sig_blob)
2585 {
2586         krb5_error_code ret;
2587         krb5_checksum cksum;
2588 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2589         krb5_crypto crypto;
2590
2591
2592         ret = krb5_crypto_init(context,
2593                                keyblock,
2594                                0,
2595                                &crypto);
2596         if (ret) {
2597                 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2598                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2599                 return ret;
2600         }
2601         ret = krb5_create_checksum(context,
2602                                    crypto,
2603                                    KRB5_KU_OTHER_CKSUM,
2604                                    0,
2605                                    pac_data->data,
2606                                    pac_data->length,
2607                                    &cksum);
2608         if (ret) {
2609                 DEBUG(2, ("PAC Verification failed: %s\n",
2610                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2611         }
2612
2613         krb5_crypto_destroy(context, crypto);
2614
2615         if (ret) {
2616                 return ret;
2617         }
2618
2619         *sig_type = cksum.cksumtype;
2620         *sig_blob = data_blob_talloc(mem_ctx,
2621                                         cksum.checksum.data,
2622                                         cksum.checksum.length);
2623 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2624         krb5_data input;
2625
2626         input.data = (char *)pac_data->data;
2627         input.length = pac_data->length;
2628
2629         ret = krb5_c_make_checksum(context,
2630                                    0,
2631                                    keyblock,
2632                                    KRB5_KEYUSAGE_APP_DATA_CKSUM,
2633                                    &input,
2634                                    &cksum);
2635         if (ret) {
2636                 DEBUG(2, ("PAC Verification failed: %s\n",
2637                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2638                 return ret;
2639         }
2640
2641         *sig_type = cksum.checksum_type;
2642         *sig_blob = data_blob_talloc(mem_ctx,
2643                                         cksum.contents,
2644                                         cksum.length);
2645
2646 #else
2647 #error krb5_create_checksum or krb5_c_make_checksum not available
2648 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2649         smb_krb5_free_checksum_contents(context, &cksum);
2650
2651         return 0;
2652 }
2653
2654
2655 /*
2656  * smb_krb5_principal_get_realm
2657  *
2658  * @brief Get realm of a principal
2659  *
2660  * @param[in] context           The krb5_context
2661  * @param[in] principal         The principal
2662  * @return pointer to the realm
2663  *
2664  * Caller must free if the return value is not NULL.
2665  *
2666  */
2667
2668 char *smb_krb5_principal_get_realm(krb5_context context,
2669                                    krb5_const_principal principal)
2670 {
2671 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2672         return strdup(discard_const_p(char, krb5_principal_get_realm(context, principal)));
2673 #elif defined(krb5_princ_realm) /* MIT */
2674         krb5_data *realm;
2675         realm = discard_const_p(krb5_data,
2676                                 krb5_princ_realm(context, principal));
2677         return strndup(realm->data, realm->length);
2678 #else
2679 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
2680 #endif
2681 }
2682
2683 /*
2684  * smb_krb5_principal_set_realm
2685  *
2686  * @brief Get realm of a principal
2687  *
2688  * @param[in] context           The krb5_context
2689  * @param[in] principal         The principal
2690  * @param[in] realm             The realm
2691  * @return                      0 on success, a krb5_error_code on error.
2692  *
2693  */
2694
2695 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
2696                                              krb5_principal principal,
2697                                              const char *realm)
2698 {
2699 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
2700         return krb5_principal_set_realm(context, principal, realm);
2701 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
2702         krb5_error_code ret;
2703         krb5_data data;
2704         krb5_data *old_data;
2705
2706         old_data = krb5_princ_realm(context, principal);
2707
2708         ret = krb5_copy_data_contents(&data,
2709                                       realm,
2710                                       strlen(realm));
2711         if (ret) {
2712                 return ret;
2713         }
2714
2715         /* free realm before setting */
2716         free(old_data->data);
2717
2718         krb5_princ_set_realm(context, principal, &data);
2719
2720         return ret;
2721 #else
2722 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
2723 #endif
2724 }
2725
2726
2727 /************************************************************************
2728  Routine to get the default realm from the kerberos credentials cache.
2729  Caller must free if the return value is not NULL.
2730 ************************************************************************/
2731
2732 static char *smb_krb5_get_default_realm_from_ccache(TALLOC_CTX *mem_ctx)
2733 {
2734         char *realm = NULL;
2735         krb5_context ctx = NULL;
2736         krb5_ccache cc = NULL;
2737         krb5_principal princ = NULL;
2738
2739         initialize_krb5_error_table();
2740         if (krb5_init_context(&ctx)) {
2741                 return NULL;
2742         }
2743
2744         DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2745                 "Trying to read krb5 cache: %s\n",
2746                 krb5_cc_default_name(ctx)));
2747         if (krb5_cc_default(ctx, &cc)) {
2748                 DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2749                         "failed to read default cache\n"));
2750                 goto out;
2751         }
2752         if (krb5_cc_get_principal(ctx, cc, &princ)) {
2753                 DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2754                         "failed to get default principal\n"));
2755                 goto out;
2756         }
2757
2758 #if defined(HAVE_KRB5_PRINCIPAL_GET_REALM)
2759         realm = talloc_strdup(mem_ctx, krb5_principal_get_realm(ctx, princ));
2760 #elif defined(HAVE_KRB5_PRINC_REALM)
2761         {
2762                 krb5_data *realm_data = krb5_princ_realm(ctx, princ);
2763                 realm = talloc_strndup(mem_ctx, realm_data->data, realm_data->length);
2764         }
2765 #endif
2766
2767   out:
2768
2769         if (ctx) {
2770                 if (princ) {
2771                         krb5_free_principal(ctx, princ);
2772                 }
2773                 if (cc) {
2774                         krb5_cc_close(ctx, cc);
2775                 }
2776                 krb5_free_context(ctx);
2777         }
2778
2779         return realm;
2780 }
2781
2782 /************************************************************************
2783  Routine to get the realm from a given DNS name.
2784 ************************************************************************/
2785
2786 static char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2787                                                 const char *hostname)
2788 {
2789 #if defined(HAVE_KRB5_REALM_TYPE)
2790         /* Heimdal. */
2791         krb5_realm *realm_list = NULL;
2792 #else
2793         /* MIT */
2794         char **realm_list = NULL;
2795 #endif
2796         char *realm = NULL;
2797         krb5_error_code kerr;
2798         krb5_context ctx = NULL;
2799
2800         initialize_krb5_error_table();
2801         if (krb5_init_context(&ctx)) {
2802                 return NULL;
2803         }
2804
2805         kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
2806         if (kerr != 0) {
2807                 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
2808                         "failed %s\n",
2809                         hostname ? hostname : "(NULL)",
2810                         error_message(kerr) ));
2811                 goto out;
2812         }
2813
2814         if (realm_list && realm_list[0]) {
2815                 realm = talloc_strdup(mem_ctx, realm_list[0]);
2816         }
2817
2818   out:
2819
2820         if (ctx) {
2821                 if (realm_list) {
2822                         krb5_free_host_realm(ctx, realm_list);
2823                         realm_list = NULL;
2824                 }
2825                 krb5_free_context(ctx);
2826                 ctx = NULL;
2827         }
2828         return realm;
2829 }
2830
2831 char *kerberos_get_principal_from_service_hostname(TALLOC_CTX *mem_ctx,
2832                                                    const char *service,
2833                                                    const char *remote_name,
2834                                                    const char *default_realm)
2835 {
2836         char *realm = NULL;
2837         char *host = NULL;
2838         char *principal;
2839         host = strchr_m(remote_name, '.');
2840         if (host) {
2841                 /* DNS name. */
2842                 realm = smb_krb5_get_realm_from_hostname(talloc_tos(),
2843                                                          remote_name);
2844         } else {
2845                 /* NetBIOS name - use our realm. */
2846                 realm = smb_krb5_get_default_realm_from_ccache(talloc_tos());
2847         }
2848
2849         if (realm == NULL || *realm == '\0') {
2850                 realm = talloc_strdup(talloc_tos(), default_realm);
2851                 if (!realm) {
2852                         return NULL;
2853                 }
2854                 DEBUG(3,("kerberos_get_principal_from_service_hostname: "
2855                          "cannot get realm from, "
2856                          "desthost %s or default ccache. Using default "
2857                          "smb.conf realm %s\n",
2858                          remote_name,
2859                          realm));
2860         }
2861
2862         principal = talloc_asprintf(mem_ctx,
2863                                     "%s/%s@%s",
2864                                     service, remote_name,
2865                                     realm);
2866         TALLOC_FREE(realm);
2867         return principal;
2868 }
2869
2870 char *smb_get_krb5_error_message(krb5_context context,
2871                                  krb5_error_code code,
2872                                  TALLOC_CTX *mem_ctx)
2873 {
2874         char *ret;
2875
2876 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
2877         const char *context_error = krb5_get_error_message(context, code);
2878         if (context_error) {
2879                 ret = talloc_asprintf(mem_ctx, "%s: %s",
2880                                         error_message(code), context_error);
2881                 krb5_free_error_message(context, context_error);
2882                 return ret;
2883         }
2884 #endif
2885         ret = talloc_strdup(mem_ctx, error_message(code));
2886         return ret;
2887 }
2888
2889
2890 /**
2891 * @brief Return the kerberos library setting for "libdefaults:allow_weak_crypto"
2892 *
2893 * @param context        The krb5_context
2894 *
2895 * @return krb5_boolean
2896 *
2897 * Function returns true if weak crypto is allowd, false if not
2898 */
2899
2900 krb5_boolean smb_krb5_get_allowed_weak_crypto(krb5_context context)
2901 #if defined(HAVE_KRB5_CONFIG_GET_BOOL_DEFAULT)
2902 {
2903         return krb5_config_get_bool_default(context,
2904                                             NULL,
2905                                             FALSE,
2906                                             "libdefaults",
2907                                             "allow_weak_crypto",
2908                                             NULL);
2909 }
2910 #elif defined(HAVE_PROFILE_H) && defined(HAVE_KRB5_GET_PROFILE)
2911 {
2912 #include <profile.h>
2913         krb5_error_code ret;
2914         krb5_boolean ret_default = false;
2915         profile_t profile;
2916         int ret_profile;
2917
2918         ret = krb5_get_profile(context,
2919                                &profile);
2920         if (ret) {
2921                 return ret_default;
2922         }
2923
2924         ret = profile_get_boolean(profile,
2925                                   "libdefaults",
2926                                   "allow_weak_crypto",
2927                                   NULL, /* subsubname */
2928                                   ret_default, /* def_val */
2929                                   &ret_profile /* *ret_default */);
2930         if (ret) {
2931                 return ret_default;
2932         }
2933
2934         profile_release(profile);
2935
2936         return ret_profile;
2937 }
2938 #else
2939 #error UNKNOWN_KRB5_CONFIG_ROUTINES
2940 #endif
2941
2942 /**
2943 * @brief Return the type of a krb5_principal
2944 *
2945 * @param context        The krb5_context
2946 * @param principal      The const krb5_principal
2947 *
2948 * @return integer type of the principal
2949 */
2950 int smb_krb5_principal_get_type(krb5_context context,
2951                                 krb5_const_principal principal)
2952 {
2953 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
2954         return krb5_principal_get_type(context, principal);
2955 #elif defined(krb5_princ_type) /* MIT */
2956         return krb5_princ_type(context, principal);
2957 #else
2958 #error  UNKNOWN_PRINC_GET_TYPE_FUNCTION
2959 #endif
2960 }
2961
2962 /**
2963 * @brief Set the type of a krb5_principal
2964 *
2965 * @param context        The krb5_context
2966 * @param principal      The const krb5_principal
2967 * @param type           The principal type
2968 *
2969 */
2970 void smb_krb5_principal_set_type(krb5_context context,
2971                                  krb5_principal principal,
2972                                  int type)
2973 {
2974 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
2975         krb5_principal_set_type(context, principal, type);
2976 #elif defined(krb5_princ_type) /* MIT */
2977         krb5_princ_type(context, principal) = type;
2978 #else
2979 #error  UNKNOWN_PRINC_SET_TYPE_FUNCTION
2980 #endif
2981 }
2982
2983 /**
2984 * @brief Generate a krb5 warning, forwarding to com_err
2985 *
2986 * @param context        The krb5_context
2987 * @param fmt            The message format
2988 * @param ...            The message arguments
2989 *
2990 * @return
2991 */
2992 #if !defined(HAVE_KRB5_WARNX)
2993 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
2994 {
2995         va_list args;
2996
2997         va_start(args, fmt);
2998         com_err_va("kdb_samba", errno, fmt, args);
2999         va_end(args);
3000
3001         return 0;
3002 }
3003 #endif
3004
3005 #else /* HAVE_KRB5 */
3006  /* this saves a few linking headaches */
3007  int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
3008                         const char *principal, time_t time_offset,
3009                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
3010                         uint32_t extra_ap_opts,
3011                         const char *ccname, time_t *tgs_expire,
3012                         const char *impersonate_princ_s)
3013 {
3014          DEBUG(0,("NO KERBEROS SUPPORT\n"));
3015          return 1;
3016 }
3017
3018 #endif /* HAVE_KRB5 */