lib/krb5_wrap: Check return value of krb5_principal_get_comp_string()
[Samba.git] / lib / krb5_wrap / krb5_samba.c
blob062e05ead34a6a48ee0b6e982148f5d7e9037f40
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_FREE_ENCTYPES)
118 void krb5_free_enctypes(krb5_context context, krb5_enctype *val) {
119 krb5_xfree(val);
121 #endif
123 #if !defined(HAVE_KRB5_FREE_STRING)
124 void krb5_free_string(krb5_context context, char *val) {
125 SAFE_FREE(val);
127 #endif
129 krb5_error_code smb_krb5_princ_component(krb5_context context,
130 krb5_const_principal principal,
131 int i,
132 krb5_data *data);
133 krb5_error_code smb_krb5_princ_component(krb5_context context,
134 krb5_const_principal principal,
135 int i,
136 krb5_data *data)
138 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
139 const char *component = NULL;
141 if (i < 0) {
142 return EINVAL;
145 component = krb5_principal_get_comp_string(context, principal, i);
146 if (component == NULL) {
147 return ENOENT;
150 *data = smb_krb5_make_data(discard_const_p(char, component), strlen(component));
152 return 0;
153 #else
154 const krb5_data *kdata = NULL;
156 if (i < 0) {
157 return EINVAL;
160 kdata = krb5_princ_component(context, principal, i);
161 if (kdata == NULL) {
162 return ENOENT;
165 *data = *kdata;
167 return 0;
168 #endif
171 /**********************************************************
172 * WRAPPING FUNCTIONS
173 **********************************************************/
176 * @brief Stores the address of a 'struct sockaddr_storage' into a krb5_address
178 * @param[in] paddr A pointer to a 'struct sockaddr_storage to extract the
179 * address from.
181 * @param[out] pkaddr A Kerberos address to store the address in.
183 * @return True on success, false if an error occurred.
185 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
186 krb5_address *pkaddr)
188 memset(pkaddr, '\0', sizeof(krb5_address));
189 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
190 /* HEIMDAL */
191 #ifdef HAVE_IPV6
192 if (paddr->ss_family == AF_INET6) {
193 pkaddr->addr_type = KRB5_ADDRESS_INET6;
194 pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
195 pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
196 return true;
198 #endif
199 if (paddr->ss_family == AF_INET) {
200 pkaddr->addr_type = KRB5_ADDRESS_INET;
201 pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
202 pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
203 return true;
205 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
206 /* MIT */
207 #ifdef HAVE_IPV6
208 if (paddr->ss_family == AF_INET6) {
209 pkaddr->addrtype = ADDRTYPE_INET6;
210 pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
211 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
212 return true;
214 #endif
215 if (paddr->ss_family == AF_INET) {
216 pkaddr->addrtype = ADDRTYPE_INET;
217 pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
218 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
219 return true;
221 #else
222 #error UNKNOWN_ADDRTYPE
223 #endif
224 return false;
227 krb5_error_code smb_krb5_mk_error(krb5_context context,
228 krb5_error_code error_code,
229 const char *e_text,
230 krb5_data *e_data,
231 const krb5_principal client,
232 const krb5_principal server,
233 krb5_data *enc_err)
235 krb5_error_code code = EINVAL;
236 #ifdef SAMBA4_USES_HEIMDAL
237 code = krb5_mk_error(context,
238 error_code,
239 e_text,
240 e_data,
241 client,
242 server,
243 NULL, /* client_time */
244 NULL, /* client_usec */
245 enc_err);
246 #else
247 krb5_principal unspec_server = NULL;
248 krb5_error errpkt;
250 errpkt.ctime = 0;
251 errpkt.cusec = 0;
253 code = krb5_us_timeofday(context,
254 &errpkt.stime,
255 &errpkt.susec);
256 if (code != 0) {
257 return code;
260 errpkt.error = error_code - ERROR_TABLE_BASE_krb5;
262 errpkt.text.length = 0;
263 if (e_text != NULL) {
264 errpkt.text = smb_krb5_make_data(discard_const_p(char, e_text), strlen(e_text));
267 errpkt.e_data = smb_krb5_make_data(NULL, 0);
268 if (e_data != NULL) {
269 errpkt.e_data = *e_data;
272 errpkt.client = client;
274 if (server != NULL) {
275 errpkt.server = server;
276 } else {
277 code = smb_krb5_make_principal(context,
278 &unspec_server,
279 "<unspecified realm>",
280 NULL);
281 if (code != 0) {
282 return code;
284 errpkt.server = unspec_server;
287 code = krb5_mk_error(context,
288 &errpkt,
289 enc_err);
290 krb5_free_principal(context, unspec_server);
291 #endif
292 return code;
296 * @brief Create a keyblock based on input parameters
298 * @param context The krb5_context
299 * @param host_princ The krb5_principal to use
300 * @param salt The optional salt, if omitted, salt is calculated with
301 * the provided principal.
302 * @param password The krb5_data containing the password
303 * @param enctype The krb5_enctype to use for the keyblock generation
304 * @param key The returned krb5_keyblock, caller needs to free with
305 * krb5_free_keyblock().
307 * @return krb5_error_code
309 int smb_krb5_create_key_from_string(krb5_context context,
310 krb5_const_principal host_princ,
311 const krb5_data *salt,
312 const krb5_data *password,
313 krb5_enctype enctype,
314 krb5_keyblock *key)
316 int ret = 0;
318 if (host_princ == NULL && salt == NULL) {
319 return -1;
322 if ((int)enctype == (int)ENCTYPE_ARCFOUR_HMAC) {
323 TALLOC_CTX *frame = talloc_stackframe();
324 uint8_t *utf16 = NULL;
325 size_t utf16_size = 0;
326 uint8_t nt_hash[16];
327 bool ok;
329 ok = convert_string_talloc(frame, CH_UNIX, CH_UTF16LE,
330 password->data, password->length,
331 &utf16, &utf16_size);
332 if (!ok) {
333 if (errno == 0) {
334 errno = EINVAL;
336 ret = errno;
337 TALLOC_FREE(frame);
338 return ret;
341 mdfour(nt_hash, utf16, utf16_size);
342 BURN_PTR_SIZE(utf16, utf16_size);
343 ret = smb_krb5_keyblock_init_contents(context,
344 ENCTYPE_ARCFOUR_HMAC,
345 nt_hash,
346 sizeof(nt_hash),
347 key);
348 ZERO_STRUCT(nt_hash);
349 if (ret != 0) {
350 TALLOC_FREE(frame);
351 return ret;
354 TALLOC_FREE(frame);
355 return 0;
358 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_C_STRING_TO_KEY)
359 {/* MIT */
360 krb5_data _salt;
362 if (salt == NULL) {
363 ret = krb5_principal2salt(context, host_princ, &_salt);
364 if (ret) {
365 DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
366 return ret;
368 } else {
369 _salt = *salt;
371 ret = krb5_c_string_to_key(context, enctype, password, &_salt, key);
372 if (salt == NULL) {
373 SAFE_FREE(_salt.data);
376 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
377 {/* Heimdal */
378 krb5_salt _salt;
380 if (salt == NULL) {
381 ret = krb5_get_pw_salt(context, host_princ, &_salt);
382 if (ret) {
383 DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
384 return ret;
386 } else {
387 _salt.saltvalue = *salt;
388 _salt.salttype = KRB5_PW_SALT;
391 ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, _salt, key);
392 if (salt == NULL) {
393 krb5_free_salt(context, _salt);
396 #else
397 #error UNKNOWN_CREATE_KEY_FUNCTIONS
398 #endif
399 return ret;
403 * @brief Create a salt for a given principal
405 * @param context The initialized krb5_context
406 * @param host_princ The krb5_principal to create the salt for
407 * @param psalt A pointer to a krb5_data struct
409 * caller has to free the contents of psalt with smb_krb5_free_data_contents
410 * when function has succeeded
412 * @return krb5_error_code, returns 0 on success, error code otherwise
415 int smb_krb5_get_pw_salt(krb5_context context,
416 krb5_const_principal host_princ,
417 krb5_data *psalt)
418 #if defined(HAVE_KRB5_GET_PW_SALT)
419 /* Heimdal */
421 int ret;
422 krb5_salt salt;
424 ret = krb5_get_pw_salt(context, host_princ, &salt);
425 if (ret) {
426 return ret;
429 *psalt = salt.saltvalue;
431 return ret;
433 #elif defined(HAVE_KRB5_PRINCIPAL2SALT)
434 /* MIT */
436 return krb5_principal2salt(context, host_princ, psalt);
438 #else
439 #error UNKNOWN_SALT_FUNCTIONS
440 #endif
443 * @brief This constructs the salt principal used by active directory
445 * Most Kerberos encryption types require a salt in order to
446 * calculate the long term private key for user/computer object
447 * based on a password.
449 * The returned _salt_principal is a string in forms like this:
450 * - host/somehost.example.com@EXAMPLE.COM
451 * - SomeAccount@EXAMPLE.COM
452 * - SomePrincipal@EXAMPLE.COM
454 * This is not the form that's used as salt, it's just
455 * the human readable form. It needs to be converted by
456 * smb_krb5_salt_principal2data().
458 * @param[in] realm The realm the user/computer is added too.
460 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
462 * @param[in] userPrincipalName The userPrincipalName attribute of the object
463 * or NULL if not available.
465 * @param[in] uac_flags UF_ACCOUNT_TYPE_MASKed userAccountControl field
467 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
469 * @param[out] _salt_principal The resulting principal as string.
471 * @retval 0 Success; otherwise - Kerberos error codes
473 * @see smb_krb5_salt_principal2data
475 int smb_krb5_salt_principal(krb5_context krb5_ctx,
476 const char *realm,
477 const char *sAMAccountName,
478 const char *userPrincipalName,
479 uint32_t uac_flags,
480 krb5_principal *salt_princ)
482 TALLOC_CTX *frame = talloc_stackframe();
483 char *upper_realm = NULL;
484 const char *principal = NULL;
485 int principal_len = 0;
486 krb5_error_code krb5_ret;
488 *salt_princ = NULL;
490 if (sAMAccountName == NULL) {
491 TALLOC_FREE(frame);
492 return EINVAL;
495 if (realm == NULL) {
496 TALLOC_FREE(frame);
497 return EINVAL;
500 if (uac_flags & ~UF_ACCOUNT_TYPE_MASK) {
502 * catch callers which still
503 * pass 'true'.
505 TALLOC_FREE(frame);
506 return EINVAL;
508 if (uac_flags == 0) {
510 * catch callers which still
511 * pass 'false'.
513 TALLOC_FREE(frame);
514 return EINVAL;
517 upper_realm = strupper_talloc(frame, realm);
518 if (upper_realm == NULL) {
519 TALLOC_FREE(frame);
520 return ENOMEM;
523 /* Many, many thanks to lukeh@padl.com for this
524 * algorithm, described in his Nov 10 2004 mail to
525 * samba-technical@lists.samba.org */
528 * Determine a salting principal
530 if (uac_flags & UF_TRUST_ACCOUNT_MASK) {
531 int computer_len = 0;
533 computer_len = strlen(sAMAccountName);
534 if (sAMAccountName[computer_len-1] == '$') {
535 computer_len -= 1;
538 if (uac_flags & UF_INTERDOMAIN_TRUST_ACCOUNT) {
539 const char *krbtgt = "krbtgt";
540 krb5_ret = krb5_build_principal_ext(krb5_ctx,
541 salt_princ,
542 strlen(upper_realm),
543 upper_realm,
544 strlen(krbtgt),
545 krbtgt,
546 computer_len,
547 sAMAccountName,
549 if (krb5_ret != 0) {
550 TALLOC_FREE(frame);
551 return krb5_ret;
553 } else {
554 const char *host = "host";
555 char *tmp = NULL;
556 char *tmp_lower = NULL;
558 tmp = talloc_asprintf(frame, "%*.*s.%s",
559 computer_len,
560 computer_len,
561 sAMAccountName,
562 realm);
563 if (tmp == NULL) {
564 TALLOC_FREE(frame);
565 return ENOMEM;
568 tmp_lower = strlower_talloc(frame, tmp);
569 if (tmp_lower == NULL) {
570 TALLOC_FREE(frame);
571 return ENOMEM;
574 krb5_ret = krb5_build_principal_ext(krb5_ctx,
575 salt_princ,
576 strlen(upper_realm),
577 upper_realm,
578 strlen(host),
579 host,
580 strlen(tmp_lower),
581 tmp_lower,
583 if (krb5_ret != 0) {
584 TALLOC_FREE(frame);
585 return krb5_ret;
589 } else if (userPrincipalName != NULL) {
591 * We parse the name not only to allow an easy
592 * replacement of the realm (no matter the realm in
593 * the UPN, the salt comes from the upper-case real
594 * realm, but also to correctly provide a salt when
595 * the UPN is host/foo.bar
597 * This can fail for a UPN of the form foo@bar@REALM
598 * (which is accepted by windows) however.
600 krb5_ret = krb5_parse_name(krb5_ctx,
601 userPrincipalName,
602 salt_princ);
604 if (krb5_ret != 0) {
605 TALLOC_FREE(frame);
606 return krb5_ret;
610 * No matter what realm (including none) in the UPN,
611 * the realm is replaced with our upper-case realm
613 krb5_ret = smb_krb5_principal_set_realm(krb5_ctx,
614 *salt_princ,
615 upper_realm);
616 if (krb5_ret != 0) {
617 krb5_free_principal(krb5_ctx, *salt_princ);
618 TALLOC_FREE(frame);
619 return krb5_ret;
621 } else {
622 principal = sAMAccountName;
623 principal_len = strlen(principal);
625 krb5_ret = krb5_build_principal_ext(krb5_ctx,
626 salt_princ,
627 strlen(upper_realm),
628 upper_realm,
629 principal_len,
630 principal,
632 if (krb5_ret != 0) {
633 TALLOC_FREE(frame);
634 return krb5_ret;
638 TALLOC_FREE(frame);
639 return 0;
643 * @brief This constructs the salt principal used by active directory
645 * Most Kerberos encryption types require a salt in order to
646 * calculate the long term private key for user/computer object
647 * based on a password.
649 * The returned _salt_principal is a string in forms like this:
650 * - host/somehost.example.com@EXAMPLE.COM
651 * - SomeAccount@EXAMPLE.COM
652 * - SomePrincipal@EXAMPLE.COM
654 * This is not the form that's used as salt, it's just
655 * the human readable form. It needs to be converted by
656 * smb_krb5_salt_principal2data().
658 * @param[in] realm The realm the user/computer is added too.
660 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
662 * @param[in] userPrincipalName The userPrincipalName attribute of the object
663 * or NULL if not available.
665 * @param[in] uac_flags UF_ACCOUNT_TYPE_MASKed userAccountControl field
667 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
669 * @param[out] _salt_principal The resulting principal as string.
671 * @retval 0 Success; otherwise - Kerberos error codes
673 * @see smb_krb5_salt_principal2data
675 int smb_krb5_salt_principal_str(const char *realm,
676 const char *sAMAccountName,
677 const char *userPrincipalName,
678 uint32_t uac_flags,
679 TALLOC_CTX *mem_ctx,
680 char **_salt_principal_str)
682 krb5_principal salt_principal = NULL;
683 char *salt_principal_malloc;
684 krb5_context krb5_ctx;
685 krb5_error_code krb5_ret
686 = smb_krb5_init_context_common(&krb5_ctx);
687 if (krb5_ret != 0) {
688 DBG_ERR("kerberos init context failed (%s)\n",
689 error_message(krb5_ret));
690 return krb5_ret;
693 krb5_ret = smb_krb5_salt_principal(krb5_ctx,
694 realm,
695 sAMAccountName,
696 userPrincipalName,
697 uac_flags,
698 &salt_principal);
699 if (krb5_ret != 0) {
700 DBG_ERR("unable to create salt principal:%s\n",
701 error_message(krb5_ret));
702 return krb5_ret;
705 krb5_ret = krb5_unparse_name(krb5_ctx, salt_principal,
706 &salt_principal_malloc);
707 if (krb5_ret != 0) {
708 krb5_free_principal(krb5_ctx, salt_principal);
709 DBG_ERR("kerberos unparse of salt principal failed (%s)\n",
710 error_message(krb5_ret));
711 return krb5_ret;
713 krb5_free_principal(krb5_ctx, salt_principal);
714 *_salt_principal_str
715 = talloc_strdup(mem_ctx, salt_principal_malloc);
716 krb5_free_unparsed_name(krb5_ctx, salt_principal_malloc);
718 if (*_salt_principal_str == NULL) {
719 return ENOMEM;
721 return 0;
725 * @brief Converts the salt principal string into the salt data blob
727 * This function takes a salt_principal as string in forms like this:
728 * - host/somehost.example.com@EXAMPLE.COM
729 * - SomeAccount@EXAMPLE.COM
730 * - SomePrincipal@EXAMPLE.COM
732 * It generates values like:
733 * - EXAMPLE.COMhost/somehost.example.com
734 * - EXAMPLE.COMSomeAccount
735 * - EXAMPLE.COMSomePrincipal
737 * @param[in] realm The realm the user/computer is added too.
739 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
741 * @param[in] userPrincipalName The userPrincipalName attribute of the object
742 * or NULL if not available.
744 * @param[in] is_computer The indication of the object includes
745 * objectClass=computer.
747 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
749 * @param[out] _salt_principal The resulting principal as string.
751 * @retval 0 Success; otherwise - Kerberos error codes
753 * @see smb_krb5_salt_principal
755 int smb_krb5_salt_principal2data(krb5_context context,
756 const char *salt_principal,
757 TALLOC_CTX *mem_ctx,
758 char **_salt_data)
760 krb5_error_code ret;
761 krb5_principal salt_princ = NULL;
762 krb5_data salt;
764 *_salt_data = NULL;
766 ret = krb5_parse_name(context, salt_principal, &salt_princ);
767 if (ret != 0) {
768 return ret;
771 ret = smb_krb5_get_pw_salt(context, salt_princ, &salt);
772 krb5_free_principal(context, salt_princ);
773 if (ret != 0) {
774 return ret;
777 *_salt_data = talloc_strndup(mem_ctx,
778 (char *)salt.data,
779 salt.length);
780 smb_krb5_free_data_contents(context, &salt);
781 if (*_salt_data == NULL) {
782 return ENOMEM;
785 return 0;
788 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
790 * @brief Get a list of encryption types allowed for session keys
792 * @param[in] context The library context
794 * @param[in] enctypes An allocated, zero-terminated list of encryption types
796 * This function returns an allocated list of encryption types allowed for
797 * session keys.
799 * Use krb5_free_enctypes() to free the enctypes when it is no longer needed.
801 * @retval 0 Success; otherwise - Kerberos error codes
803 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
804 krb5_enctype **enctypes)
806 return krb5_get_permitted_enctypes(context, enctypes);
808 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
809 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
810 krb5_enctype **enctypes)
812 #ifdef HAVE_KRB5_PDU_NONE_DECL
813 return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, enctypes);
814 #else
815 return krb5_get_default_in_tkt_etypes(context, enctypes);
816 #endif
818 #else
819 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
820 #endif
824 * @brief Convert a string principal name to a Kerberos principal.
826 * @param[in] context The library context
828 * @param[in] name The principal as a unix charset string.
830 * @param[out] principal The newly allocated principal.
832 * Use krb5_free_principal() to free a principal when it is no longer needed.
834 * @return 0 on success, a Kerberos error code otherwise.
836 krb5_error_code smb_krb5_parse_name(krb5_context context,
837 const char *name,
838 krb5_principal *principal)
840 krb5_error_code ret;
841 char *utf8_name;
842 size_t converted_size;
843 TALLOC_CTX *frame = talloc_stackframe();
845 if (!push_utf8_talloc(frame, &utf8_name, name, &converted_size)) {
846 talloc_free(frame);
847 return ENOMEM;
850 ret = krb5_parse_name(context, utf8_name, principal);
851 if (ret == KRB5_PARSE_MALFORMED) {
852 ret = krb5_parse_name_flags(context, utf8_name,
853 KRB5_PRINCIPAL_PARSE_ENTERPRISE,
854 principal);
856 TALLOC_FREE(frame);
857 return ret;
861 * @brief Convert a Kerberos principal structure to a string representation.
863 * The resulting string representation will be a unix charset name and is
864 * talloc'ed.
866 * @param[in] mem_ctx The talloc context to allocate memory on.
868 * @param[in] context The library context.
870 * @param[in] principal The principal.
872 * @param[out] unix_name A string representation of the principal name as with
873 * unix charset.
875 * Use talloc_free() to free the string representation if it is no longer
876 * needed.
878 * @return 0 on success, a Kerberos error code otherwise.
880 krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
881 krb5_context context,
882 krb5_const_principal principal,
883 char **unix_name)
885 krb5_error_code ret;
886 char *utf8_name;
887 size_t converted_size;
889 *unix_name = NULL;
890 ret = krb5_unparse_name(context, principal, &utf8_name);
891 if (ret) {
892 return ret;
895 if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
896 krb5_free_unparsed_name(context, utf8_name);
897 return ENOMEM;
899 krb5_free_unparsed_name(context, utf8_name);
900 return 0;
904 * @brief Free the contents of a krb5_data structure and zero the data field.
906 * @param[in] context The krb5 context
908 * @param[in] pdata The data structure to free contents of
910 * This function frees the contents, not the structure itself.
912 void smb_krb5_free_data_contents(krb5_context context, krb5_data *pdata)
914 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
915 if (pdata->data) {
916 krb5_free_data_contents(context, pdata);
918 #elif defined(HAVE_KRB5_DATA_FREE)
919 krb5_data_free(context, pdata);
920 #else
921 SAFE_FREE(pdata->data);
922 #endif
926 * @brief copy a buffer into a krb5_data struct
928 * @param[in] p The krb5_data
929 * @param[in] data The data to copy
930 * @param[in] length The length of the data to copy
931 * @return krb5_error_code
933 * Caller has to free krb5_data with smb_krb5_free_data_contents().
935 krb5_error_code smb_krb5_copy_data_contents(krb5_data *p,
936 const void *data,
937 size_t len)
939 #if defined(HAVE_KRB5_DATA_COPY)
940 return krb5_data_copy(p, data, len);
941 #else
942 if (len) {
943 p->data = malloc(len);
944 if (p->data == NULL) {
945 return ENOMEM;
947 memmove(p->data, data, len);
948 } else {
949 p->data = NULL;
951 p->length = len;
952 p->magic = KV5M_DATA;
953 return 0;
954 #endif
958 * @brief put a buffer reference into a krb5_data struct
960 * @param[in] data The data to reference
961 * @param[in] length The length of the data to reference
962 * @return krb5_data
964 * Caller should not free krb5_data.
966 krb5_data smb_krb5_make_data(void *data,
967 size_t len)
969 krb5_data d;
971 #ifdef SAMBA4_USES_HEIMDAL
972 d.data = (uint8_t *)data;
973 d.length = len;
974 #else
975 d.magic = KV5M_DATA;
976 d.data = data;
977 d.length = len;
978 #endif
979 return d;
982 krb5_data smb_krb5_data_from_blob(DATA_BLOB blob)
984 return smb_krb5_make_data(blob.data, blob.length);
987 bool smb_krb5_get_smb_session_key(TALLOC_CTX *mem_ctx,
988 krb5_context context,
989 krb5_auth_context auth_context,
990 DATA_BLOB *session_key,
991 bool remote)
993 krb5_keyblock *skey = NULL;
994 krb5_error_code err = 0;
995 bool ret = false;
997 if (remote) {
998 #ifdef HAVE_KRB5_AUTH_CON_GETRECVSUBKEY
999 err = krb5_auth_con_getrecvsubkey(context,
1000 auth_context,
1001 &skey);
1002 #else /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
1003 err = krb5_auth_con_getremotesubkey(context,
1004 auth_context, &skey);
1005 #endif /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
1006 } else {
1007 #ifdef HAVE_KRB5_AUTH_CON_GETSENDSUBKEY
1008 err = krb5_auth_con_getsendsubkey(context,
1009 auth_context,
1010 &skey);
1011 #else /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
1012 err = krb5_auth_con_getlocalsubkey(context,
1013 auth_context, &skey);
1014 #endif /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
1017 if (err || skey == NULL) {
1018 DEBUG(10, ("KRB5 error getting session key %d\n", err));
1019 goto done;
1022 DEBUG(10, ("Got KRB5 session key of length %d\n",
1023 (int)KRB5_KEY_LENGTH(skey)));
1025 *session_key = data_blob_talloc(mem_ctx,
1026 KRB5_KEY_DATA(skey),
1027 KRB5_KEY_LENGTH(skey));
1028 dump_data_pw("KRB5 Session Key:\n",
1029 session_key->data,
1030 session_key->length);
1032 ret = true;
1034 done:
1035 if (skey) {
1036 krb5_free_keyblock(context, skey);
1039 return ret;
1044 * @brief Get talloced string component of a principal
1046 * @param[in] mem_ctx The TALLOC_CTX
1047 * @param[in] context The krb5_context
1048 * @param[in] principal The principal
1049 * @param[in] component The component
1050 * @return string component
1052 * Caller must talloc_free if the return value is not NULL.
1055 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
1056 krb5_context context,
1057 krb5_const_principal principal,
1058 unsigned int component)
1060 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
1061 const char *str = NULL;
1063 str = krb5_principal_get_comp_string(context, principal, component);
1064 if (str == NULL) {
1065 return NULL;
1068 return talloc_strdup(mem_ctx, str);
1069 #else
1070 krb5_data *data;
1072 if (component >= krb5_princ_size(context, principal)) {
1073 return NULL;
1076 data = krb5_princ_component(context, principal, component);
1077 if (data == NULL) {
1078 return NULL;
1081 return talloc_strndup(mem_ctx, data->data, data->length);
1082 #endif
1086 * @brief
1088 * @param[in] ccache_string A string pointing to the cache to renew the ticket
1089 * (e.g. FILE:/tmp/krb5cc_0) or NULL. If the principal
1090 * ccache has not been specified, the default ccache
1091 * will be used.
1093 * @param[in] client_string The client principal string (e.g. user@SAMBA.SITE)
1094 * or NULL. If the principal string has not been
1095 * specified, the principal from the ccache will be
1096 * retrieved.
1098 * @param[in] service_string The service ticket string
1099 * (e.g. krbtgt/SAMBA.SITE@SAMBA.SITE) or NULL. If
1100 * the service ticket is specified, it is parsed
1101 * (with the realm part ignored) and used as the
1102 * server principal of the credential. Otherwise
1103 * the ticket-granting service is used.
1105 * @param[in] expire_time A pointer to store the credentials end time or
1106 * NULL.
1108 * @return 0 on Success, a Kerberos error code otherwise.
1110 krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,
1111 const char *client_string,
1112 const char *service_string,
1113 time_t *expire_time)
1115 krb5_error_code ret;
1116 krb5_context context = NULL;
1117 krb5_ccache ccache = NULL;
1118 krb5_principal client = NULL;
1119 krb5_creds creds, creds_in;
1121 ZERO_STRUCT(creds);
1122 ZERO_STRUCT(creds_in);
1124 ret = smb_krb5_init_context_common(&context);
1125 if (ret) {
1126 DBG_ERR("kerberos init context failed (%s)\n",
1127 error_message(ret));
1128 goto done;
1131 if (!ccache_string) {
1132 ccache_string = krb5_cc_default_name(context);
1135 if (!ccache_string) {
1136 ret = EINVAL;
1137 goto done;
1140 DBG_DEBUG("Using %s as ccache for client '%s' and service '%s'\n",
1141 ccache_string, client_string, service_string);
1143 /* FIXME: we should not fall back to defaults */
1144 ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
1145 if (ret) {
1146 goto done;
1149 if (client_string) {
1150 ret = smb_krb5_parse_name(context, client_string, &client);
1151 if (ret) {
1152 goto done;
1154 } else {
1155 ret = krb5_cc_get_principal(context, ccache, &client);
1156 if (ret) {
1157 goto done;
1161 ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
1162 if (ret) {
1163 DBG_DEBUG("krb5_get_renewed_creds using ccache '%s' "
1164 "for client '%s' and service '%s' failed: %s\n",
1165 ccache_string, client_string, service_string,
1166 error_message(ret));
1167 goto done;
1170 /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
1171 ret = krb5_cc_initialize(context, ccache, client);
1172 if (ret) {
1173 goto done;
1176 ret = krb5_cc_store_cred(context, ccache, &creds);
1178 if (expire_time) {
1179 *expire_time = (time_t) creds.times.endtime;
1182 done:
1183 krb5_free_cred_contents(context, &creds_in);
1184 krb5_free_cred_contents(context, &creds);
1186 if (client) {
1187 krb5_free_principal(context, client);
1189 if (ccache) {
1190 krb5_cc_close(context, ccache);
1192 if (context) {
1193 krb5_free_context(context);
1196 return ret;
1200 * @brief Free the data stored in an smb_krb5_addresses structure.
1202 * @param[in] context The library context
1204 * @param[in] addr The address structure to free.
1206 * @return 0 on success, a Kerberos error code otherwise.
1208 krb5_error_code smb_krb5_free_addresses(krb5_context context,
1209 smb_krb5_addresses *addr)
1211 krb5_error_code ret = 0;
1212 if (addr == NULL) {
1213 return ret;
1215 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1216 krb5_free_addresses(context, addr->addrs);
1217 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1218 ret = krb5_free_addresses(context, addr->addrs);
1219 SAFE_FREE(addr->addrs);
1220 #endif
1221 SAFE_FREE(addr);
1222 addr = NULL;
1223 return ret;
1226 #define MAX_NETBIOSNAME_LEN 16
1229 * @brief Add a netbios name to the array of addresses
1231 * @param[in] kerb_addr A pointer to the smb_krb5_addresses to add the
1232 * netbios name to.
1234 * @param[in] netbios_name The netbios name to add.
1236 * @return 0 on success, a Kerberos error code otherwise.
1238 krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
1239 const char *netbios_name)
1241 krb5_error_code ret = 0;
1242 char buf[MAX_NETBIOSNAME_LEN];
1243 int len;
1244 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1245 krb5_address **addrs = NULL;
1246 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1247 krb5_addresses *addrs = NULL;
1248 #endif
1250 *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1251 if (*kerb_addr == NULL) {
1252 return ENOMEM;
1255 /* temporarily duplicate put_name() code here to avoid dependency
1256 * issues for a 5 lines function */
1257 len = strlen(netbios_name);
1258 memcpy(buf, netbios_name,
1259 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
1260 if (len < MAX_NETBIOSNAME_LEN - 1) {
1261 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
1263 buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
1265 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1267 int num_addr = 2;
1269 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1270 if (addrs == NULL) {
1271 SAFE_FREE(*kerb_addr);
1272 return ENOMEM;
1275 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1277 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1278 if (addrs[0] == NULL) {
1279 SAFE_FREE(addrs);
1280 SAFE_FREE(*kerb_addr);
1281 return ENOMEM;
1284 addrs[0]->magic = KV5M_ADDRESS;
1285 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1286 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1287 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1288 if (addrs[0]->contents == NULL) {
1289 SAFE_FREE(addrs[0]);
1290 SAFE_FREE(addrs);
1291 SAFE_FREE(*kerb_addr);
1292 return ENOMEM;
1295 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1297 addrs[1] = NULL;
1299 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1301 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1302 if (addrs == NULL) {
1303 SAFE_FREE(*kerb_addr);
1304 return ENOMEM;
1307 memset(addrs, 0, sizeof(krb5_addresses));
1309 addrs->len = 1;
1310 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1311 if (addrs->val == NULL) {
1312 SAFE_FREE(addrs);
1313 SAFE_FREE(*kerb_addr);
1314 return ENOMEM;
1317 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1318 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1319 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1320 if (addrs->val[0].address.data == NULL) {
1321 SAFE_FREE(addrs->val);
1322 SAFE_FREE(addrs);
1323 SAFE_FREE(*kerb_addr);
1324 return ENOMEM;
1327 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1329 #else
1330 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1331 #endif
1332 (*kerb_addr)->addrs = addrs;
1334 return ret;
1338 * @brief Get the enctype from a key table entry
1340 * @param[in] kt_entry Key table entry to get the enctype from.
1342 * @return The enctype from the entry.
1344 krb5_enctype smb_krb5_kt_get_enctype_from_entry(krb5_keytab_entry *kt_entry)
1346 return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1350 * @brief Free the contents of a key table entry.
1352 * @param[in] context The library context.
1354 * @param[in] kt_entry The key table entry to free the contents of.
1356 * @return 0 on success, a Kerberos error code otherwise.
1358 * The pointer itself is not freed.
1360 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1361 krb5_keytab_entry *kt_entry)
1363 /* Try krb5_free_keytab_entry_contents first, since
1364 * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1365 * krb5_kt_free_entry but only has a prototype for the first, while the
1366 * second is considered private.
1368 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1369 return krb5_free_keytab_entry_contents(context, kt_entry);
1370 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1371 return krb5_kt_free_entry(context, kt_entry);
1372 #else
1373 #error UNKNOWN_KT_FREE_FUNCTION
1374 #endif
1379 * @brief Convert an encryption type to a string.
1381 * @param[in] context The library context.
1383 * @param[in] enctype The encryption type.
1385 * @param[in] etype_s A pointer to store the allocated encryption type as a
1386 * string.
1388 * @return 0 on success, a Kerberos error code otherwise.
1390 * The caller needs to free the allocated string etype_s.
1392 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1393 krb5_enctype enctype,
1394 char **etype_s)
1396 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1397 return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1398 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1399 char buf[256];
1400 krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1401 if (ret) {
1402 return ret;
1404 *etype_s = SMB_STRDUP(buf);
1405 if (!*etype_s) {
1406 return ENOMEM;
1408 return ret;
1409 #else
1410 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1411 #endif
1414 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1415 #ifndef MAX_KEYTAB_NAME_LEN
1416 #define MAX_KEYTAB_NAME_LEN 1100
1417 #endif
1420 * @brief Open a key table readonly or with readwrite access.
1422 * Allows one to use a different keytab than the default one using a relative
1423 * path to the keytab.
1425 * @param[in] context The library context
1427 * @param[in] keytab_name_req The path to the key table.
1429 * @param[in] write_access Open with readwrite access.
1431 * @param[in] keytab A pointer to the opened key table.
1433 * The keytab pointer should be freed using krb5_kt_close().
1435 * @return 0 on success, a Kerberos error code otherwise.
1437 krb5_error_code smb_krb5_kt_open_relative(krb5_context context,
1438 const char *keytab_name_req,
1439 bool write_access,
1440 krb5_keytab *keytab)
1442 krb5_error_code ret = 0;
1443 TALLOC_CTX *mem_ctx;
1444 char keytab_string[MAX_KEYTAB_NAME_LEN];
1445 char *kt_str = NULL;
1446 bool found_valid_name = false;
1447 const char *pragma = "FILE";
1448 const char *tmp = NULL;
1450 if (!write_access && !keytab_name_req) {
1451 /* caller just wants to read the default keytab readonly, so be it */
1452 return krb5_kt_default(context, keytab);
1455 mem_ctx = talloc_init("smb_krb5_kt_open_relative");
1456 if (!mem_ctx) {
1457 return ENOMEM;
1460 #ifdef HAVE_WRFILE_KEYTAB
1461 if (write_access) {
1462 pragma = "WRFILE";
1464 #endif
1466 if (keytab_name_req) {
1468 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1469 ret = KRB5_CONFIG_NOTENUFSPACE;
1470 goto out;
1473 if ((strncmp(keytab_name_req, "WRFILE:", 7) == 0) ||
1474 (strncmp(keytab_name_req, "FILE:", 5) == 0)) {
1475 tmp = keytab_name_req;
1476 goto resolve;
1479 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1480 if (!tmp) {
1481 ret = ENOMEM;
1482 goto out;
1485 goto resolve;
1488 /* we need to handle more complex keytab_strings, like:
1489 * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1491 ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1492 if (ret) {
1493 goto out;
1496 DBG_DEBUG("krb5_kt_default_name returned %s\n", keytab_string);
1498 tmp = talloc_strdup(mem_ctx, keytab_string);
1499 if (!tmp) {
1500 ret = ENOMEM;
1501 goto out;
1504 if (strncmp(tmp, "ANY:", 4) == 0) {
1505 tmp += 4;
1508 memset(&keytab_string, '\0', sizeof(keytab_string));
1510 while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1511 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1512 found_valid_name = true;
1513 tmp = kt_str;
1514 tmp += 7;
1517 if (strncmp(kt_str, "FILE:", 5) == 0) {
1518 found_valid_name = true;
1519 tmp = kt_str;
1520 tmp += 5;
1523 if (tmp[0] == '/') {
1524 /* Treat as a FILE: keytab definition. */
1525 found_valid_name = true;
1528 if (found_valid_name) {
1529 if (tmp[0] != '/') {
1530 ret = KRB5_KT_BADNAME;
1531 goto out;
1534 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1535 if (!tmp) {
1536 ret = ENOMEM;
1537 goto out;
1539 break;
1543 if (!found_valid_name) {
1544 ret = KRB5_KT_UNKNOWN_TYPE;
1545 goto out;
1548 resolve:
1549 DBG_DEBUG("resolving: %s\n", tmp);
1550 ret = krb5_kt_resolve(context, tmp, keytab);
1552 out:
1553 TALLOC_FREE(mem_ctx);
1554 return ret;
1558 * @brief Open a key table readonly or with readwrite access.
1560 * Allows one to use a different keytab than the default one. The path needs to be
1561 * an absolute path or an error will be returned.
1563 * @param[in] context The library context
1565 * @param[in] keytab_name_req The path to the key table.
1567 * @param[in] write_access Open with readwrite access.
1569 * @param[in] keytab A pointer to the opened key table.
1571 * The keytab pointer should be freed using krb5_kt_close().
1573 * @return 0 on success, a Kerberos error code otherwise.
1575 krb5_error_code smb_krb5_kt_open(krb5_context context,
1576 const char *keytab_name_req,
1577 bool write_access,
1578 krb5_keytab *keytab)
1580 int cmp;
1582 if (keytab_name_req == NULL) {
1583 return KRB5_KT_BADNAME;
1586 if (keytab_name_req[0] == '/') {
1587 goto open_keytab;
1590 cmp = strncmp(keytab_name_req, "FILE:/", 6);
1591 if (cmp == 0) {
1592 goto open_keytab;
1595 cmp = strncmp(keytab_name_req, "WRFILE:/", 8);
1596 if (cmp == 0) {
1597 goto open_keytab;
1600 DBG_WARNING("ERROR: Invalid keytab name: %s\n", keytab_name_req);
1602 return KRB5_KT_BADNAME;
1604 open_keytab:
1605 return smb_krb5_kt_open_relative(context,
1606 keytab_name_req,
1607 write_access,
1608 keytab);
1612 * @brief Get a key table name.
1614 * @param[in] mem_ctx The talloc context to use for allocation.
1616 * @param[in] context The library context.
1618 * @param[in] keytab The key table to get the name from.
1620 * @param[in] keytab_name A talloc'ed string of the key table name.
1622 * The talloc'ed name string needs to be freed with talloc_free().
1624 * @return 0 on success, a Kerberos error code otherwise.
1626 krb5_error_code smb_krb5_kt_get_name(TALLOC_CTX *mem_ctx,
1627 krb5_context context,
1628 krb5_keytab keytab,
1629 const char **keytab_name)
1631 char keytab_string[MAX_KEYTAB_NAME_LEN];
1632 krb5_error_code ret = 0;
1634 ret = krb5_kt_get_name(context, keytab,
1635 keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1636 if (ret) {
1637 return ret;
1640 *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1641 if (!*keytab_name) {
1642 return ENOMEM;
1645 return ret;
1649 * @brief Seek and delete old entries in a keytab based on the passed
1650 * principal.
1652 * @param[in] context The KRB5 context to use.
1654 * @param[in] keytab The keytab to operate on.
1656 * @param[in] keep_old_kvno Keep the entries with the previous kvno.
1658 * @param[in] kvno The kvno to use.
1660 * @param[in] enctype_only Only evaluate the enctype argument if true
1662 * @param[in] enctype Only search for entries with the specified enctype
1664 * @param[in] princ_s The principal as a string to search for.
1666 * @param[in] princ The principal as a krb5_principal to search for.
1668 * @param[in] flush Whether to flush the complete keytab.
1670 * @retval 0 on Success
1672 * @return An appropriate KRB5 error code.
1674 krb5_error_code smb_krb5_kt_seek_and_delete_old_entries(krb5_context context,
1675 krb5_keytab keytab,
1676 bool keep_old_kvno,
1677 krb5_kvno kvno,
1678 bool enctype_only,
1679 krb5_enctype enctype,
1680 const char *princ_s,
1681 krb5_principal princ,
1682 bool flush)
1684 krb5_error_code ret;
1685 krb5_kt_cursor cursor;
1686 krb5_keytab_entry kt_entry;
1687 char *ktprinc = NULL;
1688 krb5_kvno old_kvno = kvno - 1;
1689 TALLOC_CTX *tmp_ctx;
1691 if (flush) {
1692 SMB_ASSERT(!keep_old_kvno);
1693 SMB_ASSERT(!enctype_only);
1694 SMB_ASSERT(princ_s == NULL);
1695 SMB_ASSERT(princ == NULL);
1696 } else {
1697 SMB_ASSERT(princ_s != NULL);
1698 SMB_ASSERT(princ != NULL);
1701 ZERO_STRUCT(cursor);
1702 ZERO_STRUCT(kt_entry);
1705 * Start with talloc_new() and only then call krb5_kt_start_seq_get().
1706 * If any of them fails, the cleanup code is simpler.
1708 tmp_ctx = talloc_new(NULL);
1709 if (tmp_ctx == NULL) {
1710 return ENOMEM;
1713 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1714 if (ret == KRB5_KT_END || ret == ENOENT ) {
1715 /* no entries */
1716 talloc_free(tmp_ctx);
1717 return 0;
1720 DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1721 while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1722 bool name_ok = false;
1723 krb5_enctype kt_entry_enctype =
1724 smb_krb5_kt_get_enctype_from_entry(&kt_entry);
1726 if (princ_s != NULL) {
1727 ret = smb_krb5_unparse_name(tmp_ctx, context,
1728 kt_entry.principal,
1729 &ktprinc);
1730 if (ret) {
1731 DEBUG(1, (__location__
1732 ": smb_krb5_unparse_name failed "
1733 "(%s)\n", error_message(ret)));
1734 goto out;
1737 #ifdef HAVE_KRB5_KT_COMPARE
1738 name_ok = krb5_kt_compare(context, &kt_entry,
1739 princ, 0, 0);
1740 #else
1741 name_ok = (strcmp(ktprinc, princ_s) == 0);
1742 #endif
1744 if (!name_ok) {
1745 DEBUG(10, (__location__ ": ignoring keytab "
1746 "entry principal %s, kvno = %d\n",
1747 ktprinc, kt_entry.vno));
1749 /* Not a match,
1750 * just free this entry and continue. */
1751 ret = smb_krb5_kt_free_entry(context,
1752 &kt_entry);
1753 ZERO_STRUCT(kt_entry);
1754 if (ret) {
1755 DEBUG(1, (__location__
1756 ": smb_krb5_kt_free_entry "
1757 "failed (%s)\n",
1758 error_message(ret)));
1759 goto out;
1762 TALLOC_FREE(ktprinc);
1763 continue;
1766 TALLOC_FREE(ktprinc);
1769 /*------------------------------------------------------------
1770 * Save the entries with kvno - 1. This is what microsoft does
1771 * to allow people with existing sessions that have kvno - 1
1772 * to still work. Otherwise, when the password for the machine
1773 * changes, all kerberized sessions will 'break' until either
1774 * the client reboots or the client's session key expires and
1775 * they get a new session ticket with the new kvno.
1776 * Some keytab files only store the kvno in 8bits, limit
1777 * the compare accordingly.
1780 if (keep_old_kvno && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1781 DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1782 "entry for principal: %s.\n",
1783 old_kvno,
1784 princ_s != NULL ? princ_s : "UNKNOWN"));
1785 continue;
1788 if (enctype_only &&
1789 ((kt_entry.vno & 0xff) == (kvno & 0xff)) &&
1790 (kt_entry_enctype != enctype))
1792 DEBUG(5, (__location__ ": Saving entry with kvno [%d] "
1793 "enctype [%d] for principal: %s.\n",
1794 kvno, kt_entry_enctype,
1795 princ_s != NULL ? princ_s : "UNKNOWN"));
1796 continue;
1799 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1800 "(kvno %d) - trying to remove it.\n",
1801 princ_s != NULL ? princ_s : "UNKNOWN",
1802 kt_entry.vno));
1804 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1805 ZERO_STRUCT(cursor);
1806 if (ret) {
1807 DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1808 "failed (%s)\n", error_message(ret)));
1809 goto out;
1811 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1812 if (ret) {
1813 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1814 "failed (%s)\n", error_message(ret)));
1815 goto out;
1818 DEBUG(5, (__location__ ": removed old entry for principal: "
1819 "%s (kvno %d).\n",
1820 princ_s != NULL ? princ_s : "UNKNOWN",
1821 kt_entry.vno));
1823 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1824 if (ret) {
1825 DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1826 "(%s)\n", error_message(ret)));
1827 goto out;
1829 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1830 ZERO_STRUCT(kt_entry);
1831 if (ret) {
1832 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1833 "failed (%s)\n", error_message(ret)));
1834 goto out;
1838 out:
1839 talloc_free(tmp_ctx);
1840 if (!all_zero((uint8_t *)&kt_entry, sizeof(kt_entry))) {
1841 smb_krb5_kt_free_entry(context, &kt_entry);
1843 if (!all_zero((uint8_t *)&cursor, sizeof(cursor))) {
1844 krb5_kt_end_seq_get(context, keytab, &cursor);
1846 return ret;
1850 * @brief Add a keytab entry for the given principal
1852 * @param[in] context The krb5 context to use.
1854 * @param[in] keytab The keytab to add the entry to.
1856 * @param[in] kvno The kvno to use.
1858 * @param[in] princ_s The principal as a string.
1860 * @param[in] salt_principal The salt principal to salt the password with.
1861 * Only needed for keys which support salting.
1862 * If no salt is used set no_salt to false and
1863 * pass NULL here.
1865 * @param[in] enctype The encryption type of the keytab entry.
1867 * @param[in] password The password of the keytab entry.
1869 * @param[in] no_salt If the password should not be salted. Normally
1870 * this is only set to false for encryption types
1871 * which do not support salting like RC4.
1873 * @retval 0 on Success
1875 * @return A corresponding KRB5 error code.
1877 * @see smb_krb5_kt_open()
1879 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1880 krb5_keytab keytab,
1881 krb5_kvno kvno,
1882 const char *princ_s,
1883 const char *salt_principal,
1884 krb5_enctype enctype,
1885 krb5_data *password,
1886 bool no_salt)
1888 krb5_error_code ret;
1889 krb5_keytab_entry kt_entry;
1890 krb5_principal princ = NULL;
1891 krb5_keyblock *keyp;
1893 ZERO_STRUCT(kt_entry);
1895 ret = smb_krb5_parse_name(context, princ_s, &princ);
1896 if (ret) {
1897 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1898 "failed (%s)\n", princ_s, error_message(ret)));
1899 goto out;
1902 /* Seek and delete old keytab entries */
1903 ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1904 keytab,
1905 true, /* keep_old_kvno */
1906 kvno,
1907 true, /* enctype_only */
1908 enctype,
1909 princ_s,
1910 princ,
1911 false); /* flush */
1912 if (ret) {
1913 goto out;
1916 /* If we get here, we have deleted all the old entries with kvno's
1917 * not equal to the current kvno-1. */
1919 keyp = KRB5_KT_KEY(&kt_entry);
1921 if (no_salt) {
1922 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1923 if (KRB5_KEY_DATA(keyp) == NULL) {
1924 ret = ENOMEM;
1925 goto out;
1927 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1928 KRB5_KEY_LENGTH(keyp) = password->length;
1929 KRB5_KEY_TYPE(keyp) = enctype;
1930 } else {
1931 krb5_principal salt_princ = NULL;
1933 /* Now add keytab entries for all encryption types */
1934 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1935 if (ret) {
1936 DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1937 salt_principal, error_message(ret));
1938 goto out;
1941 ret = smb_krb5_create_key_from_string(context,
1942 salt_princ,
1943 NULL,
1944 password,
1945 enctype,
1946 keyp);
1947 krb5_free_principal(context, salt_princ);
1948 if (ret != 0) {
1949 goto out;
1953 kt_entry.principal = princ;
1954 kt_entry.vno = kvno;
1956 DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1957 "encryption type (%d) and version (%d)\n",
1958 princ_s, enctype, kt_entry.vno));
1959 ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1960 krb5_free_keyblock_contents(context, keyp);
1961 ZERO_STRUCT(kt_entry);
1962 if (ret) {
1963 DEBUG(1, (__location__ ": adding entry to keytab "
1964 "failed (%s)\n", error_message(ret)));
1965 goto out;
1968 out:
1969 if (princ) {
1970 krb5_free_principal(context, princ);
1973 return ret;
1976 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1977 defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1978 defined(HAVE_KRB5_GET_CREDS)
1979 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1980 krb5_ccache ccache,
1981 krb5_principal me,
1982 krb5_principal server,
1983 krb5_principal impersonate_princ,
1984 krb5_creds **out_creds)
1986 krb5_error_code ret;
1987 krb5_get_creds_opt opt;
1989 ret = krb5_get_creds_opt_alloc(context, &opt);
1990 if (ret) {
1991 goto done;
1993 krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1995 if (impersonate_princ) {
1996 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1997 impersonate_princ);
1998 if (ret) {
1999 goto done;
2003 ret = krb5_get_creds(context, opt, ccache, server, out_creds);
2004 if (ret) {
2005 goto done;
2008 done:
2009 if (opt) {
2010 krb5_get_creds_opt_free(context, opt);
2012 return ret;
2014 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
2016 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
2018 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
2019 krb5_error_code KRB5_CALLCONV
2020 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
2021 krb5_ccache ccache, krb5_creds *in_creds,
2022 krb5_data *subject_cert,
2023 krb5_creds **out_creds);
2024 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
2026 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
2027 krb5_ccache ccache,
2028 krb5_principal me,
2029 krb5_principal server,
2030 krb5_principal impersonate_princ,
2031 krb5_creds **out_creds)
2033 krb5_error_code ret;
2034 krb5_creds in_creds;
2036 ZERO_STRUCT(in_creds);
2038 if (impersonate_princ) {
2040 in_creds.server = me;
2041 in_creds.client = impersonate_princ;
2043 ret = krb5_get_credentials_for_user(context,
2044 0, /* krb5_flags options */
2045 ccache,
2046 &in_creds,
2047 NULL, /* krb5_data *subject_cert */
2048 out_creds);
2049 } else {
2050 in_creds.client = me;
2051 in_creds.server = server;
2053 ret = krb5_get_credentials(context, 0, ccache,
2054 &in_creds, out_creds);
2057 return ret;
2059 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
2062 * smb_krb5_get_credentials
2064 * @brief Get krb5 credentials for a server
2066 * @param[in] context An initialized krb5_context
2067 * @param[in] ccache An initialized krb5_ccache
2068 * @param[in] me The krb5_principal of the caller
2069 * @param[in] server The krb5_principal of the requested service
2070 * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
2071 * @param[out] out_creds The returned krb5_creds structure
2072 * @return krb5_error_code
2075 krb5_error_code smb_krb5_get_credentials(krb5_context context,
2076 krb5_ccache ccache,
2077 krb5_principal me,
2078 krb5_principal server,
2079 krb5_principal impersonate_princ,
2080 krb5_creds **out_creds)
2082 krb5_error_code ret;
2083 krb5_creds *creds = NULL;
2085 if (out_creds != NULL) {
2086 *out_creds = NULL;
2089 if (impersonate_princ) {
2090 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
2091 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
2092 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
2093 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
2094 #else
2095 ret = ENOTSUP;
2096 #endif
2097 } else {
2098 krb5_creds in_creds;
2100 ZERO_STRUCT(in_creds);
2102 in_creds.client = me;
2103 in_creds.server = server;
2105 ret = krb5_get_credentials(context, 0, ccache,
2106 &in_creds, &creds);
2108 if (ret) {
2109 goto done;
2112 if (out_creds) {
2113 *out_creds = creds;
2116 done:
2117 if (creds && ret) {
2118 krb5_free_creds(context, creds);
2121 return ret;
2125 * @brief Initialize a krb5_keyblock with the given data.
2127 * Initializes a new keyblock, allocates the contents for the key and
2128 * copies the data into the keyblock.
2130 * @param[in] context The library context
2132 * @param[in] enctype The encryption type.
2134 * @param[in] data The date to initialize the keyblock with.
2136 * @param[in] length The length of the keyblock.
2138 * @param[in] key Newly allocated keyblock structure.
2140 * The key date must be freed using krb5_free_keyblock_contents() when it is
2141 * no longer needed.
2143 * @return 0 on success, a Kerberos error code otherwise.
2145 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
2146 krb5_enctype enctype,
2147 const void *data,
2148 size_t length,
2149 krb5_keyblock *key)
2151 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
2152 return krb5_keyblock_init(context, enctype, data, length, key);
2153 #else
2154 memset(key, 0, sizeof(krb5_keyblock));
2155 KRB5_KEY_DATA(key) = SMB_MALLOC(length);
2156 if (NULL == KRB5_KEY_DATA(key)) {
2157 return ENOMEM;
2159 memcpy(KRB5_KEY_DATA(key), data, length);
2160 KRB5_KEY_LENGTH(key) = length;
2161 KRB5_KEY_TYPE(key) = enctype;
2162 return 0;
2163 #endif
2167 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2169 * This function uses a keyblock rather than needing the original password.
2171 * @param[in] ctx The library context
2173 * @param[in] cc The credential cache to put the tgt in.
2175 * @param[in] principal The client princial
2177 * @param[in] keyblock The keyblock to use.
2179 * @param[in] target_service The service name of the initial credentials (or NULL).
2181 * @param[in] krb_options Initial credential options.
2183 * @param[in] expire_time A pointer to store the expiration time of the
2184 * credentials (or NULL).
2186 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2187 * valid (or NULL).
2189 * @return 0 on success, a Kerberos error code otherwise.
2191 krb5_error_code smb_krb5_kinit_keyblock_ccache(krb5_context ctx,
2192 krb5_ccache cc,
2193 krb5_principal principal,
2194 krb5_keyblock *keyblock,
2195 const char *target_service,
2196 krb5_get_init_creds_opt *krb_options,
2197 time_t *expire_time,
2198 time_t *kdc_time)
2200 krb5_error_code code = 0;
2201 krb5_creds my_creds;
2203 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
2204 code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
2205 keyblock, 0, target_service,
2206 krb_options);
2207 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
2209 #define SMB_CREDS_KEYTAB "MEMORY:tmp_kinit_keyblock_ccache"
2210 char tmp_name[64] = {0};
2211 krb5_keytab_entry entry;
2212 krb5_keytab keytab;
2213 int rc;
2215 memset(&entry, 0, sizeof(entry));
2216 entry.principal = principal;
2217 *(KRB5_KT_KEY(&entry)) = *keyblock;
2219 rc = snprintf(tmp_name, sizeof(tmp_name),
2220 "%s-%p",
2221 SMB_CREDS_KEYTAB,
2222 &my_creds);
2223 if (rc < 0) {
2224 return KRB5_KT_BADNAME;
2226 code = krb5_kt_resolve(ctx, tmp_name, &keytab);
2227 if (code) {
2228 return code;
2231 code = krb5_kt_add_entry(ctx, keytab, &entry);
2232 if (code) {
2233 (void)krb5_kt_close(ctx, keytab);
2234 goto done;
2237 code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
2238 keytab, 0, target_service,
2239 krb_options);
2240 (void)krb5_kt_close(ctx, keytab);
2242 #else
2243 #error krb5_get_init_creds_keyblock not available!
2244 #endif
2245 if (code) {
2246 return code;
2249 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2251 * We need to store the principal as returned from the KDC to the
2252 * credentials cache. If we don't do that the KRB5 library is not
2253 * able to find the tickets it is looking for
2255 principal = my_creds.client;
2256 #endif
2257 code = krb5_cc_initialize(ctx, cc, principal);
2258 if (code) {
2259 goto done;
2262 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2263 if (code) {
2264 goto done;
2267 if (expire_time) {
2268 *expire_time = (time_t) my_creds.times.endtime;
2271 if (kdc_time) {
2272 *kdc_time = (time_t) my_creds.times.starttime;
2275 code = 0;
2276 done:
2277 krb5_free_cred_contents(ctx, &my_creds);
2278 return code;
2282 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2284 * @param[in] ctx The library context
2286 * @param[in] cc The credential cache to put the tgt in.
2288 * @param[in] principal The client princial
2290 * @param[in] password The password (or NULL).
2292 * @param[in] target_service The service name of the initial credentials (or NULL).
2294 * @param[in] krb_options Initial credential options.
2296 * @param[in] expire_time A pointer to store the expiration time of the
2297 * credentials (or NULL).
2299 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2300 * valid (or NULL).
2302 * @return 0 on success, a Kerberos error code otherwise.
2304 krb5_error_code smb_krb5_kinit_password_ccache(krb5_context ctx,
2305 krb5_ccache cc,
2306 krb5_principal principal,
2307 const char *password,
2308 const char *target_service,
2309 krb5_get_init_creds_opt *krb_options,
2310 time_t *expire_time,
2311 time_t *kdc_time)
2313 krb5_error_code code = 0;
2314 krb5_creds my_creds;
2316 code = krb5_get_init_creds_password(ctx, &my_creds, principal,
2317 password, NULL, NULL, 0,
2318 target_service, krb_options);
2319 if (code) {
2320 return code;
2324 * We need to store the principal as returned from the KDC to the
2325 * credentials cache. If we don't do that the KRB5 library is not
2326 * able to find the tickets it is looking for
2328 principal = my_creds.client;
2329 code = krb5_cc_initialize(ctx, cc, principal);
2330 if (code) {
2331 goto done;
2334 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2335 if (code) {
2336 goto done;
2339 if (expire_time) {
2340 *expire_time = (time_t) my_creds.times.endtime;
2343 if (kdc_time) {
2344 *kdc_time = (time_t) my_creds.times.starttime;
2347 code = 0;
2348 done:
2349 krb5_free_cred_contents(ctx, &my_creds);
2350 return code;
2353 #ifdef SAMBA4_USES_HEIMDAL
2355 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2357 * @param[in] ctx The library context
2359 * @param[in] cc The credential cache to store the tgt in.
2361 * @param[in] principal The initial client princial.
2363 * @param[in] password The password (or NULL).
2365 * @param[in] impersonate_principal The impersonation principal (or NULL).
2367 * @param[in] self_service The local service for S4U2Self if
2368 * impersonate_principal is specified).
2370 * @param[in] target_service The service name of the initial credentials
2371 * (kpasswd/REALM or a remote service). It defaults
2372 * to the krbtgt if NULL.
2374 * @param[in] krb_options Initial credential options.
2376 * @param[in] expire_time A pointer to store the expiration time of the
2377 * credentials (or NULL).
2379 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2380 * valid (or NULL).
2382 * @return 0 on success, a Kerberos error code otherwise.
2384 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
2385 krb5_ccache store_cc,
2386 krb5_principal init_principal,
2387 const char *init_password,
2388 krb5_principal impersonate_principal,
2389 const char *self_service,
2390 const char *target_service,
2391 krb5_get_init_creds_opt *krb_options,
2392 time_t *expire_time,
2393 time_t *kdc_time)
2395 krb5_error_code code = 0;
2396 krb5_get_creds_opt options;
2397 krb5_principal store_principal;
2398 krb5_creds store_creds;
2399 krb5_creds *s4u2self_creds;
2400 Ticket s4u2self_ticket;
2401 size_t s4u2self_ticketlen;
2402 krb5_creds *s4u2proxy_creds;
2403 krb5_principal self_princ;
2404 bool s4u2proxy;
2405 krb5_principal target_princ;
2406 krb5_ccache tmp_cc;
2407 const char *self_realm;
2408 const char *client_realm = NULL;
2409 krb5_principal blacklist_principal = NULL;
2410 krb5_principal whitelist_principal = NULL;
2412 code = krb5_get_init_creds_password(ctx, &store_creds,
2413 init_principal,
2414 init_password,
2415 NULL, NULL,
2417 NULL,
2418 krb_options);
2419 if (code != 0) {
2420 return code;
2423 store_principal = init_principal;
2426 * We are trying S4U2Self now:
2428 * As we do not want to expose our TGT in the
2429 * krb5_ccache, which is also holds the impersonated creds.
2431 * Some low level krb5/gssapi function might use the TGT
2432 * identity and let the client act as our machine account.
2434 * We need to avoid that and use a temporary krb5_ccache
2435 * in order to pass our TGT to the krb5_get_creds() function.
2437 code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
2438 if (code != 0) {
2439 krb5_free_cred_contents(ctx, &store_creds);
2440 return code;
2443 code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
2444 if (code != 0) {
2445 krb5_cc_destroy(ctx, tmp_cc);
2446 krb5_free_cred_contents(ctx, &store_creds);
2447 return code;
2450 code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
2451 if (code != 0) {
2452 krb5_free_cred_contents(ctx, &store_creds);
2453 krb5_cc_destroy(ctx, tmp_cc);
2454 return code;
2458 * we need to remember the client principal of our
2459 * TGT and make sure the KDC does not return this
2460 * in the impersonated tickets. This can happen
2461 * if the KDC does not support S4U2Self and S4U2Proxy.
2463 blacklist_principal = store_creds.client;
2464 store_creds.client = NULL;
2465 krb5_free_cred_contents(ctx, &store_creds);
2468 * Check if we also need S4U2Proxy or if S4U2Self is
2469 * enough in order to get a ticket for the target.
2471 if (target_service == NULL) {
2472 s4u2proxy = false;
2473 } else if (strcmp(target_service, self_service) == 0) {
2474 s4u2proxy = false;
2475 } else {
2476 s4u2proxy = true;
2480 * For S4U2Self we need our own service principal,
2481 * which belongs to our own realm (available on
2482 * our client principal).
2484 self_realm = krb5_principal_get_realm(ctx, init_principal);
2486 code = krb5_parse_name(ctx, self_service, &self_princ);
2487 if (code != 0) {
2488 krb5_free_principal(ctx, blacklist_principal);
2489 krb5_cc_destroy(ctx, tmp_cc);
2490 return code;
2493 code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2494 if (code != 0) {
2495 krb5_free_principal(ctx, blacklist_principal);
2496 krb5_free_principal(ctx, self_princ);
2497 krb5_cc_destroy(ctx, tmp_cc);
2498 return code;
2501 code = krb5_get_creds_opt_alloc(ctx, &options);
2502 if (code != 0) {
2503 krb5_free_principal(ctx, blacklist_principal);
2504 krb5_free_principal(ctx, self_princ);
2505 krb5_cc_destroy(ctx, tmp_cc);
2506 return code;
2509 if (s4u2proxy) {
2511 * If we want S4U2Proxy, we need the forwardable flag
2512 * on the S4U2Self ticket.
2514 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2517 code = krb5_get_creds_opt_set_impersonate(ctx, options,
2518 impersonate_principal);
2519 if (code != 0) {
2520 krb5_get_creds_opt_free(ctx, options);
2521 krb5_free_principal(ctx, blacklist_principal);
2522 krb5_free_principal(ctx, self_princ);
2523 krb5_cc_destroy(ctx, tmp_cc);
2524 return code;
2527 code = krb5_get_creds(ctx, options, tmp_cc,
2528 self_princ, &s4u2self_creds);
2529 krb5_get_creds_opt_free(ctx, options);
2530 krb5_free_principal(ctx, self_princ);
2531 if (code != 0) {
2532 krb5_free_principal(ctx, blacklist_principal);
2533 krb5_cc_destroy(ctx, tmp_cc);
2534 return code;
2537 if (!s4u2proxy) {
2538 krb5_cc_destroy(ctx, tmp_cc);
2541 * Now make sure we store the impersonated principal
2542 * and creds instead of the TGT related stuff
2543 * in the krb5_ccache of the caller.
2545 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2546 &store_creds);
2547 krb5_free_creds(ctx, s4u2self_creds);
2548 if (code != 0) {
2549 return code;
2553 * It's important to store the principal the KDC
2554 * returned, as otherwise the caller would not find
2555 * the S4U2Self ticket in the krb5_ccache lookup.
2557 store_principal = store_creds.client;
2558 goto store;
2562 * We are trying S4U2Proxy:
2564 * We need the ticket from the S4U2Self step
2565 * and our TGT in order to get the delegated ticket.
2567 code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2568 s4u2self_creds->ticket.length,
2569 &s4u2self_ticket,
2570 &s4u2self_ticketlen);
2571 if (code != 0) {
2572 krb5_free_creds(ctx, s4u2self_creds);
2573 krb5_free_principal(ctx, blacklist_principal);
2574 krb5_cc_destroy(ctx, tmp_cc);
2575 return code;
2579 * we need to remember the client principal of the
2580 * S4U2Self stage and as it needs to match the one we
2581 * will get for the S4U2Proxy stage. We need this
2582 * in order to detect KDCs which does not support S4U2Proxy.
2584 whitelist_principal = s4u2self_creds->client;
2585 s4u2self_creds->client = NULL;
2586 krb5_free_creds(ctx, s4u2self_creds);
2589 * For S4U2Proxy we also got a target service principal,
2590 * which also belongs to our own realm (available on
2591 * our client principal).
2593 code = krb5_parse_name(ctx, target_service, &target_princ);
2594 if (code != 0) {
2595 free_Ticket(&s4u2self_ticket);
2596 krb5_free_principal(ctx, whitelist_principal);
2597 krb5_free_principal(ctx, blacklist_principal);
2598 krb5_cc_destroy(ctx, tmp_cc);
2599 return code;
2602 code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2603 if (code != 0) {
2604 free_Ticket(&s4u2self_ticket);
2605 krb5_free_principal(ctx, target_princ);
2606 krb5_free_principal(ctx, whitelist_principal);
2607 krb5_free_principal(ctx, blacklist_principal);
2608 krb5_cc_destroy(ctx, tmp_cc);
2609 return code;
2612 code = krb5_get_creds_opt_alloc(ctx, &options);
2613 if (code != 0) {
2614 free_Ticket(&s4u2self_ticket);
2615 krb5_free_principal(ctx, target_princ);
2616 krb5_free_principal(ctx, whitelist_principal);
2617 krb5_free_principal(ctx, blacklist_principal);
2618 krb5_cc_destroy(ctx, tmp_cc);
2619 return code;
2622 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2623 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2625 code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2626 free_Ticket(&s4u2self_ticket);
2627 if (code != 0) {
2628 krb5_get_creds_opt_free(ctx, options);
2629 krb5_free_principal(ctx, target_princ);
2630 krb5_free_principal(ctx, whitelist_principal);
2631 krb5_free_principal(ctx, blacklist_principal);
2632 krb5_cc_destroy(ctx, tmp_cc);
2633 return code;
2636 code = krb5_get_creds(ctx, options, tmp_cc,
2637 target_princ, &s4u2proxy_creds);
2638 krb5_get_creds_opt_free(ctx, options);
2639 krb5_free_principal(ctx, target_princ);
2640 krb5_cc_destroy(ctx, tmp_cc);
2641 if (code != 0) {
2642 krb5_free_principal(ctx, whitelist_principal);
2643 krb5_free_principal(ctx, blacklist_principal);
2644 return code;
2648 * Now make sure we store the impersonated principal
2649 * and creds instead of the TGT related stuff
2650 * in the krb5_ccache of the caller.
2652 code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2653 &store_creds);
2654 krb5_free_creds(ctx, s4u2proxy_creds);
2655 if (code != 0) {
2656 krb5_free_principal(ctx, whitelist_principal);
2657 krb5_free_principal(ctx, blacklist_principal);
2658 return code;
2662 * It's important to store the principal the KDC
2663 * returned, as otherwise the caller would not find
2664 * the S4U2Self ticket in the krb5_ccache lookup.
2666 store_principal = store_creds.client;
2668 store:
2669 if (blacklist_principal &&
2670 krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2671 char *sp = NULL;
2672 char *ip = NULL;
2674 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2675 if (code != 0) {
2676 sp = NULL;
2678 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2679 if (code != 0) {
2680 ip = NULL;
2682 DBG_WARNING("KDC returned self principal[%s] while impersonating [%s]\n",
2683 sp?sp:"<no memory>",
2684 ip?ip:"<no memory>");
2686 SAFE_FREE(sp);
2687 SAFE_FREE(ip);
2689 krb5_free_principal(ctx, whitelist_principal);
2690 krb5_free_principal(ctx, blacklist_principal);
2691 krb5_free_cred_contents(ctx, &store_creds);
2692 return KRB5_FWD_BAD_PRINCIPAL;
2694 if (blacklist_principal) {
2695 krb5_free_principal(ctx, blacklist_principal);
2698 if (whitelist_principal &&
2699 !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2700 char *sp = NULL;
2701 char *ep = NULL;
2703 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2704 if (code != 0) {
2705 sp = NULL;
2707 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2708 if (code != 0) {
2709 ep = NULL;
2711 DBG_WARNING("KDC returned wrong principal[%s] we expected [%s]\n",
2712 sp?sp:"<no memory>",
2713 ep?ep:"<no memory>");
2715 SAFE_FREE(sp);
2716 SAFE_FREE(ep);
2718 krb5_free_principal(ctx, whitelist_principal);
2719 krb5_free_cred_contents(ctx, &store_creds);
2720 return KRB5_FWD_BAD_PRINCIPAL;
2722 if (whitelist_principal) {
2723 krb5_free_principal(ctx, whitelist_principal);
2726 code = krb5_cc_initialize(ctx, store_cc, store_principal);
2727 if (code != 0) {
2728 krb5_free_cred_contents(ctx, &store_creds);
2729 return code;
2732 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2733 if (code != 0) {
2734 krb5_free_cred_contents(ctx, &store_creds);
2735 return code;
2738 client_realm = krb5_principal_get_realm(ctx, store_creds.client);
2739 if (client_realm != NULL) {
2741 * Because the CANON flag doesn't have any impact
2742 * on the impersonate_principal => store_creds.client
2743 * realm mapping. We need to store the credentials twice,
2744 * once with the returned realm and once with the
2745 * realm of impersonate_principal.
2747 code = krb5_principal_set_realm(ctx, store_creds.server,
2748 client_realm);
2749 if (code != 0) {
2750 krb5_free_cred_contents(ctx, &store_creds);
2751 return code;
2754 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2755 if (code != 0) {
2756 krb5_free_cred_contents(ctx, &store_creds);
2757 return code;
2761 if (expire_time) {
2762 *expire_time = (time_t) store_creds.times.endtime;
2765 if (kdc_time) {
2766 *kdc_time = (time_t) store_creds.times.starttime;
2769 krb5_free_cred_contents(ctx, &store_creds);
2771 return 0;
2774 #else /* MIT */
2776 static bool princ_compare_no_dollar(krb5_context ctx,
2777 krb5_principal a,
2778 krb5_principal b)
2780 krb5_principal mod = NULL;
2781 bool cmp;
2783 if (a->length == 1 && b->length == 1 &&
2784 a->data[0].length != 0 && b->data[0].length != 0 &&
2785 a->data[0].data[a->data[0].length - 1] !=
2786 b->data[0].data[b->data[0].length - 1]) {
2787 if (a->data[0].data[a->data[0].length - 1] == '$') {
2788 mod = a;
2789 mod->data[0].length--;
2790 } else if (b->data[0].data[b->data[0].length - 1] == '$') {
2791 mod = b;
2792 mod->data[0].length--;
2796 cmp = krb5_principal_compare_flags(ctx,
2799 KRB5_PRINCIPAL_COMPARE_CASEFOLD);
2800 if (mod != NULL) {
2801 mod->data[0].length++;
2804 return cmp;
2807 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
2808 krb5_ccache store_cc,
2809 krb5_principal init_principal,
2810 const char *init_password,
2811 krb5_principal impersonate_principal,
2812 const char *self_service,
2813 const char *target_service,
2814 krb5_get_init_creds_opt *krb_options,
2815 time_t *expire_time,
2816 time_t *kdc_time)
2818 krb5_error_code code;
2819 krb5_principal self_princ = NULL;
2820 krb5_principal target_princ = NULL;
2821 krb5_creds *store_creds = NULL;
2822 krb5_creds *s4u2self_creds = NULL;
2823 krb5_creds *s4u2proxy_creds = NULL;
2824 krb5_creds init_creds = {0};
2825 krb5_creds mcreds = {0};
2826 krb5_flags options = KRB5_GC_NO_STORE;
2827 krb5_ccache tmp_cc;
2828 bool s4u2proxy = false;
2829 bool ok;
2831 code = krb5_cc_new_unique(ctx, "MEMORY", NULL, &tmp_cc);
2832 if (code != 0) {
2833 return code;
2836 code = krb5_get_init_creds_password(ctx,
2837 &init_creds,
2838 init_principal,
2839 init_password,
2840 NULL,
2841 NULL,
2843 NULL,
2844 krb_options);
2845 if (code != 0) {
2846 goto done;
2849 code = krb5_cc_initialize(ctx, tmp_cc, init_creds.client);
2850 if (code != 0) {
2851 goto done;
2854 code = krb5_cc_store_cred(ctx, tmp_cc, &init_creds);
2855 if (code != 0) {
2856 goto done;
2860 * Check if we also need S4U2Proxy or if S4U2Self is
2861 * enough in order to get a ticket for the target.
2863 if (target_service == NULL) {
2864 s4u2proxy = false;
2865 } else if (strcmp(target_service, self_service) == 0) {
2866 s4u2proxy = false;
2867 } else {
2868 s4u2proxy = true;
2871 code = krb5_parse_name(ctx, self_service, &self_princ);
2872 if (code != 0) {
2873 goto done;
2877 * MIT lacks aliases support in S4U, for S4U2Self we require the tgt
2878 * client and the request server to be the same principal name.
2880 ok = princ_compare_no_dollar(ctx, init_creds.client, self_princ);
2881 if (!ok) {
2882 code = KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
2883 goto done;
2886 mcreds.client = impersonate_principal;
2887 mcreds.server = init_creds.client;
2889 code = krb5_get_credentials_for_user(ctx, options, tmp_cc, &mcreds,
2890 NULL, &s4u2self_creds);
2891 if (code != 0) {
2892 goto done;
2895 if (s4u2proxy) {
2896 code = krb5_parse_name(ctx, target_service, &target_princ);
2897 if (code != 0) {
2898 goto done;
2901 mcreds.client = init_creds.client;
2902 mcreds.server = target_princ;
2903 mcreds.second_ticket = s4u2self_creds->ticket;
2905 code = krb5_get_credentials(ctx, options |
2906 KRB5_GC_CONSTRAINED_DELEGATION,
2907 tmp_cc, &mcreds, &s4u2proxy_creds);
2908 if (code != 0) {
2909 goto done;
2912 /* Check KDC support of S4U2Proxy extension */
2913 if (!krb5_principal_compare(ctx, s4u2self_creds->client,
2914 s4u2proxy_creds->client)) {
2915 code = KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
2916 goto done;
2919 store_creds = s4u2proxy_creds;
2920 } else {
2921 store_creds = s4u2self_creds;;
2923 /* We need to save the ticket with the requested server name
2924 * or the caller won't be able to find it in cache. */
2925 if (!krb5_principal_compare(ctx, self_princ,
2926 store_creds->server)) {
2927 krb5_free_principal(ctx, store_creds->server);
2928 store_creds->server = NULL;
2929 code = krb5_copy_principal(ctx, self_princ,
2930 &store_creds->server);
2931 if (code != 0) {
2932 goto done;
2937 code = krb5_cc_initialize(ctx, store_cc, store_creds->client);
2938 if (code != 0) {
2939 goto done;
2942 code = krb5_cc_store_cred(ctx, store_cc, store_creds);
2943 if (code != 0) {
2944 goto done;
2947 if (expire_time) {
2948 *expire_time = (time_t) store_creds->times.endtime;
2951 if (kdc_time) {
2952 *kdc_time = (time_t) store_creds->times.starttime;
2955 done:
2956 krb5_cc_destroy(ctx, tmp_cc);
2957 krb5_free_cred_contents(ctx, &init_creds);
2958 krb5_free_creds(ctx, s4u2self_creds);
2959 krb5_free_creds(ctx, s4u2proxy_creds);
2960 krb5_free_principal(ctx, self_princ);
2961 krb5_free_principal(ctx, target_princ);
2963 return code;
2965 #endif
2967 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2969 * @brief Create a principal name using a variable argument list.
2971 * @param[in] context The library context.
2973 * @param[inout] principal A pointer to the principal structure.
2975 * @param[in] _realm The realm to use. If NULL then the function will
2976 * get the default realm name.
2978 * @param[in] ... A list of 'char *' components, ending with NULL.
2980 * Use krb5_free_principal() to free the principal when it is no longer needed.
2982 * @return 0 on success, a Kerberos error code otherwise.
2984 krb5_error_code smb_krb5_make_principal(krb5_context context,
2985 krb5_principal *principal,
2986 const char *_realm, ...)
2988 krb5_error_code code;
2989 bool free_realm;
2990 char *realm;
2991 va_list ap;
2993 if (_realm) {
2994 realm = discard_const_p(char, _realm);
2995 free_realm = false;
2996 } else {
2997 code = krb5_get_default_realm(context, &realm);
2998 if (code) {
2999 return code;
3001 free_realm = true;
3004 va_start(ap, _realm);
3005 code = krb5_build_principal_alloc_va(context, principal,
3006 strlen(realm), realm,
3007 ap);
3008 va_end(ap);
3010 if (free_realm) {
3011 krb5_free_default_realm(context, realm);
3014 return code;
3016 #endif
3018 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
3020 * @brief Get the lifetime of the initial ticket in the cache.
3022 * @param[in] context The kerberos context.
3024 * @param[in] id The credential cache to get the ticket lifetime.
3026 * @param[out] t A pointer to a time value to store the lifetime.
3028 * @return 0 on success, a krb5_error_code on error.
3030 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
3031 krb5_ccache id,
3032 time_t *t)
3034 krb5_cc_cursor cursor;
3035 krb5_error_code kerr;
3036 krb5_creds cred;
3037 krb5_timestamp now;
3039 *t = 0;
3041 kerr = krb5_timeofday(context, &now);
3042 if (kerr) {
3043 return kerr;
3046 kerr = krb5_cc_start_seq_get(context, id, &cursor);
3047 if (kerr) {
3048 return kerr;
3051 while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
3052 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
3053 if (cred.ticket_flags & TKT_FLG_INITIAL) {
3054 #else
3055 if (cred.flags.b.initial) {
3056 #endif
3057 if (now < cred.times.endtime) {
3058 *t = (time_t) (cred.times.endtime - now);
3060 krb5_free_cred_contents(context, &cred);
3061 break;
3063 krb5_free_cred_contents(context, &cred);
3066 krb5_cc_end_seq_get(context, id, &cursor);
3068 return kerr;
3070 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
3072 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
3073 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
3075 free_Checksum(cksum);
3077 #endif
3080 * @brief Compute a checksum operating on a keyblock.
3082 * This function computes a checksum over a PAC using the keyblock for a keyed
3083 * checksum.
3085 * @param[in] mem_ctx A talloc context to allocate the signature on.
3087 * @param[in] pac_data The PAC as input.
3089 * @param[in] context The library context.
3091 * @param[in] keyblock Encryption key for a keyed checksum.
3093 * @param[out] sig_type The checksum type
3095 * @param[out] sig_blob The talloc'ed checksum
3097 * The caller must free the sig_blob with talloc_free() when it is not needed
3098 * anymore.
3100 * @return 0 on success, a Kerberos error code otherwise.
3102 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
3103 DATA_BLOB *pac_data,
3104 krb5_context context,
3105 const krb5_keyblock *keyblock,
3106 uint32_t *sig_type,
3107 DATA_BLOB *sig_blob)
3109 krb5_error_code ret;
3110 krb5_checksum cksum;
3111 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
3112 krb5_crypto crypto;
3115 ret = krb5_crypto_init(context,
3116 keyblock,
3118 &crypto);
3119 if (ret) {
3120 DEBUG(0,("krb5_crypto_init() failed: %s\n",
3121 smb_get_krb5_error_message(context, ret, mem_ctx)));
3122 return ret;
3124 ret = krb5_create_checksum(context,
3125 crypto,
3126 KRB5_KU_OTHER_CKSUM,
3128 pac_data->data,
3129 pac_data->length,
3130 &cksum);
3131 if (ret) {
3132 DEBUG(2, ("PAC Verification failed: %s\n",
3133 smb_get_krb5_error_message(context, ret, mem_ctx)));
3136 krb5_crypto_destroy(context, crypto);
3138 if (ret) {
3139 return ret;
3142 *sig_type = cksum.cksumtype;
3143 *sig_blob = data_blob_talloc(mem_ctx,
3144 cksum.checksum.data,
3145 cksum.checksum.length);
3146 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
3147 krb5_data input;
3149 input.data = (char *)pac_data->data;
3150 input.length = pac_data->length;
3152 ret = krb5_c_make_checksum(context,
3154 keyblock,
3155 KRB5_KEYUSAGE_APP_DATA_CKSUM,
3156 &input,
3157 &cksum);
3158 if (ret) {
3159 DEBUG(2, ("PAC Verification failed: %s\n",
3160 smb_get_krb5_error_message(context, ret, mem_ctx)));
3161 return ret;
3164 *sig_type = cksum.checksum_type;
3165 *sig_blob = data_blob_talloc(mem_ctx,
3166 cksum.contents,
3167 cksum.length);
3169 #else
3170 #error krb5_create_checksum or krb5_c_make_checksum not available
3171 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
3172 smb_krb5_free_checksum_contents(context, &cksum);
3174 return 0;
3179 * @brief Get realm of a principal
3181 * @param[in] mem_ctx The talloc ctx to put the result on
3183 * @param[in] context The library context
3185 * @param[in] principal The principal to get the realm from.
3187 * @return A talloced string with the realm or NULL if an error occurred.
3189 char *smb_krb5_principal_get_realm(TALLOC_CTX *mem_ctx,
3190 krb5_context context,
3191 krb5_const_principal principal)
3193 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
3194 const char *realm = NULL;
3196 realm = krb5_principal_get_realm(context, principal);
3197 if (realm == NULL) {
3198 return NULL;
3201 return talloc_strdup(mem_ctx, realm);
3202 #elif defined(krb5_princ_realm) /* MIT */
3203 const krb5_data *realm = NULL;
3205 realm = krb5_princ_realm(context, principal);
3206 if (realm == NULL) {
3207 return NULL;
3210 return talloc_strndup(mem_ctx, realm->data, realm->length);
3211 #else
3212 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
3213 #endif
3217 * @brief Get realm of a principal
3219 * @param[in] context The library context
3221 * @param[in] principal The principal to set the realm
3223 * @param[in] realm The realm as a string to set.
3225 * @return 0 on success, a Kerberos error code otherwise.
3227 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
3228 krb5_principal principal,
3229 const char *realm)
3231 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
3232 return krb5_principal_set_realm(context, principal, realm);
3233 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
3234 krb5_error_code ret;
3235 krb5_data data;
3236 krb5_data *old_data;
3238 old_data = krb5_princ_realm(context, principal);
3240 ret = smb_krb5_copy_data_contents(&data,
3241 realm,
3242 strlen(realm));
3243 if (ret) {
3244 return ret;
3247 /* free realm before setting */
3248 free(old_data->data);
3250 krb5_princ_set_realm(context, principal, &data);
3252 return ret;
3253 #else
3254 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
3255 #endif
3260 * @brief Get the realm from the service hostname.
3262 * This function will look for a domain realm mapping in the [domain_realm]
3263 * section of the krb5.conf first and fallback to extract the realm from
3264 * the provided service hostname. As a last resort it will return the
3265 * provided client_realm.
3267 * @param[in] mem_ctx The talloc context
3269 * @param[in] hostname The service hostname
3271 * @param[in] client_realm If we can not find a mapping, fall back to
3272 * this realm.
3274 * @return The realm to use for the service hostname, NULL if a fatal error
3275 * occurred.
3277 char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
3278 const char *hostname,
3279 const char *client_realm)
3281 #if defined(HAVE_KRB5_REALM_TYPE)
3282 /* Heimdal. */
3283 krb5_realm *realm_list = NULL;
3284 #else
3285 /* MIT */
3286 char **realm_list = NULL;
3287 #endif
3288 char *realm = NULL;
3289 krb5_error_code kerr;
3290 krb5_context ctx = NULL;
3292 kerr = smb_krb5_init_context_common(&ctx);
3293 if (kerr) {
3294 DBG_ERR("kerberos init context failed (%s)\n",
3295 error_message(kerr));
3296 return NULL;
3299 kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
3300 if (kerr == KRB5_ERR_HOST_REALM_UNKNOWN) {
3301 realm_list = NULL;
3302 kerr = 0;
3304 if (kerr != 0) {
3305 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
3306 "failed %s\n",
3307 hostname ? hostname : "(NULL)",
3308 error_message(kerr) ));
3309 goto out;
3312 if (realm_list != NULL &&
3313 realm_list[0] != NULL &&
3314 realm_list[0][0] != '\0') {
3315 realm = talloc_strdup(mem_ctx, realm_list[0]);
3316 if (realm == NULL) {
3317 goto out;
3319 } else {
3320 const char *p = NULL;
3323 * "dc6.samba2003.example.com"
3324 * returns a realm of "SAMBA2003.EXAMPLE.COM"
3326 * "dc6." returns realm as NULL
3328 p = strchr_m(hostname, '.');
3329 if (p != NULL && p[1] != '\0') {
3330 realm = talloc_strdup_upper(mem_ctx, p + 1);
3331 if (realm == NULL) {
3332 goto out;
3337 if (realm == NULL) {
3338 realm = talloc_strdup(mem_ctx, client_realm);
3341 out:
3343 if (ctx) {
3344 if (realm_list) {
3345 krb5_free_host_realm(ctx, realm_list);
3346 realm_list = NULL;
3348 krb5_free_context(ctx);
3349 ctx = NULL;
3351 return realm;
3355 * @brief Get an error string from a Kerberos error code.
3357 * @param[in] context The library context.
3359 * @param[in] code The Kerberos error code.
3361 * @param[in] mem_ctx The talloc context to allocate the error string on.
3363 * @return A talloc'ed error string or NULL if an error occurred.
3365 * The caller must free the returned error string with talloc_free() if not
3366 * needed anymore
3368 char *smb_get_krb5_error_message(krb5_context context,
3369 krb5_error_code code,
3370 TALLOC_CTX *mem_ctx)
3372 char *ret;
3374 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
3375 const char *context_error = krb5_get_error_message(context, code);
3376 if (context_error) {
3377 ret = talloc_asprintf(mem_ctx, "%s: %s",
3378 error_message(code), context_error);
3379 krb5_free_error_message(context, context_error);
3380 return ret;
3382 #endif
3383 ret = talloc_strdup(mem_ctx, error_message(code));
3384 return ret;
3388 * @brief Return the type of a krb5_principal
3390 * @param[in] context The library context.
3392 * @param[in] principal The principal to get the type from.
3394 * @return The integer type of the principal.
3396 int smb_krb5_principal_get_type(krb5_context context,
3397 krb5_const_principal principal)
3399 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
3400 return krb5_principal_get_type(context, principal);
3401 #elif defined(krb5_princ_type) /* MIT */
3402 return krb5_princ_type(context, principal);
3403 #else
3404 #error UNKNOWN_PRINC_GET_TYPE_FUNCTION
3405 #endif
3409 * @brief Set the type of a principal
3411 * @param[in] context The library context
3413 * @param[inout] principal The principal to set the type for.
3415 * @param[in] type The principal type to set.
3417 void smb_krb5_principal_set_type(krb5_context context,
3418 krb5_principal principal,
3419 int type)
3421 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
3422 krb5_principal_set_type(context, principal, type);
3423 #elif defined(krb5_princ_type) /* MIT */
3424 krb5_princ_type(context, principal) = type;
3425 #else
3426 #error UNKNOWN_PRINC_SET_TYPE_FUNCTION
3427 #endif
3431 * @brief Check if a principal is a TGS
3433 * @param[in] context The library context
3435 * @param[inout] principal The principal to check.
3437 * @returns 1 if equal, 0 if not and -1 on error.
3439 int smb_krb5_principal_is_tgs(krb5_context context,
3440 krb5_const_principal principal)
3442 char *p = NULL;
3443 int eq = 1;
3445 p = smb_krb5_principal_get_comp_string(NULL, context, principal, 0);
3446 if (p == NULL) {
3447 return -1;
3450 eq = krb5_princ_size(context, principal) == 2 &&
3451 (strcmp(p, KRB5_TGS_NAME) == 0);
3453 talloc_free(p);
3455 return eq;
3458 #if !defined(HAVE_KRB5_WARNX)
3460 * @brief Log a Kerberos message
3462 * It sends the message to com_err.
3464 * @param[in] context The library context
3466 * @param[in] fmt The message format
3468 * @param[in] ... The message arguments
3470 * @return 0 on success.
3472 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
3474 va_list args;
3476 va_start(args, fmt);
3477 com_err_va("samba-kdc", errno, fmt, args);
3478 va_end(args);
3480 return 0;
3482 #endif
3485 * @brief Copy a credential cache.
3487 * @param[in] context The library context.
3489 * @param[in] incc Credential cache to be copied.
3491 * @param[inout] outcc Copy of credential cache to be filled in.
3493 * @return 0 on success, a Kerberos error code otherwise.
3495 krb5_error_code smb_krb5_cc_copy_creds(krb5_context context,
3496 krb5_ccache incc, krb5_ccache outcc)
3498 #ifdef HAVE_KRB5_CC_COPY_CACHE /* Heimdal */
3499 return krb5_cc_copy_cache(context, incc, outcc);
3500 #elif defined(HAVE_KRB5_CC_COPY_CREDS)
3501 krb5_error_code ret;
3502 krb5_principal princ = NULL;
3504 ret = krb5_cc_get_principal(context, incc, &princ);
3505 if (ret != 0) {
3506 return ret;
3508 ret = krb5_cc_initialize(context, outcc, princ);
3509 krb5_free_principal(context, princ);
3510 if (ret != 0) {
3511 return ret;
3513 return krb5_cc_copy_creds(context, incc, outcc);
3514 #else
3515 #error UNKNOWN_KRB5_CC_COPY_CACHE_OR_CREDS_FUNCTION
3516 #endif
3519 /**********************************************************
3520 * ADS KRB5 CALLS
3521 **********************************************************/
3523 static bool ads_cleanup_expired_creds(krb5_context context,
3524 krb5_ccache ccache,
3525 krb5_creds *credsp)
3527 krb5_error_code retval;
3528 const char *cc_type = krb5_cc_get_type(context, ccache);
3530 DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
3531 cc_type, krb5_cc_get_name(context, ccache),
3532 http_timestring(talloc_tos(), credsp->times.endtime)));
3534 /* we will probably need new tickets if the current ones
3535 will expire within 10 seconds.
3537 if (credsp->times.endtime >= (time(NULL) + 10))
3538 return false;
3540 /* heimdal won't remove creds from a file ccache, and
3541 perhaps we shouldn't anyway, since internally we
3542 use memory ccaches, and a FILE one probably means that
3543 we're using creds obtained outside of our executable
3545 if (strequal(cc_type, "FILE")) {
3546 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
3547 return false;
3550 retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
3551 if (retval) {
3552 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
3553 error_message(retval)));
3554 /* If we have an error in this, we want to display it,
3555 but continue as though we deleted it */
3557 return true;
3560 /* Allocate and setup the auth context into the state we need. */
3562 static krb5_error_code ads_setup_auth_context(krb5_context context,
3563 krb5_auth_context *auth_context)
3565 krb5_error_code retval;
3567 retval = krb5_auth_con_init(context, auth_context );
3568 if (retval) {
3569 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
3570 error_message(retval)));
3571 return retval;
3574 /* Ensure this is an addressless ticket. */
3575 retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
3576 if (retval) {
3577 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
3578 error_message(retval)));
3581 return retval;
3584 #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)
3585 static krb5_error_code ads_create_gss_checksum(krb5_data *in_data, /* [inout] */
3586 uint32_t gss_flags)
3588 unsigned int orig_length = in_data->length;
3589 unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
3590 char *gss_cksum = NULL;
3592 if (orig_length) {
3593 /* Extra length field for delegated ticket. */
3594 base_cksum_size += 4;
3597 if ((unsigned int)base_cksum_size + orig_length <
3598 (unsigned int)base_cksum_size) {
3599 return EINVAL;
3602 gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
3603 if (gss_cksum == NULL) {
3604 return ENOMEM;
3607 memset(gss_cksum, '\0', base_cksum_size + orig_length);
3608 SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
3611 * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
3612 * This matches the behavior of heimdal and mit.
3614 * And it is needed to work against some closed source
3615 * SMB servers.
3617 * See bug #7883
3619 memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
3621 SIVAL(gss_cksum, 20, gss_flags);
3623 if (orig_length && in_data->data != NULL) {
3624 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
3625 SSVAL(gss_cksum, 26, orig_length);
3626 /* Copy the kerberos KRB_CRED data */
3627 memcpy(gss_cksum + 28, in_data->data, orig_length);
3628 free(in_data->data);
3629 in_data->data = NULL;
3630 in_data->length = 0;
3632 in_data->data = gss_cksum;
3633 in_data->length = base_cksum_size + orig_length;
3634 return 0;
3636 #endif
3639 * We can't use krb5_mk_req because w2k wants the service to be in a particular
3640 * format.
3642 static krb5_error_code ads_krb5_mk_req(krb5_context context,
3643 krb5_auth_context *auth_context,
3644 const krb5_flags ap_req_options,
3645 const char *principal,
3646 krb5_ccache ccache,
3647 krb5_data *outbuf,
3648 time_t *expire_time,
3649 const char *impersonate_princ_s)
3651 krb5_error_code retval;
3652 krb5_principal server;
3653 krb5_principal impersonate_princ = NULL;
3654 krb5_creds *credsp;
3655 krb5_creds creds;
3656 krb5_data in_data;
3657 bool creds_ready = false;
3658 int i = 0, maxtries = 3;
3659 bool ok;
3661 ZERO_STRUCT(in_data);
3663 retval = smb_krb5_parse_name(context, principal, &server);
3664 if (retval != 0) {
3665 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
3666 return retval;
3669 if (impersonate_princ_s) {
3670 retval = smb_krb5_parse_name(context, impersonate_princ_s,
3671 &impersonate_princ);
3672 if (retval) {
3673 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
3674 goto cleanup_princ;
3678 /* obtain ticket & session key */
3679 ZERO_STRUCT(creds);
3680 if ((retval = krb5_copy_principal(context, server, &creds.server))) {
3681 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
3682 error_message(retval)));
3683 goto cleanup_princ;
3686 retval = krb5_cc_get_principal(context, ccache, &creds.client);
3687 if (retval != 0) {
3688 /* This can commonly fail on smbd startup with no ticket in the cache.
3689 * Report at higher level than 1. */
3690 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
3691 error_message(retval)));
3692 goto cleanup_creds;
3695 while (!creds_ready && (i < maxtries)) {
3697 retval = smb_krb5_get_credentials(context,
3698 ccache,
3699 creds.client,
3700 creds.server,
3701 impersonate_princ,
3702 &credsp);
3703 if (retval != 0) {
3704 DBG_WARNING("smb_krb5_get_credentials failed for %s "
3705 "(%s)\n",
3706 principal,
3707 error_message(retval));
3708 goto cleanup_creds;
3711 /* cope with ticket being in the future due to clock skew */
3712 if ((unsigned)credsp->times.starttime > time(NULL)) {
3713 time_t t = time(NULL);
3714 int time_offset =(int)((unsigned)credsp->times.starttime-t);
3715 DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
3716 krb5_set_real_time(context, t + time_offset + 1, 0);
3719 ok = ads_cleanup_expired_creds(context, ccache, credsp);
3720 if (!ok) {
3721 creds_ready = true;
3724 i++;
3727 DBG_DEBUG("Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
3728 principal,
3729 krb5_cc_get_type(context, ccache),
3730 krb5_cc_get_name(context, ccache),
3731 http_timestring(talloc_tos(),
3732 (unsigned)credsp->times.endtime),
3733 (unsigned)credsp->times.endtime);
3735 if (expire_time) {
3736 *expire_time = (time_t)credsp->times.endtime;
3739 /* Allocate the auth_context. */
3740 retval = ads_setup_auth_context(context, auth_context);
3741 if (retval != 0) {
3742 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3743 error_message(retval));
3744 goto cleanup_creds;
3747 #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)
3749 uint32_t gss_flags = 0;
3751 if (credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE) {
3753 * Fetch a forwarded TGT from the KDC so that we can
3754 * hand off a 2nd ticket as part of the kerberos
3755 * exchange.
3758 DBG_INFO("Server marked as OK to delegate to, building "
3759 "forwardable TGT\n");
3761 retval = krb5_auth_con_setuseruserkey(context,
3762 *auth_context,
3763 &credsp->keyblock );
3764 if (retval != 0) {
3765 DBG_WARNING("krb5_auth_con_setuseruserkey "
3766 "failed (%s)\n",
3767 error_message(retval));
3768 goto cleanup_creds;
3771 /* Must use a subkey for forwarded tickets. */
3772 retval = krb5_auth_con_setflags(context,
3773 *auth_context,
3774 KRB5_AUTH_CONTEXT_USE_SUBKEY);
3775 if (retval != 0) {
3776 DBG_WARNING("krb5_auth_con_setflags failed (%s)\n",
3777 error_message(retval));
3778 goto cleanup_creds;
3781 retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
3782 *auth_context, /* Authentication context [in] */
3783 discard_const_p(char, KRB5_TGS_NAME), /* Ticket service name ("krbtgt") [in] */
3784 credsp->client, /* Client principal for the tgt [in] */
3785 credsp->server, /* Server principal for the tgt [in] */
3786 ccache, /* Credential cache to use for storage [in] */
3787 1, /* Turn on for "Forwardable ticket" [in] */
3788 &in_data ); /* Resulting response [out] */
3790 if (retval) {
3791 DBG_INFO("krb5_fwd_tgt_creds failed (%s)\n",
3792 error_message(retval));
3795 * This is not fatal. Delete the *auth_context and continue
3796 * with krb5_mk_req_extended to get a non-forwardable ticket.
3799 if (in_data.data) {
3800 free( in_data.data );
3801 in_data.data = NULL;
3802 in_data.length = 0;
3804 krb5_auth_con_free(context, *auth_context);
3805 *auth_context = NULL;
3806 retval = ads_setup_auth_context(context, auth_context);
3807 if (retval != 0) {
3808 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3809 error_message(retval));
3810 goto cleanup_creds;
3812 } else {
3813 /* We got a delegated ticket. */
3814 gss_flags |= GSS_C_DELEG_FLAG;
3818 /* Frees and reallocates in_data into a GSS checksum blob. */
3819 retval = ads_create_gss_checksum(&in_data, gss_flags);
3820 if (retval != 0) {
3821 goto cleanup_data;
3824 /* We always want GSS-checksum types. */
3825 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
3826 if (retval != 0) {
3827 DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
3828 error_message(retval)));
3829 goto cleanup_data;
3832 #endif
3834 retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
3835 &in_data, credsp, outbuf);
3836 if (retval != 0) {
3837 DBG_WARNING("krb5_mk_req_extended failed (%s)\n",
3838 error_message(retval));
3841 #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)
3842 cleanup_data:
3843 #endif
3845 if (in_data.data) {
3846 free( in_data.data );
3847 in_data.length = 0;
3850 krb5_free_creds(context, credsp);
3852 cleanup_creds:
3853 krb5_free_cred_contents(context, &creds);
3855 cleanup_princ:
3856 krb5_free_principal(context, server);
3857 if (impersonate_princ) {
3858 krb5_free_principal(context, impersonate_princ);
3861 return retval;
3865 get a kerberos5 ticket for the given service
3867 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3868 const char *principal,
3869 time_t time_offset,
3870 DATA_BLOB *ticket,
3871 DATA_BLOB *session_key_krb5,
3872 uint32_t extra_ap_opts, const char *ccname,
3873 time_t *tgs_expire,
3874 const char *impersonate_princ_s)
3876 krb5_error_code retval;
3877 krb5_data packet;
3878 krb5_context context = NULL;
3879 krb5_ccache ccdef = NULL;
3880 krb5_auth_context auth_context = NULL;
3881 krb5_enctype enc_types[] = {
3882 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
3883 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
3884 ENCTYPE_ARCFOUR_HMAC,
3885 ENCTYPE_NULL};
3886 bool ok;
3888 DBG_DEBUG("Getting ticket for service [%s] using creds from [%s] "
3889 "and impersonating [%s]\n",
3890 principal, ccname, impersonate_princ_s);
3892 retval = smb_krb5_init_context_common(&context);
3893 if (retval != 0) {
3894 DBG_ERR("kerberos init context failed (%s)\n",
3895 error_message(retval));
3896 goto failed;
3899 if (time_offset != 0) {
3900 krb5_set_real_time(context, time(NULL) + time_offset, 0);
3903 retval = krb5_cc_resolve(context,
3904 ccname ? ccname : krb5_cc_default_name(context),
3905 &ccdef);
3906 if (retval != 0) {
3907 DBG_WARNING("krb5_cc_default failed (%s)\n",
3908 error_message(retval));
3909 goto failed;
3912 retval = krb5_set_default_tgs_ktypes(context, enc_types);
3913 if (retval != 0) {
3914 DBG_WARNING("krb5_set_default_tgs_ktypes failed (%s)\n",
3915 error_message(retval));
3916 goto failed;
3919 retval = ads_krb5_mk_req(context,
3920 &auth_context,
3921 AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
3922 principal,
3923 ccdef,
3924 &packet,
3925 tgs_expire,
3926 impersonate_princ_s);
3927 if (retval != 0) {
3928 goto failed;
3931 ok = smb_krb5_get_smb_session_key(mem_ctx,
3932 context,
3933 auth_context,
3934 session_key_krb5,
3935 false);
3936 if (!ok) {
3937 retval = ENOMEM;
3938 goto failed;
3941 *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
3943 smb_krb5_free_data_contents(context, &packet);
3945 failed:
3947 if (context) {
3948 if (ccdef) {
3949 krb5_cc_close(context, ccdef);
3951 if (auth_context) {
3952 krb5_auth_con_free(context, auth_context);
3954 krb5_free_context(context);
3957 return retval;
3960 #ifndef SAMBA4_USES_HEIMDAL /* MITKRB5 tracing callback */
3961 static void smb_krb5_trace_cb(krb5_context ctx,
3962 #ifdef HAVE_KRB5_TRACE_INFO
3963 const krb5_trace_info *info,
3964 #elif defined(HAVE_KRB5_TRACE_INFO_STRUCT)
3965 const struct krb5_trace_info *info,
3966 #else
3967 #error unknown krb5_trace_info
3968 #endif
3969 void *data)
3971 if (info != NULL) {
3972 DBGC_DEBUG(DBGC_KERBEROS, "%s", info->message);
3975 #endif
3977 krb5_error_code smb_krb5_init_context_common(krb5_context *_krb5_context)
3979 krb5_error_code ret;
3980 krb5_context krb5_ctx;
3982 initialize_krb5_error_table();
3984 ret = krb5_init_context(&krb5_ctx);
3985 if (ret) {
3986 DBG_ERR("Krb5 context initialization failed (%s)\n",
3987 error_message(ret));
3988 return ret;
3991 /* The MIT Kerberos build relies on using the system krb5.conf file.
3992 * If you really want to use another file please set KRB5_CONFIG
3993 * accordingly. */
3994 #ifndef SAMBA4_USES_HEIMDAL
3995 ret = krb5_set_trace_callback(krb5_ctx, smb_krb5_trace_cb, NULL);
3996 if (ret) {
3997 DBG_ERR("Failed to set MIT kerberos trace callback! (%s)\n",
3998 error_message(ret));
4000 #endif
4002 #ifdef SAMBA4_USES_HEIMDAL
4003 /* Set options in kerberos */
4004 krb5_set_dns_canonicalize_hostname(krb5_ctx, false);
4005 #endif
4007 *_krb5_context = krb5_ctx;
4008 return 0;
4011 #else /* HAVE_KRB5 */
4012 /* This saves a few linking headaches */
4013 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
4014 const char *principal,
4015 time_t time_offset,
4016 DATA_BLOB *ticket,
4017 DATA_BLOB *session_key_krb5,
4018 uint32_t extra_ap_opts, const char *ccname,
4019 time_t *tgs_expire,
4020 const char *impersonate_princ_s)
4022 DEBUG(0,("NO KERBEROS SUPPORT\n"));
4023 return 1;
4026 #endif /* HAVE_KRB5 */