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