9ee71f52c65f01e7071e4f632808e2e1a9075394
[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                                                         const char *princ_s,
1489                                                         krb5_principal princ,
1490                                                         bool flush,
1491                                                         bool keep_old_entries)
1492 {
1493         krb5_error_code ret;
1494         krb5_kt_cursor cursor;
1495         krb5_kt_cursor zero_csr;
1496         krb5_keytab_entry kt_entry;
1497         krb5_keytab_entry zero_kt_entry;
1498         char *ktprinc = NULL;
1499         krb5_kvno old_kvno = kvno - 1;
1500         TALLOC_CTX *tmp_ctx;
1501
1502         ZERO_STRUCT(cursor);
1503         ZERO_STRUCT(zero_csr);
1504         ZERO_STRUCT(kt_entry);
1505         ZERO_STRUCT(zero_kt_entry);
1506
1507         ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1508         if (ret == KRB5_KT_END || ret == ENOENT ) {
1509                 /* no entries */
1510                 return 0;
1511         }
1512
1513         tmp_ctx = talloc_new(NULL);
1514         if (tmp_ctx == NULL) {
1515                 return ENOMEM;
1516         }
1517
1518         DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1519         while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1520                 bool name_ok = false;
1521
1522                 if (!flush && (princ_s != NULL)) {
1523                         ret = smb_krb5_unparse_name(tmp_ctx, context,
1524                                                     kt_entry.principal,
1525                                                     &ktprinc);
1526                         if (ret) {
1527                                 DEBUG(1, (__location__
1528                                           ": smb_krb5_unparse_name failed "
1529                                           "(%s)\n", error_message(ret)));
1530                                 goto out;
1531                         }
1532
1533 #ifdef HAVE_KRB5_KT_COMPARE
1534                         name_ok = krb5_kt_compare(context, &kt_entry,
1535                                                   princ, 0, 0);
1536 #else
1537                         name_ok = (strcmp(ktprinc, princ_s) == 0);
1538 #endif
1539
1540                         if (!name_ok) {
1541                                 DEBUG(10, (__location__ ": ignoring keytab "
1542                                            "entry principal %s, kvno = %d\n",
1543                                            ktprinc, kt_entry.vno));
1544
1545                                 /* Not a match,
1546                                  * just free this entry and continue. */
1547                                 ret = smb_krb5_kt_free_entry(context,
1548                                                              &kt_entry);
1549                                 ZERO_STRUCT(kt_entry);
1550                                 if (ret) {
1551                                         DEBUG(1, (__location__
1552                                                   ": smb_krb5_kt_free_entry "
1553                                                   "failed (%s)\n",
1554                                                   error_message(ret)));
1555                                         goto out;
1556                                 }
1557
1558                                 TALLOC_FREE(ktprinc);
1559                                 continue;
1560                         }
1561
1562                         TALLOC_FREE(ktprinc);
1563                 }
1564
1565                 /*------------------------------------------------------------
1566                  * Save the entries with kvno - 1. This is what microsoft does
1567                  * to allow people with existing sessions that have kvno - 1
1568                  * to still work. Otherwise, when the password for the machine
1569                  * changes, all kerberizied sessions will 'break' until either
1570                  * the client reboots or the client's session key expires and
1571                  * they get a new session ticket with the new kvno.
1572                  * Some keytab files only store the kvno in 8bits, limit
1573                  * the compare accordingly.
1574                  */
1575
1576                 if (!flush && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1577                         DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1578                                   "entry for principal: %s.\n",
1579                                   old_kvno, princ_s));
1580                         continue;
1581                 }
1582
1583                 if (keep_old_entries) {
1584                         DEBUG(5, (__location__ ": Saving old (kvno %d) "
1585                                   "entry for principal: %s.\n",
1586                                   kvno, princ_s));
1587                         continue;
1588                 }
1589
1590                 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1591                           "(kvno %d) - trying to remove it.\n",
1592                           princ_s, kt_entry.vno));
1593
1594                 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1595                 ZERO_STRUCT(cursor);
1596                 if (ret) {
1597                         DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1598                                   "failed (%s)\n", error_message(ret)));
1599                         goto out;
1600                 }
1601                 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1602                 if (ret) {
1603                         DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1604                                   "failed (%s)\n", error_message(ret)));
1605                         goto out;
1606                 }
1607
1608                 DEBUG(5, (__location__ ": removed old entry for principal: "
1609                           "%s (kvno %d).\n", princ_s, kt_entry.vno));
1610
1611                 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1612                 if (ret) {
1613                         DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1614                                   "(%s)\n", error_message(ret)));
1615                         goto out;
1616                 }
1617                 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1618                 ZERO_STRUCT(kt_entry);
1619                 if (ret) {
1620                         DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1621                                   "failed (%s)\n", error_message(ret)));
1622                         goto out;
1623                 }
1624         }
1625
1626 out:
1627         talloc_free(tmp_ctx);
1628         if (memcmp(&zero_kt_entry, &kt_entry, sizeof(krb5_keytab_entry))) {
1629                 smb_krb5_kt_free_entry(context, &kt_entry);
1630         }
1631         if (keytab) {
1632                 if (memcmp(&cursor, &zero_csr, sizeof(krb5_kt_cursor)) != 0) {
1633                         krb5_kt_end_seq_get(context, keytab, &cursor);
1634                 }
1635         }
1636
1637         return ret;
1638 }
1639
1640 /**
1641  * @brief Add a keytab entry for the given principal
1642  *
1643  * @param[in]  context       The krb5 context to use.
1644  *
1645  * @param[in]  keytab        The keytab to add the entry to.
1646  *
1647  * @param[in]  kvno          The kvno to use.
1648  *
1649  * @param[in]  princ_s       The principal as a string.
1650  *
1651  * @param[in]  salt_principal The salt principal to salt the password with.
1652  *                            Only needed for keys which support salting.
1653  *                            If no salt is used set no_salt to false and
1654  *                            pass NULL here.
1655  *
1656  * @param[in]  enctype        The encryption type of the keytab entry.
1657  *
1658  * @param[in]  password       The password of the keytab entry.
1659  *
1660  * @param[in]  no_salt        If the password should not be salted. Normally
1661  *                            this is only set to false for encryption types
1662  *                            which do not support salting like RC4.
1663  *
1664  * @param[in]  keep_old_entries Wether to keep or delte old keytab entries.
1665  *
1666  * @retval 0 on Success
1667  *
1668  * @return A corresponding KRB5 error code.
1669  *
1670  * @see smb_krb5_open_keytab()
1671  */
1672 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1673                                       krb5_keytab keytab,
1674                                       krb5_kvno kvno,
1675                                       const char *princ_s,
1676                                       const char *salt_principal,
1677                                       krb5_enctype enctype,
1678                                       krb5_data *password,
1679                                       bool no_salt,
1680                                       bool keep_old_entries)
1681 {
1682         krb5_error_code ret;
1683         krb5_keytab_entry kt_entry;
1684         krb5_principal princ = NULL;
1685         krb5_keyblock *keyp;
1686
1687         ZERO_STRUCT(kt_entry);
1688
1689         ret = smb_krb5_parse_name(context, princ_s, &princ);
1690         if (ret) {
1691                 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1692                           "failed (%s)\n", princ_s, error_message(ret)));
1693                 goto out;
1694         }
1695
1696         /* Seek and delete old keytab entries */
1697         ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1698                                                       keytab,
1699                                                       kvno,
1700                                                       princ_s,
1701                                                       princ,
1702                                                       false,
1703                                                       keep_old_entries);
1704         if (ret) {
1705                 goto out;
1706         }
1707
1708         /* If we get here, we have deleted all the old entries with kvno's
1709          * not equal to the current kvno-1. */
1710
1711         keyp = KRB5_KT_KEY(&kt_entry);
1712
1713         if (no_salt) {
1714                 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1715                 if (KRB5_KEY_DATA(keyp) == NULL) {
1716                         ret = ENOMEM;
1717                         goto out;
1718                 }
1719                 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1720                 KRB5_KEY_LENGTH(keyp) = password->length;
1721                 KRB5_KEY_TYPE(keyp) = enctype;
1722         } else {
1723                 krb5_principal salt_princ = NULL;
1724
1725                 /* Now add keytab entries for all encryption types */
1726                 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1727                 if (ret) {
1728                         DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1729                                     salt_principal, error_message(ret));
1730                         goto out;
1731                 }
1732
1733                 ret = smb_krb5_create_key_from_string(context,
1734                                                       salt_princ,
1735                                                       NULL,
1736                                                       password,
1737                                                       enctype,
1738                                                       keyp);
1739                 krb5_free_principal(context, salt_princ);
1740                 if (ret != 0) {
1741                         goto out;
1742                 }
1743         }
1744
1745         kt_entry.principal = princ;
1746         kt_entry.vno       = kvno;
1747
1748         DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1749                   "encryption type (%d) and version (%d)\n",
1750                   princ_s, enctype, kt_entry.vno));
1751         ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1752         krb5_free_keyblock_contents(context, keyp);
1753         ZERO_STRUCT(kt_entry);
1754         if (ret) {
1755                 DEBUG(1, (__location__ ": adding entry to keytab "
1756                           "failed (%s)\n", error_message(ret)));
1757                 goto out;
1758         }
1759
1760 out:
1761         if (princ) {
1762                 krb5_free_principal(context, princ);
1763         }
1764
1765         return ret;
1766 }
1767
1768 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1769     defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1770     defined(HAVE_KRB5_GET_CREDS)
1771 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1772                                                              krb5_ccache ccache,
1773                                                              krb5_principal me,
1774                                                              krb5_principal server,
1775                                                              krb5_principal impersonate_princ,
1776                                                              krb5_creds **out_creds)
1777 {
1778         krb5_error_code ret;
1779         krb5_get_creds_opt opt;
1780
1781         ret = krb5_get_creds_opt_alloc(context, &opt);
1782         if (ret) {
1783                 goto done;
1784         }
1785         krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1786
1787         if (impersonate_princ) {
1788                 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1789                                                          impersonate_princ);
1790                 if (ret) {
1791                         goto done;
1792                 }
1793         }
1794
1795         ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1796         if (ret) {
1797                 goto done;
1798         }
1799
1800  done:
1801         if (opt) {
1802                 krb5_get_creds_opt_free(context, opt);
1803         }
1804         return ret;
1805 }
1806 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1807
1808 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1809
1810 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1811 krb5_error_code KRB5_CALLCONV
1812 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1813                               krb5_ccache ccache, krb5_creds *in_creds,
1814                               krb5_data *subject_cert,
1815                               krb5_creds **out_creds);
1816 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1817
1818 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1819                                                          krb5_ccache ccache,
1820                                                          krb5_principal me,
1821                                                          krb5_principal server,
1822                                                          krb5_principal impersonate_princ,
1823                                                          krb5_creds **out_creds)
1824 {
1825         krb5_error_code ret;
1826         krb5_creds in_creds;
1827
1828         ZERO_STRUCT(in_creds);
1829
1830         if (impersonate_princ) {
1831
1832                 in_creds.server = me;
1833                 in_creds.client = impersonate_princ;
1834
1835                 ret = krb5_get_credentials_for_user(context,
1836                                                     0, /* krb5_flags options */
1837                                                     ccache,
1838                                                     &in_creds,
1839                                                     NULL, /* krb5_data *subject_cert */
1840                                                     out_creds);
1841         } else {
1842                 in_creds.client = me;
1843                 in_creds.server = server;
1844
1845                 ret = krb5_get_credentials(context, 0, ccache,
1846                                            &in_creds, out_creds);
1847         }
1848
1849         return ret;
1850 }
1851 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1852
1853 /*
1854  * smb_krb5_get_credentials
1855  *
1856  * @brief Get krb5 credentials for a server
1857  *
1858  * @param[in] context           An initialized krb5_context
1859  * @param[in] ccache            An initialized krb5_ccache
1860  * @param[in] me                The krb5_principal of the caller
1861  * @param[in] server            The krb5_principal of the requested service
1862  * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1863  * @param[out] out_creds        The returned krb5_creds structure
1864  * @return krb5_error_code
1865  *
1866  */
1867 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1868                                          krb5_ccache ccache,
1869                                          krb5_principal me,
1870                                          krb5_principal server,
1871                                          krb5_principal impersonate_princ,
1872                                          krb5_creds **out_creds)
1873 {
1874         krb5_error_code ret;
1875         krb5_creds *creds = NULL;
1876
1877         if (out_creds != NULL) {
1878                 *out_creds = NULL;
1879         }
1880
1881         if (impersonate_princ) {
1882 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1883                 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1884 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1885                 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1886 #else
1887                 ret = ENOTSUP;
1888 #endif
1889         } else {
1890                 krb5_creds in_creds;
1891
1892                 ZERO_STRUCT(in_creds);
1893
1894                 in_creds.client = me;
1895                 in_creds.server = server;
1896
1897                 ret = krb5_get_credentials(context, 0, ccache,
1898                                            &in_creds, &creds);
1899         }
1900         if (ret) {
1901                 goto done;
1902         }
1903
1904         if (out_creds) {
1905                 *out_creds = creds;
1906         }
1907
1908  done:
1909         if (creds && ret) {
1910                 krb5_free_creds(context, creds);
1911         }
1912
1913         return ret;
1914 }
1915
1916 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
1917                                                 krb5_enctype enctype,
1918                                                 const void *data,
1919                                                 size_t length,
1920                                                 krb5_keyblock *key)
1921 {
1922 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
1923         return krb5_keyblock_init(context, enctype, data, length, key);
1924 #else
1925         memset(key, 0, sizeof(krb5_keyblock));
1926         KRB5_KEY_DATA(key) = SMB_MALLOC(length);
1927         if (NULL == KRB5_KEY_DATA(key)) {
1928                 return ENOMEM;
1929         }
1930         memcpy(KRB5_KEY_DATA(key), data, length);
1931         KRB5_KEY_LENGTH(key) = length;
1932         KRB5_KEY_TYPE(key) = enctype;
1933         return 0;
1934 #endif
1935 }
1936
1937 /*
1938   simulate a kinit, putting the tgt in the given credentials cache.
1939   Orignally by remus@snapserver.com
1940
1941   This version is built to use a keyblock, rather than needing the
1942   original password.
1943
1944   The impersonate_principal is the principal if NULL, or the principal
1945   to impersonate
1946
1947   The target_service defaults to the krbtgt if NULL, but could be
1948    kpasswd/realm or the local service (if we are doing s4u2self)
1949 */
1950 krb5_error_code kerberos_kinit_keyblock_cc(krb5_context ctx, krb5_ccache cc,
1951                                            krb5_principal principal,
1952                                            krb5_keyblock *keyblock,
1953                                            const char *target_service,
1954                                            krb5_get_init_creds_opt *krb_options,
1955                                            time_t *expire_time,
1956                                            time_t *kdc_time)
1957 {
1958         krb5_error_code code = 0;
1959         krb5_creds my_creds;
1960
1961 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
1962         code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
1963                                             keyblock, 0, target_service,
1964                                             krb_options);
1965 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
1966 {
1967 #define SMB_CREDS_KEYTAB "MEMORY:tmp_smb_creds_XXXXXX"
1968         char tmp_name[sizeof(SMB_CREDS_KEYTAB)];
1969         krb5_keytab_entry entry;
1970         krb5_keytab keytab;
1971         mode_t mask;
1972
1973         memset(&entry, 0, sizeof(entry));
1974         entry.principal = principal;
1975         *(KRB5_KT_KEY(&entry)) = *keyblock;
1976
1977         memcpy(tmp_name, SMB_CREDS_KEYTAB, sizeof(SMB_CREDS_KEYTAB));
1978         mask = umask(S_IRWXO | S_IRWXG);
1979         mktemp(tmp_name);
1980         umask(mask);
1981         if (tmp_name[0] == 0) {
1982                 return KRB5_KT_BADNAME;
1983         }
1984         code = krb5_kt_resolve(ctx, tmp_name, &keytab);
1985         if (code) {
1986                 return code;
1987         }
1988
1989         code = krb5_kt_add_entry(ctx, keytab, &entry);
1990         if (code) {
1991                 (void)krb5_kt_close(ctx, keytab);
1992                 goto done;
1993         }
1994
1995         code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
1996                                           keytab, 0, target_service,
1997                                           krb_options);
1998         (void)krb5_kt_close(ctx, keytab);
1999 }
2000 #else
2001 #error krb5_get_init_creds_keyblock not available!
2002 #endif
2003         if (code) {
2004                 return code;
2005         }
2006
2007 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2008         /*
2009          * We need to store the principal as returned from the KDC to the
2010          * credentials cache. If we don't do that the KRB5 library is not
2011          * able to find the tickets it is looking for
2012          */
2013         principal = my_creds.client;
2014 #endif
2015         code = krb5_cc_initialize(ctx, cc, principal);
2016         if (code) {
2017                 goto done;
2018         }
2019
2020         code = krb5_cc_store_cred(ctx, cc, &my_creds);
2021         if (code) {
2022                 goto done;
2023         }
2024
2025         if (expire_time) {
2026                 *expire_time = (time_t) my_creds.times.endtime;
2027         }
2028
2029         if (kdc_time) {
2030                 *kdc_time = (time_t) my_creds.times.starttime;
2031         }
2032
2033         code = 0;
2034 done:
2035         krb5_free_cred_contents(ctx, &my_creds);
2036         return code;
2037 }
2038
2039 krb5_error_code kerberos_kinit_password_cc(krb5_context ctx, krb5_ccache cc,
2040                                            krb5_principal principal,
2041                                            const char *password,
2042                                            const char *target_service,
2043                                            krb5_get_init_creds_opt *krb_options,
2044                                            time_t *expire_time,
2045                                            time_t *kdc_time)
2046 {
2047         krb5_error_code code = 0;
2048         krb5_creds my_creds;
2049
2050         code = krb5_get_init_creds_password(ctx, &my_creds, principal,
2051                                             password, NULL, NULL, 0,
2052                                             target_service, krb_options);
2053         if (code) {
2054                 return code;
2055         }
2056
2057 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2058         /*
2059          * We need to store the principal as returned from the KDC to the
2060          * credentials cache. If we don't do that the KRB5 library is not
2061          * able to find the tickets it is looking for
2062          */
2063         principal = my_creds.client;
2064 #endif
2065         code = krb5_cc_initialize(ctx, cc, principal);
2066         if (code) {
2067                 goto done;
2068         }
2069
2070         code = krb5_cc_store_cred(ctx, cc, &my_creds);
2071         if (code) {
2072                 goto done;
2073         }
2074
2075         if (expire_time) {
2076                 *expire_time = (time_t) my_creds.times.endtime;
2077         }
2078
2079         if (kdc_time) {
2080                 *kdc_time = (time_t) my_creds.times.starttime;
2081         }
2082
2083         code = 0;
2084 done:
2085         krb5_free_cred_contents(ctx, &my_creds);
2086         return code;
2087 }
2088
2089 #ifdef SAMBA4_USES_HEIMDAL
2090 /*
2091   simulate a kinit, putting the tgt in the given credentials cache.
2092   Orignally by remus@snapserver.com
2093
2094   The impersonate_principal is the principal
2095
2096   The self_service, should be the local service (for S4U2Self if
2097   impersonate_principal is given).
2098
2099   The target_service defaults to the krbtgt if NULL, but could be
2100   kpasswd/realm or a remote service (for S4U2Proxy)
2101
2102 */
2103 krb5_error_code kerberos_kinit_s4u2_cc(krb5_context ctx,
2104                                         krb5_ccache store_cc,
2105                                         krb5_principal init_principal,
2106                                         const char *init_password,
2107                                         krb5_principal impersonate_principal,
2108                                         const char *self_service,
2109                                         const char *target_service,
2110                                         krb5_get_init_creds_opt *krb_options,
2111                                         time_t *expire_time,
2112                                         time_t *kdc_time)
2113 {
2114         krb5_error_code code = 0;
2115         krb5_get_creds_opt options;
2116         krb5_principal store_principal;
2117         krb5_creds store_creds;
2118         krb5_creds *s4u2self_creds;
2119         Ticket s4u2self_ticket;
2120         size_t s4u2self_ticketlen;
2121         krb5_creds *s4u2proxy_creds;
2122         krb5_principal self_princ;
2123         bool s4u2proxy;
2124         krb5_principal target_princ;
2125         krb5_ccache tmp_cc;
2126         const char *self_realm;
2127         krb5_principal blacklist_principal = NULL;
2128         krb5_principal whitelist_principal = NULL;
2129
2130         code = krb5_get_init_creds_password(ctx, &store_creds,
2131                                             init_principal,
2132                                             init_password,
2133                                             NULL, NULL,
2134                                             0,
2135                                             NULL,
2136                                             krb_options);
2137         if (code != 0) {
2138                 return code;
2139         }
2140
2141         store_principal = init_principal;
2142
2143         /*
2144          * We are trying S4U2Self now:
2145          *
2146          * As we do not want to expose our TGT in the
2147          * krb5_ccache, which is also holds the impersonated creds.
2148          *
2149          * Some low level krb5/gssapi function might use the TGT
2150          * identity and let the client act as our machine account.
2151          *
2152          * We need to avoid that and use a temporary krb5_ccache
2153          * in order to pass our TGT to the krb5_get_creds() function.
2154          */
2155         code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
2156         if (code != 0) {
2157                 krb5_free_cred_contents(ctx, &store_creds);
2158                 return code;
2159         }
2160
2161         code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
2162         if (code != 0) {
2163                 krb5_cc_destroy(ctx, tmp_cc);
2164                 krb5_free_cred_contents(ctx, &store_creds);
2165                 return code;
2166         }
2167
2168         code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
2169         if (code != 0) {
2170                 krb5_free_cred_contents(ctx, &store_creds);
2171                 krb5_cc_destroy(ctx, tmp_cc);
2172                 return code;
2173         }
2174
2175         /*
2176          * we need to remember the client principal of our
2177          * TGT and make sure the KDC does not return this
2178          * in the impersonated tickets. This can happen
2179          * if the KDC does not support S4U2Self and S4U2Proxy.
2180          */
2181         blacklist_principal = store_creds.client;
2182         store_creds.client = NULL;
2183         krb5_free_cred_contents(ctx, &store_creds);
2184
2185         /*
2186          * Check if we also need S4U2Proxy or if S4U2Self is
2187          * enough in order to get a ticket for the target.
2188          */
2189         if (target_service == NULL) {
2190                 s4u2proxy = false;
2191         } else if (strcmp(target_service, self_service) == 0) {
2192                 s4u2proxy = false;
2193         } else {
2194                 s4u2proxy = true;
2195         }
2196
2197         /*
2198          * For S4U2Self we need our own service principal,
2199          * which belongs to our own realm (available on
2200          * our client principal).
2201          */
2202         self_realm = krb5_principal_get_realm(ctx, init_principal);
2203
2204         code = krb5_parse_name(ctx, self_service, &self_princ);
2205         if (code != 0) {
2206                 krb5_free_principal(ctx, blacklist_principal);
2207                 krb5_cc_destroy(ctx, tmp_cc);
2208                 return code;
2209         }
2210
2211         code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2212         if (code != 0) {
2213                 krb5_free_principal(ctx, blacklist_principal);
2214                 krb5_free_principal(ctx, self_princ);
2215                 krb5_cc_destroy(ctx, tmp_cc);
2216                 return code;
2217         }
2218
2219         code = krb5_get_creds_opt_alloc(ctx, &options);
2220         if (code != 0) {
2221                 krb5_free_principal(ctx, blacklist_principal);
2222                 krb5_free_principal(ctx, self_princ);
2223                 krb5_cc_destroy(ctx, tmp_cc);
2224                 return code;
2225         }
2226
2227         if (s4u2proxy) {
2228                 /*
2229                  * If we want S4U2Proxy, we need the forwardable flag
2230                  * on the S4U2Self ticket.
2231                  */
2232                 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2233         }
2234
2235         code = krb5_get_creds_opt_set_impersonate(ctx, options,
2236                                                   impersonate_principal);
2237         if (code != 0) {
2238                 krb5_get_creds_opt_free(ctx, options);
2239                 krb5_free_principal(ctx, blacklist_principal);
2240                 krb5_free_principal(ctx, self_princ);
2241                 krb5_cc_destroy(ctx, tmp_cc);
2242                 return code;
2243         }
2244
2245         code = krb5_get_creds(ctx, options, tmp_cc,
2246                               self_princ, &s4u2self_creds);
2247         krb5_get_creds_opt_free(ctx, options);
2248         krb5_free_principal(ctx, self_princ);
2249         if (code != 0) {
2250                 krb5_free_principal(ctx, blacklist_principal);
2251                 krb5_cc_destroy(ctx, tmp_cc);
2252                 return code;
2253         }
2254
2255         if (!s4u2proxy) {
2256                 krb5_cc_destroy(ctx, tmp_cc);
2257
2258                 /*
2259                  * Now make sure we store the impersonated principal
2260                  * and creds instead of the TGT related stuff
2261                  * in the krb5_ccache of the caller.
2262                  */
2263                 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2264                                                 &store_creds);
2265                 krb5_free_creds(ctx, s4u2self_creds);
2266                 if (code != 0) {
2267                         return code;
2268                 }
2269
2270                 /*
2271                  * It's important to store the principal the KDC
2272                  * returned, as otherwise the caller would not find
2273                  * the S4U2Self ticket in the krb5_ccache lookup.
2274                  */
2275                 store_principal = store_creds.client;
2276                 goto store;
2277         }
2278
2279         /*
2280          * We are trying S4U2Proxy:
2281          *
2282          * We need the ticket from the S4U2Self step
2283          * and our TGT in order to get the delegated ticket.
2284          */
2285         code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2286                              s4u2self_creds->ticket.length,
2287                              &s4u2self_ticket,
2288                              &s4u2self_ticketlen);
2289         if (code != 0) {
2290                 krb5_free_creds(ctx, s4u2self_creds);
2291                 krb5_free_principal(ctx, blacklist_principal);
2292                 krb5_cc_destroy(ctx, tmp_cc);
2293                 return code;
2294         }
2295
2296         /*
2297          * we need to remember the client principal of the
2298          * S4U2Self stage and as it needs to match the one we
2299          * will get for the S4U2Proxy stage. We need this
2300          * in order to detect KDCs which does not support S4U2Proxy.
2301          */
2302         whitelist_principal = s4u2self_creds->client;
2303         s4u2self_creds->client = NULL;
2304         krb5_free_creds(ctx, s4u2self_creds);
2305
2306         /*
2307          * For S4U2Proxy we also got a target service principal,
2308          * which also belongs to our own realm (available on
2309          * our client principal).
2310          */
2311         code = krb5_parse_name(ctx, target_service, &target_princ);
2312         if (code != 0) {
2313                 free_Ticket(&s4u2self_ticket);
2314                 krb5_free_principal(ctx, whitelist_principal);
2315                 krb5_free_principal(ctx, blacklist_principal);
2316                 krb5_cc_destroy(ctx, tmp_cc);
2317                 return code;
2318         }
2319
2320         code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2321         if (code != 0) {
2322                 free_Ticket(&s4u2self_ticket);
2323                 krb5_free_principal(ctx, target_princ);
2324                 krb5_free_principal(ctx, whitelist_principal);
2325                 krb5_free_principal(ctx, blacklist_principal);
2326                 krb5_cc_destroy(ctx, tmp_cc);
2327                 return code;
2328         }
2329
2330         code = krb5_get_creds_opt_alloc(ctx, &options);
2331         if (code != 0) {
2332                 free_Ticket(&s4u2self_ticket);
2333                 krb5_free_principal(ctx, target_princ);
2334                 krb5_free_principal(ctx, whitelist_principal);
2335                 krb5_free_principal(ctx, blacklist_principal);
2336                 krb5_cc_destroy(ctx, tmp_cc);
2337                 return code;
2338         }
2339
2340         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2341         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2342
2343         code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2344         free_Ticket(&s4u2self_ticket);
2345         if (code != 0) {
2346                 krb5_get_creds_opt_free(ctx, options);
2347                 krb5_free_principal(ctx, target_princ);
2348                 krb5_free_principal(ctx, whitelist_principal);
2349                 krb5_free_principal(ctx, blacklist_principal);
2350                 krb5_cc_destroy(ctx, tmp_cc);
2351                 return code;
2352         }
2353
2354         code = krb5_get_creds(ctx, options, tmp_cc,
2355                               target_princ, &s4u2proxy_creds);
2356         krb5_get_creds_opt_free(ctx, options);
2357         krb5_free_principal(ctx, target_princ);
2358         krb5_cc_destroy(ctx, tmp_cc);
2359         if (code != 0) {
2360                 krb5_free_principal(ctx, whitelist_principal);
2361                 krb5_free_principal(ctx, blacklist_principal);
2362                 return code;
2363         }
2364
2365         /*
2366          * Now make sure we store the impersonated principal
2367          * and creds instead of the TGT related stuff
2368          * in the krb5_ccache of the caller.
2369          */
2370         code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2371                                         &store_creds);
2372         krb5_free_creds(ctx, s4u2proxy_creds);
2373         if (code != 0) {
2374                 krb5_free_principal(ctx, whitelist_principal);
2375                 krb5_free_principal(ctx, blacklist_principal);
2376                 return code;
2377         }
2378
2379         /*
2380          * It's important to store the principal the KDC
2381          * returned, as otherwise the caller would not find
2382          * the S4U2Self ticket in the krb5_ccache lookup.
2383          */
2384         store_principal = store_creds.client;
2385
2386  store:
2387         if (blacklist_principal &&
2388             krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2389                 char *sp = NULL;
2390                 char *ip = NULL;
2391
2392                 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2393                 if (code != 0) {
2394                         sp = NULL;
2395                 }
2396                 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2397                 if (code != 0) {
2398                         ip = NULL;
2399                 }
2400                 DEBUG(1, ("kerberos_kinit_password_cc: "
2401                           "KDC returned self principal[%s] while impersonating [%s]\n",
2402                           sp?sp:"<no memory>",
2403                           ip?ip:"<no memory>"));
2404
2405                 SAFE_FREE(sp);
2406                 SAFE_FREE(ip);
2407
2408                 krb5_free_principal(ctx, whitelist_principal);
2409                 krb5_free_principal(ctx, blacklist_principal);
2410                 krb5_free_cred_contents(ctx, &store_creds);
2411                 return KRB5_FWD_BAD_PRINCIPAL;
2412         }
2413         if (blacklist_principal) {
2414                 krb5_free_principal(ctx, blacklist_principal);
2415         }
2416
2417         if (whitelist_principal &&
2418             !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2419                 char *sp = NULL;
2420                 char *ep = NULL;
2421
2422                 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2423                 if (code != 0) {
2424                         sp = NULL;
2425                 }
2426                 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2427                 if (code != 0) {
2428                         ep = NULL;
2429                 }
2430                 DEBUG(1, ("kerberos_kinit_password_cc: "
2431                           "KDC returned wrong principal[%s] we expected [%s]\n",
2432                           sp?sp:"<no memory>",
2433                           ep?ep:"<no memory>"));
2434
2435                 SAFE_FREE(sp);
2436                 SAFE_FREE(ep);
2437
2438                 krb5_free_principal(ctx, whitelist_principal);
2439                 krb5_free_cred_contents(ctx, &store_creds);
2440                 return KRB5_FWD_BAD_PRINCIPAL;
2441         }
2442         if (whitelist_principal) {
2443                 krb5_free_principal(ctx, whitelist_principal);
2444         }
2445
2446         code = krb5_cc_initialize(ctx, store_cc, store_principal);
2447         if (code != 0) {
2448                 krb5_free_cred_contents(ctx, &store_creds);
2449                 return code;
2450         }
2451
2452         code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2453         if (code != 0) {
2454                 krb5_free_cred_contents(ctx, &store_creds);
2455                 return code;
2456         }
2457
2458         if (expire_time) {
2459                 *expire_time = (time_t) store_creds.times.endtime;
2460         }
2461
2462         if (kdc_time) {
2463                 *kdc_time = (time_t) store_creds.times.starttime;
2464         }
2465
2466         krb5_free_cred_contents(ctx, &store_creds);
2467
2468         return 0;
2469 }
2470 #endif
2471
2472 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2473 krb5_error_code smb_krb5_make_principal(krb5_context context,
2474                                         krb5_principal *principal,
2475                                         const char *_realm, ...)
2476 {
2477         krb5_error_code code;
2478         bool free_realm;
2479         char *realm;
2480         va_list ap;
2481
2482         if (_realm) {
2483                 realm = discard_const_p(char, _realm);
2484                 free_realm = false;
2485         } else {
2486                 code = krb5_get_default_realm(context, &realm);
2487                 if (code) {
2488                         return code;
2489                 }
2490                 free_realm = true;
2491         }
2492
2493         va_start(ap, _realm);
2494         code = krb5_build_principal_alloc_va(context, principal,
2495                                              strlen(realm), realm,
2496                                              ap);
2497         va_end(ap);
2498
2499         if (free_realm) {
2500                 krb5_free_default_realm(context, realm);
2501         }
2502
2503         return code;
2504 }
2505 #endif
2506
2507 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2508 /**
2509  * @brief Get the lifetime of the initial ticket in the cache.
2510  *
2511  * @param[in]  context  The kerberos context.
2512  *
2513  * @param[in]  id       The credential cache to get the ticket lifetime.
2514  *
2515  * @param[out] t        A pointer to a time value to store the lifetime.
2516  *
2517  * @return              0 on success, a krb5_error_code on error.
2518  */
2519 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2520                                          krb5_ccache id,
2521                                          time_t *t)
2522 {
2523         krb5_cc_cursor cursor;
2524         krb5_error_code kerr;
2525         krb5_creds cred;
2526         krb5_timestamp now;
2527
2528         *t = 0;
2529
2530         kerr = krb5_timeofday(context, &now);
2531         if (kerr) {
2532                 return kerr;
2533         }
2534
2535         kerr = krb5_cc_start_seq_get(context, id, &cursor);
2536         if (kerr) {
2537                 return kerr;
2538         }
2539
2540         while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2541 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2542                 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2543 #else
2544                 if (cred.flags.b.initial) {
2545 #endif
2546                         if (now < cred.times.endtime) {
2547                                 *t = (time_t) (cred.times.endtime - now);
2548                         }
2549                         krb5_free_cred_contents(context, &cred);
2550                         break;
2551                 }
2552                 krb5_free_cred_contents(context, &cred);
2553         }
2554
2555         krb5_cc_end_seq_get(context, id, &cursor);
2556
2557         return kerr;
2558 }
2559 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2560
2561 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2562 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2563 {
2564         free_Checksum(cksum);
2565 }
2566 #endif
2567
2568 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2569                                            DATA_BLOB *pac_data,
2570                                            krb5_context context,
2571                                            const krb5_keyblock *keyblock,
2572                                            uint32_t *sig_type,
2573                                            DATA_BLOB *sig_blob)
2574 {
2575         krb5_error_code ret;
2576         krb5_checksum cksum;
2577 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2578         krb5_crypto crypto;
2579
2580
2581         ret = krb5_crypto_init(context,
2582                                keyblock,
2583                                0,
2584                                &crypto);
2585         if (ret) {
2586                 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2587                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2588                 return ret;
2589         }
2590         ret = krb5_create_checksum(context,
2591                                    crypto,
2592                                    KRB5_KU_OTHER_CKSUM,
2593                                    0,
2594                                    pac_data->data,
2595                                    pac_data->length,
2596                                    &cksum);
2597         if (ret) {
2598                 DEBUG(2, ("PAC Verification failed: %s\n",
2599                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2600         }
2601
2602         krb5_crypto_destroy(context, crypto);
2603
2604         if (ret) {
2605                 return ret;
2606         }
2607
2608         *sig_type = cksum.cksumtype;
2609         *sig_blob = data_blob_talloc(mem_ctx,
2610                                         cksum.checksum.data,
2611                                         cksum.checksum.length);
2612 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2613         krb5_data input;
2614
2615         input.data = (char *)pac_data->data;
2616         input.length = pac_data->length;
2617
2618         ret = krb5_c_make_checksum(context,
2619                                    0,
2620                                    keyblock,
2621                                    KRB5_KEYUSAGE_APP_DATA_CKSUM,
2622                                    &input,
2623                                    &cksum);
2624         if (ret) {
2625                 DEBUG(2, ("PAC Verification failed: %s\n",
2626                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2627                 return ret;
2628         }
2629
2630         *sig_type = cksum.checksum_type;
2631         *sig_blob = data_blob_talloc(mem_ctx,
2632                                         cksum.contents,
2633                                         cksum.length);
2634
2635 #else
2636 #error krb5_create_checksum or krb5_c_make_checksum not available
2637 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2638         smb_krb5_free_checksum_contents(context, &cksum);
2639
2640         return 0;
2641 }
2642
2643
2644 /*
2645  * smb_krb5_principal_get_realm
2646  *
2647  * @brief Get realm of a principal
2648  *
2649  * @param[in] context           The krb5_context
2650  * @param[in] principal         The principal
2651  * @return pointer to the realm
2652  *
2653  * Caller must free if the return value is not NULL.
2654  *
2655  */
2656
2657 char *smb_krb5_principal_get_realm(krb5_context context,
2658                                    krb5_const_principal principal)
2659 {
2660 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2661         return strdup(discard_const_p(char, krb5_principal_get_realm(context, principal)));
2662 #elif defined(krb5_princ_realm) /* MIT */
2663         krb5_data *realm;
2664         realm = discard_const_p(krb5_data,
2665                                 krb5_princ_realm(context, principal));
2666         return strndup(realm->data, realm->length);
2667 #else
2668 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
2669 #endif
2670 }
2671
2672 /*
2673  * smb_krb5_principal_set_realm
2674  *
2675  * @brief Get realm of a principal
2676  *
2677  * @param[in] context           The krb5_context
2678  * @param[in] principal         The principal
2679  * @param[in] realm             The realm
2680  * @return                      0 on success, a krb5_error_code on error.
2681  *
2682  */
2683
2684 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
2685                                              krb5_principal principal,
2686                                              const char *realm)
2687 {
2688 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
2689         return krb5_principal_set_realm(context, principal, realm);
2690 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
2691         krb5_error_code ret;
2692         krb5_data data;
2693         krb5_data *old_data;
2694
2695         old_data = krb5_princ_realm(context, principal);
2696
2697         ret = krb5_copy_data_contents(&data,
2698                                       realm,
2699                                       strlen(realm));
2700         if (ret) {
2701                 return ret;
2702         }
2703
2704         /* free realm before setting */
2705         free(old_data->data);
2706
2707         krb5_princ_set_realm(context, principal, &data);
2708
2709         return ret;
2710 #else
2711 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
2712 #endif
2713 }
2714
2715
2716 /************************************************************************
2717  Routine to get the default realm from the kerberos credentials cache.
2718  Caller must free if the return value is not NULL.
2719 ************************************************************************/
2720
2721 static char *smb_krb5_get_default_realm_from_ccache(TALLOC_CTX *mem_ctx)
2722 {
2723         char *realm = NULL;
2724         krb5_context ctx = NULL;
2725         krb5_ccache cc = NULL;
2726         krb5_principal princ = NULL;
2727
2728         initialize_krb5_error_table();
2729         if (krb5_init_context(&ctx)) {
2730                 return NULL;
2731         }
2732
2733         DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2734                 "Trying to read krb5 cache: %s\n",
2735                 krb5_cc_default_name(ctx)));
2736         if (krb5_cc_default(ctx, &cc)) {
2737                 DEBUG(0,("kerberos_get_default_realm_from_ccache: "
2738                         "failed to read default cache\n"));
2739                 goto out;
2740         }
2741         if (krb5_cc_get_principal(ctx, cc, &princ)) {
2742                 DEBUG(0,("kerberos_get_default_realm_from_ccache: "
2743                         "failed to get default principal\n"));
2744                 goto out;
2745         }
2746
2747 #if defined(HAVE_KRB5_PRINCIPAL_GET_REALM)
2748         realm = talloc_strdup(mem_ctx, krb5_principal_get_realm(ctx, princ));
2749 #elif defined(HAVE_KRB5_PRINC_REALM)
2750         {
2751                 krb5_data *realm_data = krb5_princ_realm(ctx, princ);
2752                 realm = talloc_strndup(mem_ctx, realm_data->data, realm_data->length);
2753         }
2754 #endif
2755
2756   out:
2757
2758         if (ctx) {
2759                 if (princ) {
2760                         krb5_free_principal(ctx, princ);
2761                 }
2762                 if (cc) {
2763                         krb5_cc_close(ctx, cc);
2764                 }
2765                 krb5_free_context(ctx);
2766         }
2767
2768         return realm;
2769 }
2770
2771 /************************************************************************
2772  Routine to get the realm from a given DNS name.
2773 ************************************************************************/
2774
2775 static char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2776                                                 const char *hostname)
2777 {
2778 #if defined(HAVE_KRB5_REALM_TYPE)
2779         /* Heimdal. */
2780         krb5_realm *realm_list = NULL;
2781 #else
2782         /* MIT */
2783         char **realm_list = NULL;
2784 #endif
2785         char *realm = NULL;
2786         krb5_error_code kerr;
2787         krb5_context ctx = NULL;
2788
2789         initialize_krb5_error_table();
2790         if (krb5_init_context(&ctx)) {
2791                 return NULL;
2792         }
2793
2794         kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
2795         if (kerr != 0) {
2796                 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
2797                         "failed %s\n",
2798                         hostname ? hostname : "(NULL)",
2799                         error_message(kerr) ));
2800                 goto out;
2801         }
2802
2803         if (realm_list && realm_list[0]) {
2804                 realm = talloc_strdup(mem_ctx, realm_list[0]);
2805         }
2806
2807   out:
2808
2809         if (ctx) {
2810                 if (realm_list) {
2811                         krb5_free_host_realm(ctx, realm_list);
2812                         realm_list = NULL;
2813                 }
2814                 krb5_free_context(ctx);
2815                 ctx = NULL;
2816         }
2817         return realm;
2818 }
2819
2820 char *kerberos_get_principal_from_service_hostname(TALLOC_CTX *mem_ctx,
2821                                                    const char *service,
2822                                                    const char *remote_name,
2823                                                    const char *default_realm)
2824 {
2825         char *realm = NULL;
2826         char *host = NULL;
2827         char *principal;
2828         host = strchr_m(remote_name, '.');
2829         if (host) {
2830                 /* DNS name. */
2831                 realm = smb_krb5_get_realm_from_hostname(talloc_tos(),
2832                                                          remote_name);
2833         } else {
2834                 /* NetBIOS name - use our realm. */
2835                 realm = smb_krb5_get_default_realm_from_ccache(talloc_tos());
2836         }
2837
2838         if (realm == NULL || *realm == '\0') {
2839                 realm = talloc_strdup(talloc_tos(), default_realm);
2840                 if (!realm) {
2841                         return NULL;
2842                 }
2843                 DEBUG(3,("kerberos_get_principal_from_service_hostname: "
2844                          "cannot get realm from, "
2845                          "desthost %s or default ccache. Using default "
2846                          "smb.conf realm %s\n",
2847                          remote_name,
2848                          realm));
2849         }
2850
2851         principal = talloc_asprintf(mem_ctx,
2852                                     "%s/%s@%s",
2853                                     service, remote_name,
2854                                     realm);
2855         TALLOC_FREE(realm);
2856         return principal;
2857 }
2858
2859 char *smb_get_krb5_error_message(krb5_context context,
2860                                  krb5_error_code code,
2861                                  TALLOC_CTX *mem_ctx)
2862 {
2863         char *ret;
2864
2865 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
2866         const char *context_error = krb5_get_error_message(context, code);
2867         if (context_error) {
2868                 ret = talloc_asprintf(mem_ctx, "%s: %s",
2869                                         error_message(code), context_error);
2870                 krb5_free_error_message(context, context_error);
2871                 return ret;
2872         }
2873 #endif
2874         ret = talloc_strdup(mem_ctx, error_message(code));
2875         return ret;
2876 }
2877
2878
2879 /**
2880 * @brief Return the kerberos library setting for "libdefaults:allow_weak_crypto"
2881 *
2882 * @param context        The krb5_context
2883 *
2884 * @return krb5_boolean
2885 *
2886 * Function returns true if weak crypto is allowd, false if not
2887 */
2888
2889 krb5_boolean smb_krb5_get_allowed_weak_crypto(krb5_context context)
2890 #if defined(HAVE_KRB5_CONFIG_GET_BOOL_DEFAULT)
2891 {
2892         return krb5_config_get_bool_default(context,
2893                                             NULL,
2894                                             FALSE,
2895                                             "libdefaults",
2896                                             "allow_weak_crypto",
2897                                             NULL);
2898 }
2899 #elif defined(HAVE_PROFILE_H) && defined(HAVE_KRB5_GET_PROFILE)
2900 {
2901 #include <profile.h>
2902         krb5_error_code ret;
2903         krb5_boolean ret_default = false;
2904         profile_t profile;
2905         int ret_profile;
2906
2907         ret = krb5_get_profile(context,
2908                                &profile);
2909         if (ret) {
2910                 return ret_default;
2911         }
2912
2913         ret = profile_get_boolean(profile,
2914                                   "libdefaults",
2915                                   "allow_weak_crypto",
2916                                   NULL, /* subsubname */
2917                                   ret_default, /* def_val */
2918                                   &ret_profile /* *ret_default */);
2919         if (ret) {
2920                 return ret_default;
2921         }
2922
2923         profile_release(profile);
2924
2925         return ret_profile;
2926 }
2927 #else
2928 #error UNKNOWN_KRB5_CONFIG_ROUTINES
2929 #endif
2930
2931 /**
2932 * @brief Return the type of a krb5_principal
2933 *
2934 * @param context        The krb5_context
2935 * @param principal      The const krb5_principal
2936 *
2937 * @return integer type of the principal
2938 */
2939 int smb_krb5_principal_get_type(krb5_context context,
2940                                 krb5_const_principal principal)
2941 {
2942 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
2943         return krb5_principal_get_type(context, principal);
2944 #elif defined(krb5_princ_type) /* MIT */
2945         return krb5_princ_type(context, principal);
2946 #else
2947 #error  UNKNOWN_PRINC_GET_TYPE_FUNCTION
2948 #endif
2949 }
2950
2951 /**
2952 * @brief Set the type of a krb5_principal
2953 *
2954 * @param context        The krb5_context
2955 * @param principal      The const krb5_principal
2956 * @param type           The principal type
2957 *
2958 */
2959 void smb_krb5_principal_set_type(krb5_context context,
2960                                  krb5_principal principal,
2961                                  int type)
2962 {
2963 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
2964         krb5_principal_set_type(context, principal, type);
2965 #elif defined(krb5_princ_type) /* MIT */
2966         krb5_princ_type(context, principal) = type;
2967 #else
2968 #error  UNKNOWN_PRINC_SET_TYPE_FUNCTION
2969 #endif
2970 }
2971
2972 /**
2973 * @brief Generate a krb5 warning, forwarding to com_err
2974 *
2975 * @param context        The krb5_context
2976 * @param fmt            The message format
2977 * @param ...            The message arguments
2978 *
2979 * @return
2980 */
2981 #if !defined(HAVE_KRB5_WARNX)
2982 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
2983 {
2984         va_list args;
2985
2986         va_start(args, fmt);
2987         com_err_va("kdb_samba", errno, fmt, args);
2988         va_end(args);
2989
2990         return 0;
2991 }
2992 #endif
2993
2994 #else /* HAVE_KRB5 */
2995  /* this saves a few linking headaches */
2996  int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
2997                         const char *principal, time_t time_offset,
2998                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
2999                         uint32_t extra_ap_opts,
3000                         const char *ccname, time_t *tgs_expire,
3001                         const char *impersonate_princ_s)
3002 {
3003          DEBUG(0,("NO KERBEROS SUPPORT\n"));
3004          return 1;
3005 }
3006
3007 #endif /* HAVE_KRB5 */