s3:smbd: only do profiling overhead in smbd_tevent_trace_callback() when needed
[Samba.git] / lib / krb5_wrap / krb5_samba.c
blob22aeda330269dac47af2017fb1ce92dd4a937df3
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
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.
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.
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/>.
23 #include "includes.h"
24 #include "system/filesys.h"
25 #include "krb5_samba.h"
26 #include "lib/crypto/md4.h"
27 #include "../libds/common/flags.h"
29 #ifdef HAVE_COM_ERR_H
30 #include <com_err.h>
31 #endif /* HAVE_COM_ERR_H */
33 #ifndef KRB5_AUTHDATA_WIN2K_PAC
34 #define KRB5_AUTHDATA_WIN2K_PAC 128
35 #endif
37 #ifndef KRB5_AUTHDATA_IF_RELEVANT
38 #define KRB5_AUTHDATA_IF_RELEVANT 1
39 #endif
41 #ifdef HAVE_KRB5
43 #define GSSAPI_CHECKSUM 0x8003 /* Checksum type value for Kerberos */
44 #define GSSAPI_BNDLENGTH 16 /* Bind Length (rfc-1964 pg.3) */
45 #define GSSAPI_CHECKSUM_SIZE (4+GSSAPI_BNDLENGTH+4) /* Length of bind length,
46 bind field, flags field. */
47 #define GSS_C_DELEG_FLAG 1
49 /* MIT krb5 1.7beta3 (in Ubuntu Karmic) is missing the prototype,
50 but still has the symbol */
51 #if !HAVE_DECL_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE
52 krb5_error_code krb5_auth_con_set_req_cksumtype(
53 krb5_context context,
54 krb5_auth_context auth_context,
55 krb5_cksumtype cksumtype);
56 #endif
58 #if !defined(SMB_MALLOC)
59 #undef malloc
60 #define SMB_MALLOC(s) malloc((s))
61 #endif
63 #ifndef SMB_STRDUP
64 #define SMB_STRDUP(s) strdup(s)
65 #endif
67 /**********************************************************
68 * MISSING FUNCTIONS
69 **********************************************************/
71 #if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
73 #if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)
75 /* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
76 * to krb5_set_default_tgs_ktypes. See
77 * http://lists.samba.org/archive/samba-technical/2006-July/048271.html
79 * If the MIT libraries are not exporting internal symbols, we will end up in
80 * this branch, which is correct. Otherwise we will continue to use the
81 * internal symbol
83 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
85 return krb5_set_default_tgs_enctypes(ctx, enc);
88 #elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)
90 /* Heimdal */
91 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
93 return krb5_set_default_in_tkt_etypes(ctx, enc);
96 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */
98 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */
101 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
102 krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
103 krb5_auth_context auth_context,
104 krb5_keyblock *keyblock)
106 return krb5_auth_con_setkey(context, auth_context, keyblock);
108 #endif
110 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
111 void krb5_free_unparsed_name(krb5_context context, char *val)
113 SAFE_FREE(val);
115 #endif
117 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
118 const krb5_data *krb5_princ_component(krb5_context context,
119 krb5_principal principal, int i);
121 const krb5_data *krb5_princ_component(krb5_context context,
122 krb5_principal principal, int i)
124 static krb5_data kdata;
126 kdata.data = discard_const_p(char, krb5_principal_get_comp_string(context, principal, i));
127 kdata.length = strlen((const char *)kdata.data);
128 return &kdata;
130 #endif
133 /**********************************************************
134 * WRAPPING FUNCTIONS
135 **********************************************************/
137 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
138 /* HEIMDAL */
141 * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
143 * @param[in] paddr A pointer to a 'struct sockaddr_storage to extract the
144 * address from.
146 * @param[out] pkaddr A Kerberos address to store the address in.
148 * @return True on success, false if an error occurred.
150 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
151 krb5_address *pkaddr)
153 memset(pkaddr, '\0', sizeof(krb5_address));
154 #ifdef HAVE_IPV6
155 if (paddr->ss_family == AF_INET6) {
156 pkaddr->addr_type = KRB5_ADDRESS_INET6;
157 pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
158 pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
159 return true;
161 #endif
162 if (paddr->ss_family == AF_INET) {
163 pkaddr->addr_type = KRB5_ADDRESS_INET;
164 pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
165 pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
166 return true;
168 return false;
170 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
171 /* MIT */
174 * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
176 * @param[in] paddr A pointer to a 'struct sockaddr_storage to extract the
177 * address from.
179 * @param[in] pkaddr A Kerberos address to store the address in.
181 * @return True on success, false if an error occurred.
183 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
184 krb5_address *pkaddr)
186 memset(pkaddr, '\0', sizeof(krb5_address));
187 #ifdef HAVE_IPV6
188 if (paddr->ss_family == AF_INET6) {
189 pkaddr->addrtype = ADDRTYPE_INET6;
190 pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
191 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
192 return true;
194 #endif
195 if (paddr->ss_family == AF_INET) {
196 pkaddr->addrtype = ADDRTYPE_INET;
197 pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
198 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
199 return true;
201 return false;
203 #else
204 #error UNKNOWN_ADDRTYPE
205 #endif
207 krb5_error_code smb_krb5_mk_error(krb5_context context,
208 krb5_error_code error_code,
209 const char *e_text,
210 krb5_data *e_data,
211 const krb5_principal client,
212 const krb5_principal server,
213 krb5_data *enc_err)
215 krb5_error_code code = EINVAL;
216 #ifdef SAMBA4_USES_HEIMDAL
217 code = krb5_mk_error(context,
218 error_code,
219 e_text,
220 e_data,
221 client,
222 server,
223 NULL, /* client_time */
224 NULL, /* client_usec */
225 enc_err);
226 #else
227 krb5_principal unspec_server = NULL;
228 krb5_error errpkt;
230 errpkt.ctime = 0;
231 errpkt.cusec = 0;
233 code = krb5_us_timeofday(context,
234 &errpkt.stime,
235 &errpkt.susec);
236 if (code != 0) {
237 return code;
240 errpkt.error = error_code - ERROR_TABLE_BASE_krb5;
242 errpkt.text.length = 0;
243 if (e_text != NULL) {
244 errpkt.text.length = strlen(e_text);
245 errpkt.text.data = discard_const_p(char, e_text);
248 errpkt.e_data.magic = KV5M_DATA;
249 errpkt.e_data.length = 0;
250 errpkt.e_data.data = NULL;
251 if (e_data != NULL) {
252 errpkt.e_data = *e_data;
255 errpkt.client = client;
257 if (server != NULL) {
258 errpkt.server = server;
259 } else {
260 code = smb_krb5_make_principal(context,
261 &unspec_server,
262 "<unspecified realm>",
263 NULL);
264 if (code != 0) {
265 return code;
267 errpkt.server = unspec_server;
270 code = krb5_mk_error(context,
271 &errpkt,
272 enc_err);
273 krb5_free_principal(context, unspec_server);
274 #endif
275 return code;
279 * @brief Create a keyblock based on input parameters
281 * @param context The krb5_context
282 * @param host_princ The krb5_principal to use
283 * @param salt The optional salt, if omitted, salt is calculated with
284 * the provided principal.
285 * @param password The krb5_data containing the password
286 * @param enctype The krb5_enctype to use for the keyblock generation
287 * @param key The returned krb5_keyblock, caller needs to free with
288 * krb5_free_keyblock().
290 * @return krb5_error_code
292 int smb_krb5_create_key_from_string(krb5_context context,
293 krb5_const_principal host_princ,
294 const krb5_data *salt,
295 const krb5_data *password,
296 krb5_enctype enctype,
297 krb5_keyblock *key)
299 int ret = 0;
301 if (host_princ == NULL && salt == NULL) {
302 return -1;
305 if ((int)enctype == (int)ENCTYPE_ARCFOUR_HMAC) {
306 TALLOC_CTX *frame = talloc_stackframe();
307 uint8_t *utf16 = NULL;
308 size_t utf16_size = 0;
309 uint8_t nt_hash[16];
310 bool ok;
312 ok = convert_string_talloc(frame, CH_UNIX, CH_UTF16LE,
313 password->data, password->length,
314 (void **)&utf16, &utf16_size);
315 if (!ok) {
316 if (errno == 0) {
317 errno = EINVAL;
319 ret = errno;
320 TALLOC_FREE(frame);
321 return ret;
324 mdfour(nt_hash, utf16, utf16_size);
325 BURN_PTR_SIZE(utf16, utf16_size);
326 ret = smb_krb5_keyblock_init_contents(context,
327 ENCTYPE_ARCFOUR_HMAC,
328 nt_hash,
329 sizeof(nt_hash),
330 key);
331 ZERO_STRUCT(nt_hash);
332 if (ret != 0) {
333 TALLOC_FREE(frame);
334 return ret;
337 TALLOC_FREE(frame);
338 return 0;
341 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_C_STRING_TO_KEY)
342 {/* MIT */
343 krb5_data _salt;
345 if (salt == NULL) {
346 ret = krb5_principal2salt(context, host_princ, &_salt);
347 if (ret) {
348 DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
349 return ret;
351 } else {
352 _salt = *salt;
354 ret = krb5_c_string_to_key(context, enctype, password, &_salt, key);
355 if (salt == NULL) {
356 SAFE_FREE(_salt.data);
359 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
360 {/* Heimdal */
361 krb5_salt _salt;
363 if (salt == NULL) {
364 ret = krb5_get_pw_salt(context, host_princ, &_salt);
365 if (ret) {
366 DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
367 return ret;
369 } else {
370 _salt.saltvalue = *salt;
371 _salt.salttype = KRB5_PW_SALT;
374 ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, _salt, key);
375 if (salt == NULL) {
376 krb5_free_salt(context, _salt);
379 #else
380 #error UNKNOWN_CREATE_KEY_FUNCTIONS
381 #endif
382 return ret;
386 * @brief Create a salt for a given principal
388 * @param context The initialized krb5_context
389 * @param host_princ The krb5_principal to create the salt for
390 * @param psalt A pointer to a krb5_data struct
392 * caller has to free the contents of psalt with smb_krb5_free_data_contents
393 * when function has succeeded
395 * @return krb5_error_code, returns 0 on success, error code otherwise
398 int smb_krb5_get_pw_salt(krb5_context context,
399 krb5_const_principal host_princ,
400 krb5_data *psalt)
401 #if defined(HAVE_KRB5_GET_PW_SALT)
402 /* Heimdal */
404 int ret;
405 krb5_salt salt;
407 ret = krb5_get_pw_salt(context, host_princ, &salt);
408 if (ret) {
409 return ret;
412 psalt->data = salt.saltvalue.data;
413 psalt->length = salt.saltvalue.length;
415 return ret;
417 #elif defined(HAVE_KRB5_PRINCIPAL2SALT)
418 /* MIT */
420 return krb5_principal2salt(context, host_princ, psalt);
422 #else
423 #error UNKNOWN_SALT_FUNCTIONS
424 #endif
427 * @brief This constructs the salt principal used by active directory
429 * Most Kerberos encryption types require a salt in order to
430 * calculate the long term private key for user/computer object
431 * based on a password.
433 * The returned _salt_principal is a string in forms like this:
434 * - host/somehost.example.com@EXAMPLE.COM
435 * - SomeAccount@EXAMPLE.COM
436 * - SomePrincipal@EXAMPLE.COM
438 * This is not the form that's used as salt, it's just
439 * the human readable form. It needs to be converted by
440 * smb_krb5_salt_principal2data().
442 * @param[in] realm The realm the user/computer is added too.
444 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
446 * @param[in] userPrincipalName The userPrincipalName attribute of the object
447 * or NULL is not available.
449 * @param[in] uac_flags UF_ACCOUNT_TYPE_MASKed userAccountControl field
451 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
453 * @param[out] _salt_principal The resulting principal as string.
455 * @retval 0 Success; otherwise - Kerberos error codes
457 * @see smb_krb5_salt_principal2data
459 int smb_krb5_salt_principal(krb5_context krb5_ctx,
460 const char *realm,
461 const char *sAMAccountName,
462 const char *userPrincipalName,
463 uint32_t uac_flags,
464 krb5_principal *salt_princ)
466 TALLOC_CTX *frame = talloc_stackframe();
467 char *upper_realm = NULL;
468 const char *principal = NULL;
469 int principal_len = 0;
470 krb5_error_code krb5_ret;
472 *salt_princ = NULL;
474 if (sAMAccountName == NULL) {
475 TALLOC_FREE(frame);
476 return EINVAL;
479 if (realm == NULL) {
480 TALLOC_FREE(frame);
481 return EINVAL;
484 if (uac_flags & ~UF_ACCOUNT_TYPE_MASK) {
486 * catch callers which still
487 * pass 'true'.
489 TALLOC_FREE(frame);
490 return EINVAL;
492 if (uac_flags == 0) {
494 * catch callers which still
495 * pass 'false'.
497 TALLOC_FREE(frame);
498 return EINVAL;
501 upper_realm = strupper_talloc(frame, realm);
502 if (upper_realm == NULL) {
503 TALLOC_FREE(frame);
504 return ENOMEM;
507 /* Many, many thanks to lukeh@padl.com for this
508 * algorithm, described in his Nov 10 2004 mail to
509 * samba-technical@lists.samba.org */
512 * Determine a salting principal
514 if (uac_flags & UF_TRUST_ACCOUNT_MASK) {
515 int computer_len = 0;
517 computer_len = strlen(sAMAccountName);
518 if (sAMAccountName[computer_len-1] == '$') {
519 computer_len -= 1;
522 if (uac_flags & UF_INTERDOMAIN_TRUST_ACCOUNT) {
523 const char *krbtgt = "krbtgt";
524 krb5_ret = krb5_build_principal_ext(krb5_ctx,
525 salt_princ,
526 strlen(upper_realm),
527 upper_realm,
528 strlen(krbtgt),
529 krbtgt,
530 computer_len,
531 sAMAccountName,
533 if (krb5_ret != 0) {
534 TALLOC_FREE(frame);
535 return krb5_ret;
537 } else {
538 const char *host = "host";
539 char *tmp = NULL;
540 char *tmp_lower = NULL;
542 tmp = talloc_asprintf(frame, "%*.*s.%s",
543 computer_len,
544 computer_len,
545 sAMAccountName,
546 realm);
547 if (tmp == NULL) {
548 TALLOC_FREE(frame);
549 return ENOMEM;
552 tmp_lower = strlower_talloc(frame, tmp);
553 if (tmp_lower == NULL) {
554 TALLOC_FREE(frame);
555 return ENOMEM;
558 krb5_ret = krb5_build_principal_ext(krb5_ctx,
559 salt_princ,
560 strlen(upper_realm),
561 upper_realm,
562 strlen(host),
563 host,
564 strlen(tmp_lower),
565 tmp_lower,
567 if (krb5_ret != 0) {
568 TALLOC_FREE(frame);
569 return krb5_ret;
573 } else if (userPrincipalName != NULL) {
575 * We parse the name not only to allow an easy
576 * replacement of the realm (no matter the realm in
577 * the UPN, the salt comes from the upper-case real
578 * realm, but also to correctly provide a salt when
579 * the UPN is host/foo.bar
581 * This can fail for a UPN of the form foo@bar@REALM
582 * (which is accepted by windows) however.
584 krb5_ret = krb5_parse_name(krb5_ctx,
585 userPrincipalName,
586 salt_princ);
588 if (krb5_ret != 0) {
589 TALLOC_FREE(frame);
590 return krb5_ret;
594 * No matter what realm (including none) in the UPN,
595 * the realm is replaced with our upper-case realm
597 krb5_ret = smb_krb5_principal_set_realm(krb5_ctx,
598 *salt_princ,
599 upper_realm);
600 if (krb5_ret != 0) {
601 krb5_free_principal(krb5_ctx, *salt_princ);
602 TALLOC_FREE(frame);
603 return krb5_ret;
605 } else {
606 principal = sAMAccountName;
607 principal_len = strlen(principal);
609 krb5_ret = krb5_build_principal_ext(krb5_ctx,
610 salt_princ,
611 strlen(upper_realm),
612 upper_realm,
613 principal_len,
614 principal,
616 if (krb5_ret != 0) {
617 TALLOC_FREE(frame);
618 return krb5_ret;
622 TALLOC_FREE(frame);
623 return 0;
627 * @brief This constructs the salt principal used by active directory
629 * Most Kerberos encryption types require a salt in order to
630 * calculate the long term private key for user/computer object
631 * based on a password.
633 * The returned _salt_principal is a string in forms like this:
634 * - host/somehost.example.com@EXAMPLE.COM
635 * - SomeAccount@EXAMPLE.COM
636 * - SomePrincipal@EXAMPLE.COM
638 * This is not the form that's used as salt, it's just
639 * the human readable form. It needs to be converted by
640 * smb_krb5_salt_principal2data().
642 * @param[in] realm The realm the user/computer is added too.
644 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
646 * @param[in] userPrincipalName The userPrincipalName attribute of the object
647 * or NULL is not available.
649 * @param[in] uac_flags UF_ACCOUNT_TYPE_MASKed userAccountControl field
651 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
653 * @param[out] _salt_principal The resulting principal as string.
655 * @retval 0 Success; otherwise - Kerberos error codes
657 * @see smb_krb5_salt_principal2data
659 int smb_krb5_salt_principal_str(const char *realm,
660 const char *sAMAccountName,
661 const char *userPrincipalName,
662 uint32_t uac_flags,
663 TALLOC_CTX *mem_ctx,
664 char **_salt_principal_str)
666 krb5_principal salt_principal = NULL;
667 char *salt_principal_malloc;
668 krb5_context krb5_ctx;
669 krb5_error_code krb5_ret
670 = smb_krb5_init_context_common(&krb5_ctx);
671 if (krb5_ret != 0) {
672 DBG_ERR("kerberos init context failed (%s)\n",
673 error_message(krb5_ret));
674 return krb5_ret;
677 krb5_ret = smb_krb5_salt_principal(krb5_ctx,
678 realm,
679 sAMAccountName,
680 userPrincipalName,
681 uac_flags,
682 &salt_principal);
683 if (krb5_ret != 0) {
684 DBG_ERR("unable to create salt principal:%s\n",
685 error_message(krb5_ret));
686 return krb5_ret;
689 krb5_ret = krb5_unparse_name(krb5_ctx, salt_principal,
690 &salt_principal_malloc);
691 if (krb5_ret != 0) {
692 krb5_free_principal(krb5_ctx, salt_principal);
693 DBG_ERR("kerberos unparse of salt principal failed (%s)\n",
694 error_message(krb5_ret));
695 return krb5_ret;
697 krb5_free_principal(krb5_ctx, salt_principal);
698 *_salt_principal_str
699 = talloc_strdup(mem_ctx, salt_principal_malloc);
700 krb5_free_unparsed_name(krb5_ctx, salt_principal_malloc);
702 if (*_salt_principal_str == NULL) {
703 return ENOMEM;
705 return 0;
709 * @brief Converts the salt principal string into the salt data blob
711 * This function takes a salt_principal as string in forms like this:
712 * - host/somehost.example.com@EXAMPLE.COM
713 * - SomeAccount@EXAMPLE.COM
714 * - SomePrincipal@EXAMPLE.COM
716 * It generates values like:
717 * - EXAMPLE.COMhost/somehost.example.com
718 * - EXAMPLE.COMSomeAccount
719 * - EXAMPLE.COMSomePrincipal
721 * @param[in] realm The realm the user/computer is added too.
723 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
725 * @param[in] userPrincipalName The userPrincipalName attribute of the object
726 * or NULL is not available.
728 * @param[in] is_computer The indication of the object includes
729 * objectClass=computer.
731 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
733 * @param[out] _salt_principal The resulting principal as string.
735 * @retval 0 Success; otherwise - Kerberos error codes
737 * @see smb_krb5_salt_principal
739 int smb_krb5_salt_principal2data(krb5_context context,
740 const char *salt_principal,
741 TALLOC_CTX *mem_ctx,
742 char **_salt_data)
744 krb5_error_code ret;
745 krb5_principal salt_princ = NULL;
746 krb5_data salt;
748 *_salt_data = NULL;
750 ret = krb5_parse_name(context, salt_principal, &salt_princ);
751 if (ret != 0) {
752 return ret;
755 ret = smb_krb5_get_pw_salt(context, salt_princ, &salt);
756 krb5_free_principal(context, salt_princ);
757 if (ret != 0) {
758 return ret;
761 *_salt_data = talloc_strndup(mem_ctx,
762 (char *)salt.data,
763 salt.length);
764 smb_krb5_free_data_contents(context, &salt);
765 if (*_salt_data == NULL) {
766 return ENOMEM;
769 return 0;
772 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
774 * @brief Get a list of encryption types allowed for session keys
776 * @param[in] context The library context
778 * @param[in] enctypes An allocated, zero-terminated list of encryption types
780 * This function returns an allocated list of encryption types allowed for
781 * session keys.
783 * Use free() to free the enctypes when it is no longer needed.
785 * @retval 0 Success; otherwise - Kerberos error codes
787 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
788 krb5_enctype **enctypes)
790 return krb5_get_permitted_enctypes(context, enctypes);
792 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
793 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
794 krb5_enctype **enctypes)
796 #ifdef HAVE_KRB5_PDU_NONE_DECL
797 return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, enctypes);
798 #else
799 return krb5_get_default_in_tkt_etypes(context, enctypes);
800 #endif
802 #else
803 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
804 #endif
808 * @brief Convert a string principal name to a Kerberos principal.
810 * @param[in] context The library context
812 * @param[in] name The principal as a unix charset string.
814 * @param[out] principal The newly allocated principal.
816 * Use krb5_free_principal() to free a principal when it is no longer needed.
818 * @return 0 on success, a Kerberos error code otherwise.
820 krb5_error_code smb_krb5_parse_name(krb5_context context,
821 const char *name,
822 krb5_principal *principal)
824 krb5_error_code ret;
825 char *utf8_name;
826 size_t converted_size;
827 TALLOC_CTX *frame = talloc_stackframe();
829 if (!push_utf8_talloc(frame, &utf8_name, name, &converted_size)) {
830 talloc_free(frame);
831 return ENOMEM;
834 ret = krb5_parse_name(context, utf8_name, principal);
835 if (ret == KRB5_PARSE_MALFORMED) {
836 ret = krb5_parse_name_flags(context, utf8_name,
837 KRB5_PRINCIPAL_PARSE_ENTERPRISE,
838 principal);
840 TALLOC_FREE(frame);
841 return ret;
845 * @brief Convert a Kerberos principal structure to a string representation.
847 * The resulting string representation will be a unix charset name and is
848 * talloc'ed.
850 * @param[in] mem_ctx The talloc context to allocate memory on.
852 * @param[in] context The library context.
854 * @param[in] principal The principal.
856 * @param[out] unix_name A string representation of the princpial name as with
857 * unix charset.
859 * Use talloc_free() to free the string representation if it is no longer
860 * needed.
862 * @return 0 on success, a Kerberos error code otherwise.
864 krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
865 krb5_context context,
866 krb5_const_principal principal,
867 char **unix_name)
869 krb5_error_code ret;
870 char *utf8_name;
871 size_t converted_size;
873 *unix_name = NULL;
874 ret = krb5_unparse_name(context, principal, &utf8_name);
875 if (ret) {
876 return ret;
879 if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
880 krb5_free_unparsed_name(context, utf8_name);
881 return ENOMEM;
883 krb5_free_unparsed_name(context, utf8_name);
884 return 0;
888 * @brief Free the contents of a krb5_data structure and zero the data field.
890 * @param[in] context The krb5 context
892 * @param[in] pdata The data structure to free contents of
894 * This function frees the contents, not the structure itself.
896 void smb_krb5_free_data_contents(krb5_context context, krb5_data *pdata)
898 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
899 if (pdata->data) {
900 krb5_free_data_contents(context, pdata);
902 #elif defined(HAVE_KRB5_DATA_FREE)
903 krb5_data_free(context, pdata);
904 #else
905 SAFE_FREE(pdata->data);
906 #endif
910 * @brief copy a buffer into a krb5_data struct
912 * @param[in] p The krb5_data
913 * @param[in] data The data to copy
914 * @param[in] length The length of the data to copy
915 * @return krb5_error_code
917 * Caller has to free krb5_data with smb_krb5_free_data_contents().
919 krb5_error_code smb_krb5_copy_data_contents(krb5_data *p,
920 const void *data,
921 size_t len)
923 #if defined(HAVE_KRB5_DATA_COPY)
924 return krb5_data_copy(p, data, len);
925 #else
926 if (len) {
927 p->data = malloc(len);
928 if (p->data == NULL) {
929 return ENOMEM;
931 memmove(p->data, data, len);
932 } else {
933 p->data = NULL;
935 p->length = len;
936 p->magic = KV5M_DATA;
937 return 0;
938 #endif
942 * @brief put a buffer reference into a krb5_data struct
944 * @param[in] data The data to reference
945 * @param[in] length The length of the data to reference
946 * @return krb5_data
948 * Caller should not free krb5_data.
950 krb5_data smb_krb5_make_data(void *data,
951 size_t len)
953 krb5_data d;
955 #ifdef SAMBA4_USES_HEIMDAL
956 d.data = (uint8_t *)data;
957 d.length = len;
958 #else
959 d.magic = KV5M_DATA;
960 d.data = data;
961 d.length = len;
962 #endif
963 return d;
966 krb5_data smb_krb5_data_from_blob(DATA_BLOB blob)
968 return smb_krb5_make_data(blob.data, blob.length);
971 bool smb_krb5_get_smb_session_key(TALLOC_CTX *mem_ctx,
972 krb5_context context,
973 krb5_auth_context auth_context,
974 DATA_BLOB *session_key,
975 bool remote)
977 krb5_keyblock *skey = NULL;
978 krb5_error_code err = 0;
979 bool ret = false;
981 if (remote) {
982 #ifdef HAVE_KRB5_AUTH_CON_GETRECVSUBKEY
983 err = krb5_auth_con_getrecvsubkey(context,
984 auth_context,
985 &skey);
986 #else /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
987 err = krb5_auth_con_getremotesubkey(context,
988 auth_context, &skey);
989 #endif /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
990 } else {
991 #ifdef HAVE_KRB5_AUTH_CON_GETSENDSUBKEY
992 err = krb5_auth_con_getsendsubkey(context,
993 auth_context,
994 &skey);
995 #else /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
996 err = krb5_auth_con_getlocalsubkey(context,
997 auth_context, &skey);
998 #endif /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
1001 if (err || skey == NULL) {
1002 DEBUG(10, ("KRB5 error getting session key %d\n", err));
1003 goto done;
1006 DEBUG(10, ("Got KRB5 session key of length %d\n",
1007 (int)KRB5_KEY_LENGTH(skey)));
1009 *session_key = data_blob_talloc(mem_ctx,
1010 KRB5_KEY_DATA(skey),
1011 KRB5_KEY_LENGTH(skey));
1012 dump_data_pw("KRB5 Session Key:\n",
1013 session_key->data,
1014 session_key->length);
1016 ret = true;
1018 done:
1019 if (skey) {
1020 krb5_free_keyblock(context, skey);
1023 return ret;
1028 * @brief Get talloced string component of a principal
1030 * @param[in] mem_ctx The TALLOC_CTX
1031 * @param[in] context The krb5_context
1032 * @param[in] principal The principal
1033 * @param[in] component The component
1034 * @return string component
1036 * Caller must talloc_free if the return value is not NULL.
1039 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
1040 krb5_context context,
1041 krb5_const_principal principal,
1042 unsigned int component)
1044 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
1045 return talloc_strdup(mem_ctx, krb5_principal_get_comp_string(context, principal, component));
1046 #else
1047 krb5_data *data;
1049 if (component >= krb5_princ_size(context, principal)) {
1050 return NULL;
1053 data = krb5_princ_component(context, principal, component);
1054 if (data == NULL) {
1055 return NULL;
1058 return talloc_strndup(mem_ctx, data->data, data->length);
1059 #endif
1063 * @brief
1065 * @param[in] ccache_string A string pointing to the cache to renew the ticket
1066 * (e.g. FILE:/tmp/krb5cc_0) or NULL. If the principal
1067 * ccache has not been specified, the default ccache
1068 * will be used.
1070 * @param[in] client_string The client principal string (e.g. user@SAMBA.SITE)
1071 * or NULL. If the principal string has not been
1072 * specified, the principal from the ccache will be
1073 * retrieved.
1075 * @param[in] service_string The service ticket string
1076 * (e.g. krbtgt/SAMBA.SITE@SAMBA.SITE) or NULL. If
1077 * the service ticket is specified, it is parsed
1078 * (with the realm part ignored) and used as the
1079 * server principal of the credential. Otherwise
1080 * the ticket-granting service is used.
1082 * @param[in] expire_time A pointer to store the credentials end time or
1083 * NULL.
1085 * @return 0 on Success, a Kerberos error code otherwise.
1087 krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,
1088 const char *client_string,
1089 const char *service_string,
1090 time_t *expire_time)
1092 krb5_error_code ret;
1093 krb5_context context = NULL;
1094 krb5_ccache ccache = NULL;
1095 krb5_principal client = NULL;
1096 krb5_creds creds, creds_in;
1098 ZERO_STRUCT(creds);
1099 ZERO_STRUCT(creds_in);
1101 ret = smb_krb5_init_context_common(&context);
1102 if (ret) {
1103 DBG_ERR("kerberos init context failed (%s)\n",
1104 error_message(ret));
1105 goto done;
1108 if (!ccache_string) {
1109 ccache_string = krb5_cc_default_name(context);
1112 if (!ccache_string) {
1113 ret = EINVAL;
1114 goto done;
1117 DBG_DEBUG("Using %s as ccache for client '%s' and service '%s'\n",
1118 ccache_string, client_string, service_string);
1120 /* FIXME: we should not fall back to defaults */
1121 ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
1122 if (ret) {
1123 goto done;
1126 if (client_string) {
1127 ret = smb_krb5_parse_name(context, client_string, &client);
1128 if (ret) {
1129 goto done;
1131 } else {
1132 ret = krb5_cc_get_principal(context, ccache, &client);
1133 if (ret) {
1134 goto done;
1138 ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
1139 if (ret) {
1140 DBG_DEBUG("krb5_get_renewed_creds using ccache '%s' "
1141 "for client '%s' and service '%s' failed: %s\n",
1142 ccache_string, client_string, service_string,
1143 error_message(ret));
1144 goto done;
1147 /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
1148 ret = krb5_cc_initialize(context, ccache, client);
1149 if (ret) {
1150 goto done;
1153 ret = krb5_cc_store_cred(context, ccache, &creds);
1155 if (expire_time) {
1156 *expire_time = (time_t) creds.times.endtime;
1159 done:
1160 krb5_free_cred_contents(context, &creds_in);
1161 krb5_free_cred_contents(context, &creds);
1163 if (client) {
1164 krb5_free_principal(context, client);
1166 if (ccache) {
1167 krb5_cc_close(context, ccache);
1169 if (context) {
1170 krb5_free_context(context);
1173 return ret;
1177 * @brief Free the data stored in an smb_krb5_addresses structure.
1179 * @param[in] context The library context
1181 * @param[in] addr The address structure to free.
1183 * @return 0 on success, a Kerberos error code otherwise.
1185 krb5_error_code smb_krb5_free_addresses(krb5_context context,
1186 smb_krb5_addresses *addr)
1188 krb5_error_code ret = 0;
1189 if (addr == NULL) {
1190 return ret;
1192 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1193 krb5_free_addresses(context, addr->addrs);
1194 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1195 ret = krb5_free_addresses(context, addr->addrs);
1196 SAFE_FREE(addr->addrs);
1197 #endif
1198 SAFE_FREE(addr);
1199 addr = NULL;
1200 return ret;
1203 #define MAX_NETBIOSNAME_LEN 16
1206 * @brief Add a netbios name to the array of addresses
1208 * @param[in] kerb_addr A pointer to the smb_krb5_addresses to add the
1209 * netbios name to.
1211 * @param[in] netbios_name The netbios name to add.
1213 * @return 0 on success, a Kerberos error code otherwise.
1215 krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
1216 const char *netbios_name)
1218 krb5_error_code ret = 0;
1219 char buf[MAX_NETBIOSNAME_LEN];
1220 int len;
1221 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1222 krb5_address **addrs = NULL;
1223 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1224 krb5_addresses *addrs = NULL;
1225 #endif
1227 *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1228 if (*kerb_addr == NULL) {
1229 return ENOMEM;
1232 /* temporarily duplicate put_name() code here to avoid dependency
1233 * issues for a 5 lines function */
1234 len = strlen(netbios_name);
1235 memcpy(buf, netbios_name,
1236 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
1237 if (len < MAX_NETBIOSNAME_LEN - 1) {
1238 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
1240 buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
1242 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1244 int num_addr = 2;
1246 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1247 if (addrs == NULL) {
1248 SAFE_FREE(*kerb_addr);
1249 return ENOMEM;
1252 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1254 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1255 if (addrs[0] == NULL) {
1256 SAFE_FREE(addrs);
1257 SAFE_FREE(*kerb_addr);
1258 return ENOMEM;
1261 addrs[0]->magic = KV5M_ADDRESS;
1262 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1263 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1264 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1265 if (addrs[0]->contents == NULL) {
1266 SAFE_FREE(addrs[0]);
1267 SAFE_FREE(addrs);
1268 SAFE_FREE(*kerb_addr);
1269 return ENOMEM;
1272 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1274 addrs[1] = NULL;
1276 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1278 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1279 if (addrs == NULL) {
1280 SAFE_FREE(*kerb_addr);
1281 return ENOMEM;
1284 memset(addrs, 0, sizeof(krb5_addresses));
1286 addrs->len = 1;
1287 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1288 if (addrs->val == NULL) {
1289 SAFE_FREE(addrs);
1290 SAFE_FREE(*kerb_addr);
1291 return ENOMEM;
1294 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1295 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1296 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1297 if (addrs->val[0].address.data == NULL) {
1298 SAFE_FREE(addrs->val);
1299 SAFE_FREE(addrs);
1300 SAFE_FREE(*kerb_addr);
1301 return ENOMEM;
1304 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1306 #else
1307 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1308 #endif
1309 (*kerb_addr)->addrs = addrs;
1311 return ret;
1315 * @brief Get the enctype from a key table entry
1317 * @param[in] kt_entry Key table entry to get the enctype from.
1319 * @return The enctype from the entry.
1321 krb5_enctype smb_krb5_kt_get_enctype_from_entry(krb5_keytab_entry *kt_entry)
1323 return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1327 * @brief Free the contents of a key table entry.
1329 * @param[in] context The library context.
1331 * @param[in] kt_entry The key table entry to free the contents of.
1333 * @return 0 on success, a Kerberos error code otherwise.
1335 * The pointer itself is not freed.
1337 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1338 krb5_keytab_entry *kt_entry)
1340 /* Try krb5_free_keytab_entry_contents first, since
1341 * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1342 * krb5_kt_free_entry but only has a prototype for the first, while the
1343 * second is considered private.
1345 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1346 return krb5_free_keytab_entry_contents(context, kt_entry);
1347 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1348 return krb5_kt_free_entry(context, kt_entry);
1349 #else
1350 #error UNKNOWN_KT_FREE_FUNCTION
1351 #endif
1356 * @brief Convert an encryption type to a string.
1358 * @param[in] context The library context.
1360 * @param[in] enctype The encryption type.
1362 * @param[in] etype_s A pointer to store the allocated encryption type as a
1363 * string.
1365 * @return 0 on success, a Kerberos error code otherwise.
1367 * The caller needs to free the allocated string etype_s.
1369 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1370 krb5_enctype enctype,
1371 char **etype_s)
1373 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1374 return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1375 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1376 char buf[256];
1377 krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1378 if (ret) {
1379 return ret;
1381 *etype_s = SMB_STRDUP(buf);
1382 if (!*etype_s) {
1383 return ENOMEM;
1385 return ret;
1386 #else
1387 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1388 #endif
1391 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1392 #ifndef MAX_KEYTAB_NAME_LEN
1393 #define MAX_KEYTAB_NAME_LEN 1100
1394 #endif
1397 * @brief Open a key table readonly or with readwrite access.
1399 * Allows one to use a different keytab than the default one using a relative
1400 * path to the keytab.
1402 * @param[in] context The library context
1404 * @param[in] keytab_name_req The path to the key table.
1406 * @param[in] write_access Open with readwrite access.
1408 * @param[in] keytab A pointer to the opened key table.
1410 * The keytab pointer should be freed using krb5_kt_close().
1412 * @return 0 on success, a Kerberos error code otherwise.
1414 krb5_error_code smb_krb5_kt_open_relative(krb5_context context,
1415 const char *keytab_name_req,
1416 bool write_access,
1417 krb5_keytab *keytab)
1419 krb5_error_code ret = 0;
1420 TALLOC_CTX *mem_ctx;
1421 char keytab_string[MAX_KEYTAB_NAME_LEN];
1422 char *kt_str = NULL;
1423 bool found_valid_name = false;
1424 const char *pragma = "FILE";
1425 const char *tmp = NULL;
1427 if (!write_access && !keytab_name_req) {
1428 /* caller just wants to read the default keytab readonly, so be it */
1429 return krb5_kt_default(context, keytab);
1432 mem_ctx = talloc_init("smb_krb5_open_keytab");
1433 if (!mem_ctx) {
1434 return ENOMEM;
1437 #ifdef HAVE_WRFILE_KEYTAB
1438 if (write_access) {
1439 pragma = "WRFILE";
1441 #endif
1443 if (keytab_name_req) {
1445 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1446 ret = KRB5_CONFIG_NOTENUFSPACE;
1447 goto out;
1450 if ((strncmp(keytab_name_req, "WRFILE:", 7) == 0) ||
1451 (strncmp(keytab_name_req, "FILE:", 5) == 0)) {
1452 tmp = keytab_name_req;
1453 goto resolve;
1456 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1457 if (!tmp) {
1458 ret = ENOMEM;
1459 goto out;
1462 goto resolve;
1465 /* we need to handle more complex keytab_strings, like:
1466 * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1468 ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1469 if (ret) {
1470 goto out;
1473 DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1475 tmp = talloc_strdup(mem_ctx, keytab_string);
1476 if (!tmp) {
1477 ret = ENOMEM;
1478 goto out;
1481 if (strncmp(tmp, "ANY:", 4) == 0) {
1482 tmp += 4;
1485 memset(&keytab_string, '\0', sizeof(keytab_string));
1487 while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1488 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1489 found_valid_name = true;
1490 tmp = kt_str;
1491 tmp += 7;
1494 if (strncmp(kt_str, "FILE:", 5) == 0) {
1495 found_valid_name = true;
1496 tmp = kt_str;
1497 tmp += 5;
1500 if (tmp[0] == '/') {
1501 /* Treat as a FILE: keytab definition. */
1502 found_valid_name = true;
1505 if (found_valid_name) {
1506 if (tmp[0] != '/') {
1507 ret = KRB5_KT_BADNAME;
1508 goto out;
1511 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1512 if (!tmp) {
1513 ret = ENOMEM;
1514 goto out;
1516 break;
1520 if (!found_valid_name) {
1521 ret = KRB5_KT_UNKNOWN_TYPE;
1522 goto out;
1525 resolve:
1526 DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1527 ret = krb5_kt_resolve(context, tmp, keytab);
1529 out:
1530 TALLOC_FREE(mem_ctx);
1531 return ret;
1535 * @brief Open a key table readonly or with readwrite access.
1537 * Allows one to use a different keytab than the default one. The path needs to be
1538 * an absolute path or an error will be returned.
1540 * @param[in] context The library context
1542 * @param[in] keytab_name_req The path to the key table.
1544 * @param[in] write_access Open with readwrite access.
1546 * @param[in] keytab A pointer to the opened key table.
1548 * The keytab pointer should be freed using krb5_kt_close().
1550 * @return 0 on success, a Kerberos error code otherwise.
1552 krb5_error_code smb_krb5_kt_open(krb5_context context,
1553 const char *keytab_name_req,
1554 bool write_access,
1555 krb5_keytab *keytab)
1557 int cmp;
1559 if (keytab_name_req == NULL) {
1560 return KRB5_KT_BADNAME;
1563 if (keytab_name_req[0] == '/') {
1564 goto open_keytab;
1567 cmp = strncmp(keytab_name_req, "FILE:/", 6);
1568 if (cmp == 0) {
1569 goto open_keytab;
1572 cmp = strncmp(keytab_name_req, "WRFILE:/", 8);
1573 if (cmp == 0) {
1574 goto open_keytab;
1577 DBG_WARNING("ERROR: Invalid keytab name: %s\n", keytab_name_req);
1579 return KRB5_KT_BADNAME;
1581 open_keytab:
1582 return smb_krb5_kt_open_relative(context,
1583 keytab_name_req,
1584 write_access,
1585 keytab);
1589 * @brief Get a key table name.
1591 * @param[in] mem_ctx The talloc context to use for allocation.
1593 * @param[in] context The library context.
1595 * @param[in] keytab The key table to get the name from.
1597 * @param[in] keytab_name A talloc'ed string of the key table name.
1599 * The talloc'ed name string needs to be freed with talloc_free().
1601 * @return 0 on success, a Kerberos error code otherwise.
1603 krb5_error_code smb_krb5_kt_get_name(TALLOC_CTX *mem_ctx,
1604 krb5_context context,
1605 krb5_keytab keytab,
1606 const char **keytab_name)
1608 char keytab_string[MAX_KEYTAB_NAME_LEN];
1609 krb5_error_code ret = 0;
1611 ret = krb5_kt_get_name(context, keytab,
1612 keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1613 if (ret) {
1614 return ret;
1617 *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1618 if (!*keytab_name) {
1619 return ENOMEM;
1622 return ret;
1626 * @brief Seek and delete old entries in a keytab based on the passed
1627 * principal.
1629 * @param[in] context The KRB5 context to use.
1631 * @param[in] keytab The keytab to operate on.
1633 * @param[in] keep_old_kvno Keep the entries with the previous kvno.
1635 * @param[in] kvno The kvnco to use.
1637 * @param[in] enctype_only Only evaluate the enctype argument if true
1639 * @param[in] enctype Only search for entries with the specified enctype
1641 * @param[in] princ_s The principal as a string to search for.
1643 * @param[in] princ The principal as a krb5_principal to search for.
1645 * @param[in] flush Whether to flush the complete keytab.
1647 * @retval 0 on Success
1649 * @return An appropriate KRB5 error code.
1651 krb5_error_code smb_krb5_kt_seek_and_delete_old_entries(krb5_context context,
1652 krb5_keytab keytab,
1653 bool keep_old_kvno,
1654 krb5_kvno kvno,
1655 bool enctype_only,
1656 krb5_enctype enctype,
1657 const char *princ_s,
1658 krb5_principal princ,
1659 bool flush)
1661 krb5_error_code ret;
1662 krb5_kt_cursor cursor;
1663 krb5_keytab_entry kt_entry;
1664 char *ktprinc = NULL;
1665 krb5_kvno old_kvno = kvno - 1;
1666 TALLOC_CTX *tmp_ctx;
1668 if (flush) {
1669 SMB_ASSERT(!keep_old_kvno);
1670 SMB_ASSERT(!enctype_only);
1671 SMB_ASSERT(princ_s == NULL);
1672 SMB_ASSERT(princ == NULL);
1673 } else {
1674 SMB_ASSERT(princ_s != NULL);
1675 SMB_ASSERT(princ != NULL);
1678 ZERO_STRUCT(cursor);
1679 ZERO_STRUCT(kt_entry);
1681 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1682 if (ret == KRB5_KT_END || ret == ENOENT ) {
1683 /* no entries */
1684 return 0;
1687 tmp_ctx = talloc_new(NULL);
1688 if (tmp_ctx == NULL) {
1689 return ENOMEM;
1692 DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1693 while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1694 bool name_ok = false;
1695 krb5_enctype kt_entry_enctype =
1696 smb_krb5_kt_get_enctype_from_entry(&kt_entry);
1698 if (princ_s != NULL) {
1699 ret = smb_krb5_unparse_name(tmp_ctx, context,
1700 kt_entry.principal,
1701 &ktprinc);
1702 if (ret) {
1703 DEBUG(1, (__location__
1704 ": smb_krb5_unparse_name failed "
1705 "(%s)\n", error_message(ret)));
1706 goto out;
1709 #ifdef HAVE_KRB5_KT_COMPARE
1710 name_ok = krb5_kt_compare(context, &kt_entry,
1711 princ, 0, 0);
1712 #else
1713 name_ok = (strcmp(ktprinc, princ_s) == 0);
1714 #endif
1716 if (!name_ok) {
1717 DEBUG(10, (__location__ ": ignoring keytab "
1718 "entry principal %s, kvno = %d\n",
1719 ktprinc, kt_entry.vno));
1721 /* Not a match,
1722 * just free this entry and continue. */
1723 ret = smb_krb5_kt_free_entry(context,
1724 &kt_entry);
1725 ZERO_STRUCT(kt_entry);
1726 if (ret) {
1727 DEBUG(1, (__location__
1728 ": smb_krb5_kt_free_entry "
1729 "failed (%s)\n",
1730 error_message(ret)));
1731 goto out;
1734 TALLOC_FREE(ktprinc);
1735 continue;
1738 TALLOC_FREE(ktprinc);
1741 /*------------------------------------------------------------
1742 * Save the entries with kvno - 1. This is what microsoft does
1743 * to allow people with existing sessions that have kvno - 1
1744 * to still work. Otherwise, when the password for the machine
1745 * changes, all kerberizied sessions will 'break' until either
1746 * the client reboots or the client's session key expires and
1747 * they get a new session ticket with the new kvno.
1748 * Some keytab files only store the kvno in 8bits, limit
1749 * the compare accordingly.
1752 if (keep_old_kvno && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1753 DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1754 "entry for principal: %s.\n",
1755 old_kvno,
1756 princ_s != NULL ? princ_s : "UNKNOWN"));
1757 continue;
1760 if (enctype_only &&
1761 ((kt_entry.vno & 0xff) == (kvno & 0xff)) &&
1762 (kt_entry_enctype != enctype))
1764 DEBUG(5, (__location__ ": Saving entry with kvno [%d] "
1765 "enctype [%d] for principal: %s.\n",
1766 kvno, kt_entry_enctype,
1767 princ_s != NULL ? princ_s : "UNKNOWN"));
1768 continue;
1771 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1772 "(kvno %d) - trying to remove it.\n",
1773 princ_s != NULL ? princ_s : "UNKNOWN",
1774 kt_entry.vno));
1776 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1777 ZERO_STRUCT(cursor);
1778 if (ret) {
1779 DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1780 "failed (%s)\n", error_message(ret)));
1781 goto out;
1783 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1784 if (ret) {
1785 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1786 "failed (%s)\n", error_message(ret)));
1787 goto out;
1790 DEBUG(5, (__location__ ": removed old entry for principal: "
1791 "%s (kvno %d).\n",
1792 princ_s != NULL ? princ_s : "UNKNOWN",
1793 kt_entry.vno));
1795 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1796 if (ret) {
1797 DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1798 "(%s)\n", error_message(ret)));
1799 goto out;
1801 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1802 ZERO_STRUCT(kt_entry);
1803 if (ret) {
1804 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1805 "failed (%s)\n", error_message(ret)));
1806 goto out;
1810 out:
1811 talloc_free(tmp_ctx);
1812 if (!all_zero((uint8_t *)&kt_entry, sizeof(kt_entry))) {
1813 smb_krb5_kt_free_entry(context, &kt_entry);
1815 if (!all_zero((uint8_t *)&cursor, sizeof(cursor))) {
1816 krb5_kt_end_seq_get(context, keytab, &cursor);
1818 return ret;
1822 * @brief Add a keytab entry for the given principal
1824 * @param[in] context The krb5 context to use.
1826 * @param[in] keytab The keytab to add the entry to.
1828 * @param[in] kvno The kvno to use.
1830 * @param[in] princ_s The principal as a string.
1832 * @param[in] salt_principal The salt principal to salt the password with.
1833 * Only needed for keys which support salting.
1834 * If no salt is used set no_salt to false and
1835 * pass NULL here.
1837 * @param[in] enctype The encryption type of the keytab entry.
1839 * @param[in] password The password of the keytab entry.
1841 * @param[in] no_salt If the password should not be salted. Normally
1842 * this is only set to false for encryption types
1843 * which do not support salting like RC4.
1845 * @retval 0 on Success
1847 * @return A corresponding KRB5 error code.
1849 * @see smb_krb5_kt_open()
1851 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1852 krb5_keytab keytab,
1853 krb5_kvno kvno,
1854 const char *princ_s,
1855 const char *salt_principal,
1856 krb5_enctype enctype,
1857 krb5_data *password,
1858 bool no_salt)
1860 krb5_error_code ret;
1861 krb5_keytab_entry kt_entry;
1862 krb5_principal princ = NULL;
1863 krb5_keyblock *keyp;
1865 ZERO_STRUCT(kt_entry);
1867 ret = smb_krb5_parse_name(context, princ_s, &princ);
1868 if (ret) {
1869 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1870 "failed (%s)\n", princ_s, error_message(ret)));
1871 goto out;
1874 /* Seek and delete old keytab entries */
1875 ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1876 keytab,
1877 true, /* keep_old_kvno */
1878 kvno,
1879 true, /* enctype_only */
1880 enctype,
1881 princ_s,
1882 princ,
1883 false); /* flush */
1884 if (ret) {
1885 goto out;
1888 /* If we get here, we have deleted all the old entries with kvno's
1889 * not equal to the current kvno-1. */
1891 keyp = KRB5_KT_KEY(&kt_entry);
1893 if (no_salt) {
1894 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1895 if (KRB5_KEY_DATA(keyp) == NULL) {
1896 ret = ENOMEM;
1897 goto out;
1899 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1900 KRB5_KEY_LENGTH(keyp) = password->length;
1901 KRB5_KEY_TYPE(keyp) = enctype;
1902 } else {
1903 krb5_principal salt_princ = NULL;
1905 /* Now add keytab entries for all encryption types */
1906 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1907 if (ret) {
1908 DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1909 salt_principal, error_message(ret));
1910 goto out;
1913 ret = smb_krb5_create_key_from_string(context,
1914 salt_princ,
1915 NULL,
1916 password,
1917 enctype,
1918 keyp);
1919 krb5_free_principal(context, salt_princ);
1920 if (ret != 0) {
1921 goto out;
1925 kt_entry.principal = princ;
1926 kt_entry.vno = kvno;
1928 DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1929 "encryption type (%d) and version (%d)\n",
1930 princ_s, enctype, kt_entry.vno));
1931 ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1932 krb5_free_keyblock_contents(context, keyp);
1933 ZERO_STRUCT(kt_entry);
1934 if (ret) {
1935 DEBUG(1, (__location__ ": adding entry to keytab "
1936 "failed (%s)\n", error_message(ret)));
1937 goto out;
1940 out:
1941 if (princ) {
1942 krb5_free_principal(context, princ);
1945 return ret;
1948 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1949 defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1950 defined(HAVE_KRB5_GET_CREDS)
1951 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1952 krb5_ccache ccache,
1953 krb5_principal me,
1954 krb5_principal server,
1955 krb5_principal impersonate_princ,
1956 krb5_creds **out_creds)
1958 krb5_error_code ret;
1959 krb5_get_creds_opt opt;
1961 ret = krb5_get_creds_opt_alloc(context, &opt);
1962 if (ret) {
1963 goto done;
1965 krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1967 if (impersonate_princ) {
1968 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1969 impersonate_princ);
1970 if (ret) {
1971 goto done;
1975 ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1976 if (ret) {
1977 goto done;
1980 done:
1981 if (opt) {
1982 krb5_get_creds_opt_free(context, opt);
1984 return ret;
1986 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1988 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1990 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1991 krb5_error_code KRB5_CALLCONV
1992 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1993 krb5_ccache ccache, krb5_creds *in_creds,
1994 krb5_data *subject_cert,
1995 krb5_creds **out_creds);
1996 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1998 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1999 krb5_ccache ccache,
2000 krb5_principal me,
2001 krb5_principal server,
2002 krb5_principal impersonate_princ,
2003 krb5_creds **out_creds)
2005 krb5_error_code ret;
2006 krb5_creds in_creds;
2008 ZERO_STRUCT(in_creds);
2010 if (impersonate_princ) {
2012 in_creds.server = me;
2013 in_creds.client = impersonate_princ;
2015 ret = krb5_get_credentials_for_user(context,
2016 0, /* krb5_flags options */
2017 ccache,
2018 &in_creds,
2019 NULL, /* krb5_data *subject_cert */
2020 out_creds);
2021 } else {
2022 in_creds.client = me;
2023 in_creds.server = server;
2025 ret = krb5_get_credentials(context, 0, ccache,
2026 &in_creds, out_creds);
2029 return ret;
2031 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
2034 * smb_krb5_get_credentials
2036 * @brief Get krb5 credentials for a server
2038 * @param[in] context An initialized krb5_context
2039 * @param[in] ccache An initialized krb5_ccache
2040 * @param[in] me The krb5_principal of the caller
2041 * @param[in] server The krb5_principal of the requested service
2042 * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
2043 * @param[out] out_creds The returned krb5_creds structure
2044 * @return krb5_error_code
2047 krb5_error_code smb_krb5_get_credentials(krb5_context context,
2048 krb5_ccache ccache,
2049 krb5_principal me,
2050 krb5_principal server,
2051 krb5_principal impersonate_princ,
2052 krb5_creds **out_creds)
2054 krb5_error_code ret;
2055 krb5_creds *creds = NULL;
2057 if (out_creds != NULL) {
2058 *out_creds = NULL;
2061 if (impersonate_princ) {
2062 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
2063 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
2064 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
2065 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
2066 #else
2067 ret = ENOTSUP;
2068 #endif
2069 } else {
2070 krb5_creds in_creds;
2072 ZERO_STRUCT(in_creds);
2074 in_creds.client = me;
2075 in_creds.server = server;
2077 ret = krb5_get_credentials(context, 0, ccache,
2078 &in_creds, &creds);
2080 if (ret) {
2081 goto done;
2084 if (out_creds) {
2085 *out_creds = creds;
2088 done:
2089 if (creds && ret) {
2090 krb5_free_creds(context, creds);
2093 return ret;
2097 * @brief Initialize a krb5_keyblock with the given data.
2099 * Initializes a new keyblock, allocates the contents for the key and
2100 * copies the data into the keyblock.
2102 * @param[in] context The library context
2104 * @param[in] enctype The encryption type.
2106 * @param[in] data The date to initialize the keyblock with.
2108 * @param[in] length The length of the keyblock.
2110 * @param[in] key Newly allocated keyblock structure.
2112 * The key date must be freed using krb5_free_keyblock_contents() when it is
2113 * no longer needed.
2115 * @return 0 on success, a Kerberos error code otherwise.
2117 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
2118 krb5_enctype enctype,
2119 const void *data,
2120 size_t length,
2121 krb5_keyblock *key)
2123 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
2124 return krb5_keyblock_init(context, enctype, data, length, key);
2125 #else
2126 memset(key, 0, sizeof(krb5_keyblock));
2127 KRB5_KEY_DATA(key) = SMB_MALLOC(length);
2128 if (NULL == KRB5_KEY_DATA(key)) {
2129 return ENOMEM;
2131 memcpy(KRB5_KEY_DATA(key), data, length);
2132 KRB5_KEY_LENGTH(key) = length;
2133 KRB5_KEY_TYPE(key) = enctype;
2134 return 0;
2135 #endif
2139 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2141 * This function uses a keyblock rather than needing the original password.
2143 * @param[in] ctx The library context
2145 * @param[in] cc The credential cache to put the tgt in.
2147 * @param[in] principal The client princial
2149 * @param[in] keyblock The keyblock to use.
2151 * @param[in] target_service The service name of the initial credentials (or NULL).
2153 * @param[in] krb_options Initial credential options.
2155 * @param[in] expire_time A pointer to store the expiration time of the
2156 * credentials (or NULL).
2158 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2159 * valid (or NULL).
2161 * @return 0 on success, a Kerberos error code otherwise.
2163 krb5_error_code smb_krb5_kinit_keyblock_ccache(krb5_context ctx,
2164 krb5_ccache cc,
2165 krb5_principal principal,
2166 krb5_keyblock *keyblock,
2167 const char *target_service,
2168 krb5_get_init_creds_opt *krb_options,
2169 time_t *expire_time,
2170 time_t *kdc_time)
2172 krb5_error_code code = 0;
2173 krb5_creds my_creds;
2175 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
2176 code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
2177 keyblock, 0, target_service,
2178 krb_options);
2179 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
2181 #define SMB_CREDS_KEYTAB "MEMORY:tmp_kinit_keyblock_ccache"
2182 char tmp_name[64] = {0};
2183 krb5_keytab_entry entry;
2184 krb5_keytab keytab;
2185 int rc;
2187 memset(&entry, 0, sizeof(entry));
2188 entry.principal = principal;
2189 *(KRB5_KT_KEY(&entry)) = *keyblock;
2191 rc = snprintf(tmp_name, sizeof(tmp_name),
2192 "%s-%p",
2193 SMB_CREDS_KEYTAB,
2194 &my_creds);
2195 if (rc < 0) {
2196 return KRB5_KT_BADNAME;
2198 code = krb5_kt_resolve(ctx, tmp_name, &keytab);
2199 if (code) {
2200 return code;
2203 code = krb5_kt_add_entry(ctx, keytab, &entry);
2204 if (code) {
2205 (void)krb5_kt_close(ctx, keytab);
2206 goto done;
2209 code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
2210 keytab, 0, target_service,
2211 krb_options);
2212 (void)krb5_kt_close(ctx, keytab);
2214 #else
2215 #error krb5_get_init_creds_keyblock not available!
2216 #endif
2217 if (code) {
2218 return code;
2221 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2223 * We need to store the principal as returned from the KDC to the
2224 * credentials cache. If we don't do that the KRB5 library is not
2225 * able to find the tickets it is looking for
2227 principal = my_creds.client;
2228 #endif
2229 code = krb5_cc_initialize(ctx, cc, principal);
2230 if (code) {
2231 goto done;
2234 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2235 if (code) {
2236 goto done;
2239 if (expire_time) {
2240 *expire_time = (time_t) my_creds.times.endtime;
2243 if (kdc_time) {
2244 *kdc_time = (time_t) my_creds.times.starttime;
2247 code = 0;
2248 done:
2249 krb5_free_cred_contents(ctx, &my_creds);
2250 return code;
2254 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2256 * @param[in] ctx The library context
2258 * @param[in] cc The credential cache to put the tgt in.
2260 * @param[in] principal The client princial
2262 * @param[in] password The password (or NULL).
2264 * @param[in] target_service The service name of the initial credentials (or NULL).
2266 * @param[in] krb_options Initial credential options.
2268 * @param[in] expire_time A pointer to store the expiration time of the
2269 * credentials (or NULL).
2271 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2272 * valid (or NULL).
2274 * @return 0 on success, a Kerberos error code otherwise.
2276 krb5_error_code smb_krb5_kinit_password_ccache(krb5_context ctx,
2277 krb5_ccache cc,
2278 krb5_principal principal,
2279 const char *password,
2280 const char *target_service,
2281 krb5_get_init_creds_opt *krb_options,
2282 time_t *expire_time,
2283 time_t *kdc_time)
2285 krb5_error_code code = 0;
2286 krb5_creds my_creds;
2288 code = krb5_get_init_creds_password(ctx, &my_creds, principal,
2289 password, NULL, NULL, 0,
2290 target_service, krb_options);
2291 if (code) {
2292 return code;
2296 * We need to store the principal as returned from the KDC to the
2297 * credentials cache. If we don't do that the KRB5 library is not
2298 * able to find the tickets it is looking for
2300 principal = my_creds.client;
2301 code = krb5_cc_initialize(ctx, cc, principal);
2302 if (code) {
2303 goto done;
2306 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2307 if (code) {
2308 goto done;
2311 if (expire_time) {
2312 *expire_time = (time_t) my_creds.times.endtime;
2315 if (kdc_time) {
2316 *kdc_time = (time_t) my_creds.times.starttime;
2319 code = 0;
2320 done:
2321 krb5_free_cred_contents(ctx, &my_creds);
2322 return code;
2325 #ifdef SAMBA4_USES_HEIMDAL
2327 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2329 * @param[in] ctx The library context
2331 * @param[in] cc The credential cache to store the tgt in.
2333 * @param[in] principal The initial client princial.
2335 * @param[in] password The password (or NULL).
2337 * @param[in] impersonate_principal The impersonatiion principal (or NULL).
2339 * @param[in] self_service The local service for S4U2Self if
2340 * impersonate_principal is specified).
2342 * @param[in] target_service The service name of the initial credentials
2343 * (kpasswd/REALM or a remote service). It defaults
2344 * to the krbtgt if NULL.
2346 * @param[in] krb_options Initial credential options.
2348 * @param[in] expire_time A pointer to store the expiration time of the
2349 * credentials (or NULL).
2351 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2352 * valid (or NULL).
2354 * @return 0 on success, a Kerberos error code otherwise.
2356 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
2357 krb5_ccache store_cc,
2358 krb5_principal init_principal,
2359 const char *init_password,
2360 krb5_principal impersonate_principal,
2361 const char *self_service,
2362 const char *target_service,
2363 krb5_get_init_creds_opt *krb_options,
2364 time_t *expire_time,
2365 time_t *kdc_time)
2367 krb5_error_code code = 0;
2368 krb5_get_creds_opt options;
2369 krb5_principal store_principal;
2370 krb5_creds store_creds;
2371 krb5_creds *s4u2self_creds;
2372 Ticket s4u2self_ticket;
2373 size_t s4u2self_ticketlen;
2374 krb5_creds *s4u2proxy_creds;
2375 krb5_principal self_princ;
2376 bool s4u2proxy;
2377 krb5_principal target_princ;
2378 krb5_ccache tmp_cc;
2379 const char *self_realm;
2380 const char *client_realm = NULL;
2381 krb5_principal blacklist_principal = NULL;
2382 krb5_principal whitelist_principal = NULL;
2384 code = krb5_get_init_creds_password(ctx, &store_creds,
2385 init_principal,
2386 init_password,
2387 NULL, NULL,
2389 NULL,
2390 krb_options);
2391 if (code != 0) {
2392 return code;
2395 store_principal = init_principal;
2398 * We are trying S4U2Self now:
2400 * As we do not want to expose our TGT in the
2401 * krb5_ccache, which is also holds the impersonated creds.
2403 * Some low level krb5/gssapi function might use the TGT
2404 * identity and let the client act as our machine account.
2406 * We need to avoid that and use a temporary krb5_ccache
2407 * in order to pass our TGT to the krb5_get_creds() function.
2409 code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
2410 if (code != 0) {
2411 krb5_free_cred_contents(ctx, &store_creds);
2412 return code;
2415 code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
2416 if (code != 0) {
2417 krb5_cc_destroy(ctx, tmp_cc);
2418 krb5_free_cred_contents(ctx, &store_creds);
2419 return code;
2422 code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
2423 if (code != 0) {
2424 krb5_free_cred_contents(ctx, &store_creds);
2425 krb5_cc_destroy(ctx, tmp_cc);
2426 return code;
2430 * we need to remember the client principal of our
2431 * TGT and make sure the KDC does not return this
2432 * in the impersonated tickets. This can happen
2433 * if the KDC does not support S4U2Self and S4U2Proxy.
2435 blacklist_principal = store_creds.client;
2436 store_creds.client = NULL;
2437 krb5_free_cred_contents(ctx, &store_creds);
2440 * Check if we also need S4U2Proxy or if S4U2Self is
2441 * enough in order to get a ticket for the target.
2443 if (target_service == NULL) {
2444 s4u2proxy = false;
2445 } else if (strcmp(target_service, self_service) == 0) {
2446 s4u2proxy = false;
2447 } else {
2448 s4u2proxy = true;
2452 * For S4U2Self we need our own service principal,
2453 * which belongs to our own realm (available on
2454 * our client principal).
2456 self_realm = krb5_principal_get_realm(ctx, init_principal);
2458 code = krb5_parse_name(ctx, self_service, &self_princ);
2459 if (code != 0) {
2460 krb5_free_principal(ctx, blacklist_principal);
2461 krb5_cc_destroy(ctx, tmp_cc);
2462 return code;
2465 code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2466 if (code != 0) {
2467 krb5_free_principal(ctx, blacklist_principal);
2468 krb5_free_principal(ctx, self_princ);
2469 krb5_cc_destroy(ctx, tmp_cc);
2470 return code;
2473 code = krb5_get_creds_opt_alloc(ctx, &options);
2474 if (code != 0) {
2475 krb5_free_principal(ctx, blacklist_principal);
2476 krb5_free_principal(ctx, self_princ);
2477 krb5_cc_destroy(ctx, tmp_cc);
2478 return code;
2481 if (s4u2proxy) {
2483 * If we want S4U2Proxy, we need the forwardable flag
2484 * on the S4U2Self ticket.
2486 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2489 code = krb5_get_creds_opt_set_impersonate(ctx, options,
2490 impersonate_principal);
2491 if (code != 0) {
2492 krb5_get_creds_opt_free(ctx, options);
2493 krb5_free_principal(ctx, blacklist_principal);
2494 krb5_free_principal(ctx, self_princ);
2495 krb5_cc_destroy(ctx, tmp_cc);
2496 return code;
2499 code = krb5_get_creds(ctx, options, tmp_cc,
2500 self_princ, &s4u2self_creds);
2501 krb5_get_creds_opt_free(ctx, options);
2502 krb5_free_principal(ctx, self_princ);
2503 if (code != 0) {
2504 krb5_free_principal(ctx, blacklist_principal);
2505 krb5_cc_destroy(ctx, tmp_cc);
2506 return code;
2509 if (!s4u2proxy) {
2510 krb5_cc_destroy(ctx, tmp_cc);
2513 * Now make sure we store the impersonated principal
2514 * and creds instead of the TGT related stuff
2515 * in the krb5_ccache of the caller.
2517 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2518 &store_creds);
2519 krb5_free_creds(ctx, s4u2self_creds);
2520 if (code != 0) {
2521 return code;
2525 * It's important to store the principal the KDC
2526 * returned, as otherwise the caller would not find
2527 * the S4U2Self ticket in the krb5_ccache lookup.
2529 store_principal = store_creds.client;
2530 goto store;
2534 * We are trying S4U2Proxy:
2536 * We need the ticket from the S4U2Self step
2537 * and our TGT in order to get the delegated ticket.
2539 code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2540 s4u2self_creds->ticket.length,
2541 &s4u2self_ticket,
2542 &s4u2self_ticketlen);
2543 if (code != 0) {
2544 krb5_free_creds(ctx, s4u2self_creds);
2545 krb5_free_principal(ctx, blacklist_principal);
2546 krb5_cc_destroy(ctx, tmp_cc);
2547 return code;
2551 * we need to remember the client principal of the
2552 * S4U2Self stage and as it needs to match the one we
2553 * will get for the S4U2Proxy stage. We need this
2554 * in order to detect KDCs which does not support S4U2Proxy.
2556 whitelist_principal = s4u2self_creds->client;
2557 s4u2self_creds->client = NULL;
2558 krb5_free_creds(ctx, s4u2self_creds);
2561 * For S4U2Proxy we also got a target service principal,
2562 * which also belongs to our own realm (available on
2563 * our client principal).
2565 code = krb5_parse_name(ctx, target_service, &target_princ);
2566 if (code != 0) {
2567 free_Ticket(&s4u2self_ticket);
2568 krb5_free_principal(ctx, whitelist_principal);
2569 krb5_free_principal(ctx, blacklist_principal);
2570 krb5_cc_destroy(ctx, tmp_cc);
2571 return code;
2574 code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2575 if (code != 0) {
2576 free_Ticket(&s4u2self_ticket);
2577 krb5_free_principal(ctx, target_princ);
2578 krb5_free_principal(ctx, whitelist_principal);
2579 krb5_free_principal(ctx, blacklist_principal);
2580 krb5_cc_destroy(ctx, tmp_cc);
2581 return code;
2584 code = krb5_get_creds_opt_alloc(ctx, &options);
2585 if (code != 0) {
2586 free_Ticket(&s4u2self_ticket);
2587 krb5_free_principal(ctx, target_princ);
2588 krb5_free_principal(ctx, whitelist_principal);
2589 krb5_free_principal(ctx, blacklist_principal);
2590 krb5_cc_destroy(ctx, tmp_cc);
2591 return code;
2594 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2595 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2597 code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2598 free_Ticket(&s4u2self_ticket);
2599 if (code != 0) {
2600 krb5_get_creds_opt_free(ctx, options);
2601 krb5_free_principal(ctx, target_princ);
2602 krb5_free_principal(ctx, whitelist_principal);
2603 krb5_free_principal(ctx, blacklist_principal);
2604 krb5_cc_destroy(ctx, tmp_cc);
2605 return code;
2608 code = krb5_get_creds(ctx, options, tmp_cc,
2609 target_princ, &s4u2proxy_creds);
2610 krb5_get_creds_opt_free(ctx, options);
2611 krb5_free_principal(ctx, target_princ);
2612 krb5_cc_destroy(ctx, tmp_cc);
2613 if (code != 0) {
2614 krb5_free_principal(ctx, whitelist_principal);
2615 krb5_free_principal(ctx, blacklist_principal);
2616 return code;
2620 * Now make sure we store the impersonated principal
2621 * and creds instead of the TGT related stuff
2622 * in the krb5_ccache of the caller.
2624 code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2625 &store_creds);
2626 krb5_free_creds(ctx, s4u2proxy_creds);
2627 if (code != 0) {
2628 krb5_free_principal(ctx, whitelist_principal);
2629 krb5_free_principal(ctx, blacklist_principal);
2630 return code;
2634 * It's important to store the principal the KDC
2635 * returned, as otherwise the caller would not find
2636 * the S4U2Self ticket in the krb5_ccache lookup.
2638 store_principal = store_creds.client;
2640 store:
2641 if (blacklist_principal &&
2642 krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2643 char *sp = NULL;
2644 char *ip = NULL;
2646 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2647 if (code != 0) {
2648 sp = NULL;
2650 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2651 if (code != 0) {
2652 ip = NULL;
2654 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2655 "KDC returned self principal[%s] while impersonating [%s]\n",
2656 sp?sp:"<no memory>",
2657 ip?ip:"<no memory>"));
2659 SAFE_FREE(sp);
2660 SAFE_FREE(ip);
2662 krb5_free_principal(ctx, whitelist_principal);
2663 krb5_free_principal(ctx, blacklist_principal);
2664 krb5_free_cred_contents(ctx, &store_creds);
2665 return KRB5_FWD_BAD_PRINCIPAL;
2667 if (blacklist_principal) {
2668 krb5_free_principal(ctx, blacklist_principal);
2671 if (whitelist_principal &&
2672 !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2673 char *sp = NULL;
2674 char *ep = NULL;
2676 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2677 if (code != 0) {
2678 sp = NULL;
2680 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2681 if (code != 0) {
2682 ep = NULL;
2684 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2685 "KDC returned wrong principal[%s] we expected [%s]\n",
2686 sp?sp:"<no memory>",
2687 ep?ep:"<no memory>"));
2689 SAFE_FREE(sp);
2690 SAFE_FREE(ep);
2692 krb5_free_principal(ctx, whitelist_principal);
2693 krb5_free_cred_contents(ctx, &store_creds);
2694 return KRB5_FWD_BAD_PRINCIPAL;
2696 if (whitelist_principal) {
2697 krb5_free_principal(ctx, whitelist_principal);
2700 code = krb5_cc_initialize(ctx, store_cc, store_principal);
2701 if (code != 0) {
2702 krb5_free_cred_contents(ctx, &store_creds);
2703 return code;
2706 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2707 if (code != 0) {
2708 krb5_free_cred_contents(ctx, &store_creds);
2709 return code;
2712 client_realm = krb5_principal_get_realm(ctx, store_creds.client);
2713 if (client_realm != NULL) {
2715 * Because the CANON flag doesn't have any impact
2716 * on the impersonate_principal => store_creds.client
2717 * realm mapping. We need to store the credentials twice,
2718 * once with the returned realm and once with the
2719 * realm of impersonate_principal.
2721 code = krb5_principal_set_realm(ctx, store_creds.server,
2722 client_realm);
2723 if (code != 0) {
2724 krb5_free_cred_contents(ctx, &store_creds);
2725 return code;
2728 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2729 if (code != 0) {
2730 krb5_free_cred_contents(ctx, &store_creds);
2731 return code;
2735 if (expire_time) {
2736 *expire_time = (time_t) store_creds.times.endtime;
2739 if (kdc_time) {
2740 *kdc_time = (time_t) store_creds.times.starttime;
2743 krb5_free_cred_contents(ctx, &store_creds);
2745 return 0;
2748 #else /* MIT */
2750 static bool princ_compare_no_dollar(krb5_context ctx,
2751 krb5_principal a,
2752 krb5_principal b)
2754 krb5_principal mod = NULL;
2755 bool cmp;
2757 if (a->length == 1 && b->length == 1 &&
2758 a->data[0].length != 0 && b->data[0].length != 0 &&
2759 a->data[0].data[a->data[0].length - 1] !=
2760 b->data[0].data[b->data[0].length - 1]) {
2761 if (a->data[0].data[a->data[0].length - 1] == '$') {
2762 mod = a;
2763 mod->data[0].length--;
2764 } else if (b->data[0].data[b->data[0].length - 1] == '$') {
2765 mod = b;
2766 mod->data[0].length--;
2770 cmp = krb5_principal_compare_flags(ctx,
2773 KRB5_PRINCIPAL_COMPARE_CASEFOLD);
2774 if (mod != NULL) {
2775 mod->data[0].length++;
2778 return cmp;
2781 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
2782 krb5_ccache store_cc,
2783 krb5_principal init_principal,
2784 const char *init_password,
2785 krb5_principal impersonate_principal,
2786 const char *self_service,
2787 const char *target_service,
2788 krb5_get_init_creds_opt *krb_options,
2789 time_t *expire_time,
2790 time_t *kdc_time)
2792 krb5_error_code code;
2793 krb5_principal self_princ = NULL;
2794 krb5_principal target_princ = NULL;
2795 krb5_creds *store_creds = NULL;
2796 krb5_creds *s4u2self_creds = NULL;
2797 krb5_creds *s4u2proxy_creds = NULL;
2798 krb5_creds init_creds = {0};
2799 krb5_creds mcreds = {0};
2800 krb5_flags options = KRB5_GC_NO_STORE;
2801 krb5_ccache tmp_cc;
2802 bool s4u2proxy = false;
2803 bool ok;
2805 code = krb5_cc_new_unique(ctx, "MEMORY", NULL, &tmp_cc);
2806 if (code != 0) {
2807 return code;
2810 code = krb5_get_init_creds_password(ctx,
2811 &init_creds,
2812 init_principal,
2813 init_password,
2814 NULL,
2815 NULL,
2817 NULL,
2818 krb_options);
2819 if (code != 0) {
2820 goto done;
2823 code = krb5_cc_initialize(ctx, tmp_cc, init_creds.client);
2824 if (code != 0) {
2825 goto done;
2828 code = krb5_cc_store_cred(ctx, tmp_cc, &init_creds);
2829 if (code != 0) {
2830 goto done;
2834 * Check if we also need S4U2Proxy or if S4U2Self is
2835 * enough in order to get a ticket for the target.
2837 if (target_service == NULL) {
2838 s4u2proxy = false;
2839 } else if (strcmp(target_service, self_service) == 0) {
2840 s4u2proxy = false;
2841 } else {
2842 s4u2proxy = true;
2845 code = krb5_parse_name(ctx, self_service, &self_princ);
2846 if (code != 0) {
2847 goto done;
2851 * MIT lacks aliases support in S4U, for S4U2Self we require the tgt
2852 * client and the request server to be the same principal name.
2854 ok = princ_compare_no_dollar(ctx, init_creds.client, self_princ);
2855 if (!ok) {
2856 code = KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
2857 goto done;
2860 mcreds.client = impersonate_principal;
2861 mcreds.server = init_creds.client;
2863 code = krb5_get_credentials_for_user(ctx, options, tmp_cc, &mcreds,
2864 NULL, &s4u2self_creds);
2865 if (code != 0) {
2866 goto done;
2869 if (s4u2proxy) {
2870 code = krb5_parse_name(ctx, target_service, &target_princ);
2871 if (code != 0) {
2872 goto done;
2875 mcreds.client = init_creds.client;
2876 mcreds.server = target_princ;
2877 mcreds.second_ticket = s4u2self_creds->ticket;
2879 code = krb5_get_credentials(ctx, options |
2880 KRB5_GC_CONSTRAINED_DELEGATION,
2881 tmp_cc, &mcreds, &s4u2proxy_creds);
2882 if (code != 0) {
2883 goto done;
2886 /* Check KDC support of S4U2Proxy extension */
2887 if (!krb5_principal_compare(ctx, s4u2self_creds->client,
2888 s4u2proxy_creds->client)) {
2889 code = KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
2890 goto done;
2893 store_creds = s4u2proxy_creds;
2894 } else {
2895 store_creds = s4u2self_creds;;
2897 /* We need to save the ticket with the requested server name
2898 * or the caller won't be able to find it in cache. */
2899 if (!krb5_principal_compare(ctx, self_princ,
2900 store_creds->server)) {
2901 krb5_free_principal(ctx, store_creds->server);
2902 store_creds->server = NULL;
2903 code = krb5_copy_principal(ctx, self_princ,
2904 &store_creds->server);
2905 if (code != 0) {
2906 goto done;
2911 code = krb5_cc_initialize(ctx, store_cc, store_creds->client);
2912 if (code != 0) {
2913 goto done;
2916 code = krb5_cc_store_cred(ctx, store_cc, store_creds);
2917 if (code != 0) {
2918 goto done;
2921 if (expire_time) {
2922 *expire_time = (time_t) store_creds->times.endtime;
2925 if (kdc_time) {
2926 *kdc_time = (time_t) store_creds->times.starttime;
2929 done:
2930 krb5_cc_destroy(ctx, tmp_cc);
2931 krb5_free_cred_contents(ctx, &init_creds);
2932 krb5_free_creds(ctx, s4u2self_creds);
2933 krb5_free_creds(ctx, s4u2proxy_creds);
2934 krb5_free_principal(ctx, self_princ);
2935 krb5_free_principal(ctx, target_princ);
2937 return code;
2939 #endif
2941 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2943 * @brief Create a principal name using a variable argument list.
2945 * @param[in] context The library context.
2947 * @param[inout] principal A pointer to the principal structure.
2949 * @param[in] _realm The realm to use. If NULL then the function will
2950 * get the default realm name.
2952 * @param[in] ... A list of 'char *' components, ending with NULL.
2954 * Use krb5_free_principal() to free the principal when it is no longer needed.
2956 * @return 0 on success, a Kerberos error code otherwise.
2958 krb5_error_code smb_krb5_make_principal(krb5_context context,
2959 krb5_principal *principal,
2960 const char *_realm, ...)
2962 krb5_error_code code;
2963 bool free_realm;
2964 char *realm;
2965 va_list ap;
2967 if (_realm) {
2968 realm = discard_const_p(char, _realm);
2969 free_realm = false;
2970 } else {
2971 code = krb5_get_default_realm(context, &realm);
2972 if (code) {
2973 return code;
2975 free_realm = true;
2978 va_start(ap, _realm);
2979 code = krb5_build_principal_alloc_va(context, principal,
2980 strlen(realm), realm,
2981 ap);
2982 va_end(ap);
2984 if (free_realm) {
2985 krb5_free_default_realm(context, realm);
2988 return code;
2990 #endif
2992 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2994 * @brief Get the lifetime of the initial ticket in the cache.
2996 * @param[in] context The kerberos context.
2998 * @param[in] id The credential cache to get the ticket lifetime.
3000 * @param[out] t A pointer to a time value to store the lifetime.
3002 * @return 0 on success, a krb5_error_code on error.
3004 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
3005 krb5_ccache id,
3006 time_t *t)
3008 krb5_cc_cursor cursor;
3009 krb5_error_code kerr;
3010 krb5_creds cred;
3011 krb5_timestamp now;
3013 *t = 0;
3015 kerr = krb5_timeofday(context, &now);
3016 if (kerr) {
3017 return kerr;
3020 kerr = krb5_cc_start_seq_get(context, id, &cursor);
3021 if (kerr) {
3022 return kerr;
3025 while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
3026 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
3027 if (cred.ticket_flags & TKT_FLG_INITIAL) {
3028 #else
3029 if (cred.flags.b.initial) {
3030 #endif
3031 if (now < cred.times.endtime) {
3032 *t = (time_t) (cred.times.endtime - now);
3034 krb5_free_cred_contents(context, &cred);
3035 break;
3037 krb5_free_cred_contents(context, &cred);
3040 krb5_cc_end_seq_get(context, id, &cursor);
3042 return kerr;
3044 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
3046 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
3047 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
3049 free_Checksum(cksum);
3051 #endif
3054 * @brief Compute a checksum operating on a keyblock.
3056 * This function computes a checksum over a PAC using the keyblock for a keyed
3057 * checksum.
3059 * @param[in] mem_ctx A talloc context to allocate the signature on.
3061 * @param[in] pac_data The PAC as input.
3063 * @param[in] context The library context.
3065 * @param[in] keyblock Encryption key for a keyed checksum.
3067 * @param[out] sig_type The checksum type
3069 * @param[out] sig_blob The talloc'ed checksum
3071 * The caller must free the sig_blob with talloc_free() when it is not needed
3072 * anymore.
3074 * @return 0 on success, a Kerberos error code otherwise.
3076 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
3077 DATA_BLOB *pac_data,
3078 krb5_context context,
3079 const krb5_keyblock *keyblock,
3080 uint32_t *sig_type,
3081 DATA_BLOB *sig_blob)
3083 krb5_error_code ret;
3084 krb5_checksum cksum;
3085 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
3086 krb5_crypto crypto;
3089 ret = krb5_crypto_init(context,
3090 keyblock,
3092 &crypto);
3093 if (ret) {
3094 DEBUG(0,("krb5_crypto_init() failed: %s\n",
3095 smb_get_krb5_error_message(context, ret, mem_ctx)));
3096 return ret;
3098 ret = krb5_create_checksum(context,
3099 crypto,
3100 KRB5_KU_OTHER_CKSUM,
3102 pac_data->data,
3103 pac_data->length,
3104 &cksum);
3105 if (ret) {
3106 DEBUG(2, ("PAC Verification failed: %s\n",
3107 smb_get_krb5_error_message(context, ret, mem_ctx)));
3110 krb5_crypto_destroy(context, crypto);
3112 if (ret) {
3113 return ret;
3116 *sig_type = cksum.cksumtype;
3117 *sig_blob = data_blob_talloc(mem_ctx,
3118 cksum.checksum.data,
3119 cksum.checksum.length);
3120 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
3121 krb5_data input;
3123 input.data = (char *)pac_data->data;
3124 input.length = pac_data->length;
3126 ret = krb5_c_make_checksum(context,
3128 keyblock,
3129 KRB5_KEYUSAGE_APP_DATA_CKSUM,
3130 &input,
3131 &cksum);
3132 if (ret) {
3133 DEBUG(2, ("PAC Verification failed: %s\n",
3134 smb_get_krb5_error_message(context, ret, mem_ctx)));
3135 return ret;
3138 *sig_type = cksum.checksum_type;
3139 *sig_blob = data_blob_talloc(mem_ctx,
3140 cksum.contents,
3141 cksum.length);
3143 #else
3144 #error krb5_create_checksum or krb5_c_make_checksum not available
3145 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
3146 smb_krb5_free_checksum_contents(context, &cksum);
3148 return 0;
3153 * @brief Get realm of a principal
3155 * @param[in] mem_ctx The talloc ctx to put the result on
3157 * @param[in] context The library context
3159 * @param[in] principal The principal to get the realm from.
3161 * @return A talloced string with the realm or NULL if an error occurred.
3163 char *smb_krb5_principal_get_realm(TALLOC_CTX *mem_ctx,
3164 krb5_context context,
3165 krb5_const_principal principal)
3167 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
3168 return talloc_strdup(mem_ctx,
3169 krb5_principal_get_realm(context, principal));
3170 #elif defined(krb5_princ_realm) /* MIT */
3171 const krb5_data *realm;
3172 realm = krb5_princ_realm(context, principal);
3173 return talloc_strndup(mem_ctx, realm->data, realm->length);
3174 #else
3175 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
3176 #endif
3180 * @brief Get realm of a principal
3182 * @param[in] context The library context
3184 * @param[in] principal The principal to set the realm
3186 * @param[in] realm The realm as a string to set.
3188 * @return 0 on success, a Kerberos error code otherwise.
3190 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
3191 krb5_principal principal,
3192 const char *realm)
3194 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
3195 return krb5_principal_set_realm(context, principal, realm);
3196 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
3197 krb5_error_code ret;
3198 krb5_data data;
3199 krb5_data *old_data;
3201 old_data = krb5_princ_realm(context, principal);
3203 ret = smb_krb5_copy_data_contents(&data,
3204 realm,
3205 strlen(realm));
3206 if (ret) {
3207 return ret;
3210 /* free realm before setting */
3211 free(old_data->data);
3213 krb5_princ_set_realm(context, principal, &data);
3215 return ret;
3216 #else
3217 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
3218 #endif
3223 * @brief Get the realm from the service hostname.
3225 * This function will look for a domain realm mapping in the [domain_realm]
3226 * section of the krb5.conf first and fallback to extract the realm from
3227 * the provided service hostname. As a last resort it will return the
3228 * provided client_realm.
3230 * @param[in] mem_ctx The talloc context
3232 * @param[in] hostname The service hostname
3234 * @param[in] client_realm If we can not find a mapping, fall back to
3235 * this realm.
3237 * @return The realm to use for the service hostname, NULL if a fatal error
3238 * occurred.
3240 char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
3241 const char *hostname,
3242 const char *client_realm)
3244 #if defined(HAVE_KRB5_REALM_TYPE)
3245 /* Heimdal. */
3246 krb5_realm *realm_list = NULL;
3247 #else
3248 /* MIT */
3249 char **realm_list = NULL;
3250 #endif
3251 char *realm = NULL;
3252 krb5_error_code kerr;
3253 krb5_context ctx = NULL;
3255 kerr = smb_krb5_init_context_common(&ctx);
3256 if (kerr) {
3257 DBG_ERR("kerberos init context failed (%s)\n",
3258 error_message(kerr));
3259 return NULL;
3262 kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
3263 if (kerr == KRB5_ERR_HOST_REALM_UNKNOWN) {
3264 realm_list = NULL;
3265 kerr = 0;
3267 if (kerr != 0) {
3268 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
3269 "failed %s\n",
3270 hostname ? hostname : "(NULL)",
3271 error_message(kerr) ));
3272 goto out;
3275 if (realm_list != NULL &&
3276 realm_list[0] != NULL &&
3277 realm_list[0][0] != '\0') {
3278 realm = talloc_strdup(mem_ctx, realm_list[0]);
3279 if (realm == NULL) {
3280 goto out;
3282 } else {
3283 const char *p = NULL;
3286 * "dc6.samba2003.example.com"
3287 * returns a realm of "SAMBA2003.EXAMPLE.COM"
3289 * "dc6." returns realm as NULL
3291 p = strchr_m(hostname, '.');
3292 if (p != NULL && p[1] != '\0') {
3293 realm = talloc_strdup_upper(mem_ctx, p + 1);
3294 if (realm == NULL) {
3295 goto out;
3300 if (realm == NULL) {
3301 realm = talloc_strdup(mem_ctx, client_realm);
3304 out:
3306 if (ctx) {
3307 if (realm_list) {
3308 krb5_free_host_realm(ctx, realm_list);
3309 realm_list = NULL;
3311 krb5_free_context(ctx);
3312 ctx = NULL;
3314 return realm;
3318 * @brief Get an error string from a Kerberos error code.
3320 * @param[in] context The library context.
3322 * @param[in] code The Kerberos error code.
3324 * @param[in] mem_ctx The talloc context to allocate the error string on.
3326 * @return A talloc'ed error string or NULL if an error occurred.
3328 * The caller must free the returned error string with talloc_free() if not
3329 * needed anymore
3331 char *smb_get_krb5_error_message(krb5_context context,
3332 krb5_error_code code,
3333 TALLOC_CTX *mem_ctx)
3335 char *ret;
3337 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
3338 const char *context_error = krb5_get_error_message(context, code);
3339 if (context_error) {
3340 ret = talloc_asprintf(mem_ctx, "%s: %s",
3341 error_message(code), context_error);
3342 krb5_free_error_message(context, context_error);
3343 return ret;
3345 #endif
3346 ret = talloc_strdup(mem_ctx, error_message(code));
3347 return ret;
3351 * @brief Return the type of a krb5_principal
3353 * @param[in] context The library context.
3355 * @param[in] principal The principal to get the type from.
3357 * @return The integer type of the principal.
3359 int smb_krb5_principal_get_type(krb5_context context,
3360 krb5_const_principal principal)
3362 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
3363 return krb5_principal_get_type(context, principal);
3364 #elif defined(krb5_princ_type) /* MIT */
3365 return krb5_princ_type(context, principal);
3366 #else
3367 #error UNKNOWN_PRINC_GET_TYPE_FUNCTION
3368 #endif
3372 * @brief Set the type of a principal
3374 * @param[in] context The library context
3376 * @param[inout] principal The principal to set the type for.
3378 * @param[in] type The principal type to set.
3380 void smb_krb5_principal_set_type(krb5_context context,
3381 krb5_principal principal,
3382 int type)
3384 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
3385 krb5_principal_set_type(context, principal, type);
3386 #elif defined(krb5_princ_type) /* MIT */
3387 krb5_princ_type(context, principal) = type;
3388 #else
3389 #error UNKNOWN_PRINC_SET_TYPE_FUNCTION
3390 #endif
3394 * @brief Check if a principal is a TGS
3396 * @param[in] context The library context
3398 * @param[inout] principal The principal to check.
3400 * @returns 1 if equal, 0 if not and -1 on error.
3402 int smb_krb5_principal_is_tgs(krb5_context context,
3403 krb5_const_principal principal)
3405 char *p = NULL;
3406 int eq = 1;
3408 p = smb_krb5_principal_get_comp_string(NULL, context, principal, 0);
3409 if (p == NULL) {
3410 return -1;
3413 eq = krb5_princ_size(context, principal) == 2 &&
3414 (strcmp(p, KRB5_TGS_NAME) == 0);
3416 talloc_free(p);
3418 return eq;
3421 #if !defined(HAVE_KRB5_WARNX)
3423 * @brief Log a Kerberos message
3425 * It sends the message to com_err.
3427 * @param[in] context The library context
3429 * @param[in] fmt The message format
3431 * @param[in] ... The message arguments
3433 * @return 0 on success.
3435 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
3437 va_list args;
3439 va_start(args, fmt);
3440 com_err_va("samba-kdc", errno, fmt, args);
3441 va_end(args);
3443 return 0;
3445 #endif
3448 * @brief Copy a credential cache.
3450 * @param[in] context The library context.
3452 * @param[in] incc Credential cache to be copied.
3454 * @param[inout] outcc Copy of credential cache to be filled in.
3456 * @return 0 on success, a Kerberos error code otherwise.
3458 krb5_error_code smb_krb5_cc_copy_creds(krb5_context context,
3459 krb5_ccache incc, krb5_ccache outcc)
3461 #ifdef HAVE_KRB5_CC_COPY_CACHE /* Heimdal */
3462 return krb5_cc_copy_cache(context, incc, outcc);
3463 #elif defined(HAVE_KRB5_CC_COPY_CREDS)
3464 krb5_error_code ret;
3465 krb5_principal princ = NULL;
3467 ret = krb5_cc_get_principal(context, incc, &princ);
3468 if (ret != 0) {
3469 return ret;
3471 ret = krb5_cc_initialize(context, outcc, princ);
3472 krb5_free_principal(context, princ);
3473 if (ret != 0) {
3474 return ret;
3476 return krb5_cc_copy_creds(context, incc, outcc);
3477 #else
3478 #error UNKNOWN_KRB5_CC_COPY_CACHE_OR_CREDS_FUNCTION
3479 #endif
3482 /**********************************************************
3483 * ADS KRB5 CALLS
3484 **********************************************************/
3486 static bool ads_cleanup_expired_creds(krb5_context context,
3487 krb5_ccache ccache,
3488 krb5_creds *credsp)
3490 krb5_error_code retval;
3491 const char *cc_type = krb5_cc_get_type(context, ccache);
3493 DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
3494 cc_type, krb5_cc_get_name(context, ccache),
3495 http_timestring(talloc_tos(), credsp->times.endtime)));
3497 /* we will probably need new tickets if the current ones
3498 will expire within 10 seconds.
3500 if (credsp->times.endtime >= (time(NULL) + 10))
3501 return false;
3503 /* heimdal won't remove creds from a file ccache, and
3504 perhaps we shouldn't anyway, since internally we
3505 use memory ccaches, and a FILE one probably means that
3506 we're using creds obtained outside of our executable
3508 if (strequal(cc_type, "FILE")) {
3509 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
3510 return false;
3513 retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
3514 if (retval) {
3515 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
3516 error_message(retval)));
3517 /* If we have an error in this, we want to display it,
3518 but continue as though we deleted it */
3520 return true;
3523 /* Allocate and setup the auth context into the state we need. */
3525 static krb5_error_code ads_setup_auth_context(krb5_context context,
3526 krb5_auth_context *auth_context)
3528 krb5_error_code retval;
3530 retval = krb5_auth_con_init(context, auth_context );
3531 if (retval) {
3532 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
3533 error_message(retval)));
3534 return retval;
3537 /* Ensure this is an addressless ticket. */
3538 retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
3539 if (retval) {
3540 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
3541 error_message(retval)));
3544 return retval;
3547 #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)
3548 static krb5_error_code ads_create_gss_checksum(krb5_data *in_data, /* [inout] */
3549 uint32_t gss_flags)
3551 unsigned int orig_length = in_data->length;
3552 unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
3553 char *gss_cksum = NULL;
3555 if (orig_length) {
3556 /* Extra length field for delegated ticket. */
3557 base_cksum_size += 4;
3560 if ((unsigned int)base_cksum_size + orig_length <
3561 (unsigned int)base_cksum_size) {
3562 return EINVAL;
3565 gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
3566 if (gss_cksum == NULL) {
3567 return ENOMEM;
3570 memset(gss_cksum, '\0', base_cksum_size + orig_length);
3571 SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
3574 * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
3575 * This matches the behavior of heimdal and mit.
3577 * And it is needed to work against some closed source
3578 * SMB servers.
3580 * See bug #7883
3582 memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
3584 SIVAL(gss_cksum, 20, gss_flags);
3586 if (orig_length && in_data->data != NULL) {
3587 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
3588 SSVAL(gss_cksum, 26, orig_length);
3589 /* Copy the kerberos KRB_CRED data */
3590 memcpy(gss_cksum + 28, in_data->data, orig_length);
3591 free(in_data->data);
3592 in_data->data = NULL;
3593 in_data->length = 0;
3595 in_data->data = gss_cksum;
3596 in_data->length = base_cksum_size + orig_length;
3597 return 0;
3599 #endif
3602 * We can't use krb5_mk_req because w2k wants the service to be in a particular
3603 * format.
3605 static krb5_error_code ads_krb5_mk_req(krb5_context context,
3606 krb5_auth_context *auth_context,
3607 const krb5_flags ap_req_options,
3608 const char *principal,
3609 krb5_ccache ccache,
3610 krb5_data *outbuf,
3611 time_t *expire_time,
3612 const char *impersonate_princ_s)
3614 krb5_error_code retval;
3615 krb5_principal server;
3616 krb5_principal impersonate_princ = NULL;
3617 krb5_creds *credsp;
3618 krb5_creds creds;
3619 krb5_data in_data;
3620 bool creds_ready = false;
3621 int i = 0, maxtries = 3;
3622 bool ok;
3624 ZERO_STRUCT(in_data);
3626 retval = smb_krb5_parse_name(context, principal, &server);
3627 if (retval != 0) {
3628 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
3629 return retval;
3632 if (impersonate_princ_s) {
3633 retval = smb_krb5_parse_name(context, impersonate_princ_s,
3634 &impersonate_princ);
3635 if (retval) {
3636 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
3637 goto cleanup_princ;
3641 /* obtain ticket & session key */
3642 ZERO_STRUCT(creds);
3643 if ((retval = krb5_copy_principal(context, server, &creds.server))) {
3644 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
3645 error_message(retval)));
3646 goto cleanup_princ;
3649 retval = krb5_cc_get_principal(context, ccache, &creds.client);
3650 if (retval != 0) {
3651 /* This can commonly fail on smbd startup with no ticket in the cache.
3652 * Report at higher level than 1. */
3653 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
3654 error_message(retval)));
3655 goto cleanup_creds;
3658 while (!creds_ready && (i < maxtries)) {
3660 retval = smb_krb5_get_credentials(context,
3661 ccache,
3662 creds.client,
3663 creds.server,
3664 impersonate_princ,
3665 &credsp);
3666 if (retval != 0) {
3667 DBG_WARNING("smb_krb5_get_credentials failed for %s "
3668 "(%s)\n",
3669 principal,
3670 error_message(retval));
3671 goto cleanup_creds;
3674 /* cope with ticket being in the future due to clock skew */
3675 if ((unsigned)credsp->times.starttime > time(NULL)) {
3676 time_t t = time(NULL);
3677 int time_offset =(int)((unsigned)credsp->times.starttime-t);
3678 DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
3679 krb5_set_real_time(context, t + time_offset + 1, 0);
3682 ok = ads_cleanup_expired_creds(context, ccache, credsp);
3683 if (!ok) {
3684 creds_ready = true;
3687 i++;
3690 DBG_DEBUG("Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
3691 principal,
3692 krb5_cc_get_type(context, ccache),
3693 krb5_cc_get_name(context, ccache),
3694 http_timestring(talloc_tos(),
3695 (unsigned)credsp->times.endtime),
3696 (unsigned)credsp->times.endtime);
3698 if (expire_time) {
3699 *expire_time = (time_t)credsp->times.endtime;
3702 /* Allocate the auth_context. */
3703 retval = ads_setup_auth_context(context, auth_context);
3704 if (retval != 0) {
3705 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3706 error_message(retval));
3707 goto cleanup_creds;
3710 #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)
3712 uint32_t gss_flags = 0;
3714 if (credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE) {
3716 * Fetch a forwarded TGT from the KDC so that we can
3717 * hand off a 2nd ticket as part of the kerberos
3718 * exchange.
3721 DBG_INFO("Server marked as OK to delegate to, building "
3722 "forwardable TGT\n");
3724 retval = krb5_auth_con_setuseruserkey(context,
3725 *auth_context,
3726 &credsp->keyblock );
3727 if (retval != 0) {
3728 DBG_WARNING("krb5_auth_con_setuseruserkey "
3729 "failed (%s)\n",
3730 error_message(retval));
3731 goto cleanup_creds;
3734 /* Must use a subkey for forwarded tickets. */
3735 retval = krb5_auth_con_setflags(context,
3736 *auth_context,
3737 KRB5_AUTH_CONTEXT_USE_SUBKEY);
3738 if (retval != 0) {
3739 DBG_WARNING("krb5_auth_con_setflags failed (%s)\n",
3740 error_message(retval));
3741 goto cleanup_creds;
3744 retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
3745 *auth_context, /* Authentication context [in] */
3746 discard_const_p(char, KRB5_TGS_NAME), /* Ticket service name ("krbtgt") [in] */
3747 credsp->client, /* Client principal for the tgt [in] */
3748 credsp->server, /* Server principal for the tgt [in] */
3749 ccache, /* Credential cache to use for storage [in] */
3750 1, /* Turn on for "Forwardable ticket" [in] */
3751 &in_data ); /* Resulting response [out] */
3753 if (retval) {
3754 DBG_INFO("krb5_fwd_tgt_creds failed (%s)\n",
3755 error_message(retval));
3758 * This is not fatal. Delete the *auth_context and continue
3759 * with krb5_mk_req_extended to get a non-forwardable ticket.
3762 if (in_data.data) {
3763 free( in_data.data );
3764 in_data.data = NULL;
3765 in_data.length = 0;
3767 krb5_auth_con_free(context, *auth_context);
3768 *auth_context = NULL;
3769 retval = ads_setup_auth_context(context, auth_context);
3770 if (retval != 0) {
3771 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3772 error_message(retval));
3773 goto cleanup_creds;
3775 } else {
3776 /* We got a delegated ticket. */
3777 gss_flags |= GSS_C_DELEG_FLAG;
3781 /* Frees and reallocates in_data into a GSS checksum blob. */
3782 retval = ads_create_gss_checksum(&in_data, gss_flags);
3783 if (retval != 0) {
3784 goto cleanup_data;
3787 /* We always want GSS-checksum types. */
3788 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
3789 if (retval != 0) {
3790 DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
3791 error_message(retval)));
3792 goto cleanup_data;
3795 #endif
3797 retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
3798 &in_data, credsp, outbuf);
3799 if (retval != 0) {
3800 DBG_WARNING("krb5_mk_req_extended failed (%s)\n",
3801 error_message(retval));
3804 #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)
3805 cleanup_data:
3806 #endif
3808 if (in_data.data) {
3809 free( in_data.data );
3810 in_data.length = 0;
3813 krb5_free_creds(context, credsp);
3815 cleanup_creds:
3816 krb5_free_cred_contents(context, &creds);
3818 cleanup_princ:
3819 krb5_free_principal(context, server);
3820 if (impersonate_princ) {
3821 krb5_free_principal(context, impersonate_princ);
3824 return retval;
3828 get a kerberos5 ticket for the given service
3830 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3831 const char *principal,
3832 time_t time_offset,
3833 DATA_BLOB *ticket,
3834 DATA_BLOB *session_key_krb5,
3835 uint32_t extra_ap_opts, const char *ccname,
3836 time_t *tgs_expire,
3837 const char *impersonate_princ_s)
3839 krb5_error_code retval;
3840 krb5_data packet;
3841 krb5_context context = NULL;
3842 krb5_ccache ccdef = NULL;
3843 krb5_auth_context auth_context = NULL;
3844 krb5_enctype enc_types[] = {
3845 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
3846 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
3847 ENCTYPE_ARCFOUR_HMAC,
3848 ENCTYPE_NULL};
3849 bool ok;
3851 DBG_DEBUG("Getting ticket for service [%s] using creds from [%s] "
3852 "and impersonating [%s]\n",
3853 principal, ccname, impersonate_princ_s);
3855 retval = smb_krb5_init_context_common(&context);
3856 if (retval != 0) {
3857 DBG_ERR("kerberos init context failed (%s)\n",
3858 error_message(retval));
3859 goto failed;
3862 if (time_offset != 0) {
3863 krb5_set_real_time(context, time(NULL) + time_offset, 0);
3866 retval = krb5_cc_resolve(context,
3867 ccname ? ccname : krb5_cc_default_name(context),
3868 &ccdef);
3869 if (retval != 0) {
3870 DBG_WARNING("krb5_cc_default failed (%s)\n",
3871 error_message(retval));
3872 goto failed;
3875 retval = krb5_set_default_tgs_ktypes(context, enc_types);
3876 if (retval != 0) {
3877 DBG_WARNING("krb5_set_default_tgs_ktypes failed (%s)\n",
3878 error_message(retval));
3879 goto failed;
3882 retval = ads_krb5_mk_req(context,
3883 &auth_context,
3884 AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
3885 principal,
3886 ccdef,
3887 &packet,
3888 tgs_expire,
3889 impersonate_princ_s);
3890 if (retval != 0) {
3891 goto failed;
3894 ok = smb_krb5_get_smb_session_key(mem_ctx,
3895 context,
3896 auth_context,
3897 session_key_krb5,
3898 false);
3899 if (!ok) {
3900 retval = ENOMEM;
3901 goto failed;
3904 *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
3906 smb_krb5_free_data_contents(context, &packet);
3908 failed:
3910 if (context) {
3911 if (ccdef) {
3912 krb5_cc_close(context, ccdef);
3914 if (auth_context) {
3915 krb5_auth_con_free(context, auth_context);
3917 krb5_free_context(context);
3920 return retval;
3923 #ifndef SAMBA4_USES_HEIMDAL /* MITKRB5 tracing callback */
3924 static void smb_krb5_trace_cb(krb5_context ctx,
3925 #ifdef HAVE_KRB5_TRACE_INFO
3926 const krb5_trace_info *info,
3927 #elif defined(HAVE_KRB5_TRACE_INFO_STRUCT)
3928 const struct krb5_trace_info *info,
3929 #else
3930 #error unknown krb5_trace_info
3931 #endif
3932 void *data)
3934 if (info != NULL) {
3935 DBGC_DEBUG(DBGC_KERBEROS, "%s", info->message);
3938 #endif
3940 krb5_error_code smb_krb5_init_context_common(krb5_context *_krb5_context)
3942 krb5_error_code ret;
3943 krb5_context krb5_ctx;
3945 initialize_krb5_error_table();
3947 ret = krb5_init_context(&krb5_ctx);
3948 if (ret) {
3949 DBG_ERR("Krb5 context initialization failed (%s)\n",
3950 error_message(ret));
3951 return ret;
3954 /* The MIT Kerberos build relies on using the system krb5.conf file.
3955 * If you really want to use another file please set KRB5_CONFIG
3956 * accordingly. */
3957 #ifndef SAMBA4_USES_HEIMDAL
3958 ret = krb5_set_trace_callback(krb5_ctx, smb_krb5_trace_cb, NULL);
3959 if (ret) {
3960 DBG_ERR("Failed to set MIT kerberos trace callback! (%s)\n",
3961 error_message(ret));
3963 #endif
3965 #ifdef SAMBA4_USES_HEIMDAL
3966 /* Set options in kerberos */
3967 krb5_set_dns_canonicalize_hostname(krb5_ctx, false);
3968 #endif
3970 *_krb5_context = krb5_ctx;
3971 return 0;
3974 #else /* HAVE_KRB5 */
3975 /* This saves a few linking headaches */
3976 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3977 const char *principal,
3978 time_t time_offset,
3979 DATA_BLOB *ticket,
3980 DATA_BLOB *session_key_krb5,
3981 uint32_t extra_ap_opts, const char *ccname,
3982 time_t *tgs_expire,
3983 const char *impersonate_princ_s)
3985 DEBUG(0,("NO KERBEROS SUPPORT\n"));
3986 return 1;
3989 #endif /* HAVE_KRB5 */