lib/krb5_wrap: Fix missing error check in new salt code
[Samba.git] / lib / krb5_wrap / krb5_samba.c
blobfff5b4e2a22fcd7ff57058fa615219134bf72ad7
1 /*
2 Unix SMB/CIFS implementation.
3 simple kerberos5 routines for active directory
4 Copyright (C) Andrew Tridgell 2001
5 Copyright (C) Luke Howard 2002-2003
6 Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
7 Copyright (C) Guenther Deschner 2005-2009
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "includes.h"
24 #include "system/filesys.h"
25 #include "krb5_samba.h"
26 #include "lib/crypto/md4.h"
27 #include "../libds/common/flags.h"
29 #ifdef HAVE_COM_ERR_H
30 #include <com_err.h>
31 #endif /* HAVE_COM_ERR_H */
33 #ifndef KRB5_AUTHDATA_WIN2K_PAC
34 #define KRB5_AUTHDATA_WIN2K_PAC 128
35 #endif
37 #ifndef KRB5_AUTHDATA_IF_RELEVANT
38 #define KRB5_AUTHDATA_IF_RELEVANT 1
39 #endif
41 #ifdef HAVE_KRB5
43 #define GSSAPI_CHECKSUM 0x8003 /* Checksum type value for Kerberos */
44 #define GSSAPI_BNDLENGTH 16 /* Bind Length (rfc-1964 pg.3) */
45 #define GSSAPI_CHECKSUM_SIZE (4+GSSAPI_BNDLENGTH+4) /* Length of bind length,
46 bind field, flags field. */
47 #define GSS_C_DELEG_FLAG 1
49 /* MIT krb5 1.7beta3 (in Ubuntu Karmic) is missing the prototype,
50 but still has the symbol */
51 #if !HAVE_DECL_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE
52 krb5_error_code krb5_auth_con_set_req_cksumtype(
53 krb5_context context,
54 krb5_auth_context auth_context,
55 krb5_cksumtype cksumtype);
56 #endif
58 #if !defined(SMB_MALLOC)
59 #undef malloc
60 #define SMB_MALLOC(s) malloc((s))
61 #endif
63 #ifndef SMB_STRDUP
64 #define SMB_STRDUP(s) strdup(s)
65 #endif
67 /**********************************************************
68 * MISSING FUNCTIONS
69 **********************************************************/
71 #if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
73 #if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)
75 /* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
76 * to krb5_set_default_tgs_ktypes. See
77 * http://lists.samba.org/archive/samba-technical/2006-July/048271.html
79 * If the MIT libraries are not exporting internal symbols, we will end up in
80 * this branch, which is correct. Otherwise we will continue to use the
81 * internal symbol
83 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
85 return krb5_set_default_tgs_enctypes(ctx, enc);
88 #elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)
90 /* Heimdal */
91 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
93 return krb5_set_default_in_tkt_etypes(ctx, enc);
96 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */
98 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */
101 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
102 krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
103 krb5_auth_context auth_context,
104 krb5_keyblock *keyblock)
106 return krb5_auth_con_setkey(context, auth_context, keyblock);
108 #endif
110 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
111 void krb5_free_unparsed_name(krb5_context context, char *val)
113 SAFE_FREE(val);
115 #endif
117 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
118 const krb5_data *krb5_princ_component(krb5_context context,
119 krb5_principal principal, int i);
121 const krb5_data *krb5_princ_component(krb5_context context,
122 krb5_principal principal, int i)
124 static krb5_data kdata;
126 kdata.data = discard_const_p(char, krb5_principal_get_comp_string(context, principal, i));
127 kdata.length = strlen((const char *)kdata.data);
128 return &kdata;
130 #endif
133 /**********************************************************
134 * WRAPPING FUNCTIONS
135 **********************************************************/
137 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
138 /* HEIMDAL */
141 * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
143 * @param[in] paddr A pointer to a 'struct sockaddr_storage to extract the
144 * address from.
146 * @param[out] pkaddr A Kerberos address to store tha address in.
148 * @return True on success, false if an error occurred.
150 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
151 krb5_address *pkaddr)
153 memset(pkaddr, '\0', sizeof(krb5_address));
154 #ifdef HAVE_IPV6
155 if (paddr->ss_family == AF_INET6) {
156 pkaddr->addr_type = KRB5_ADDRESS_INET6;
157 pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
158 pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
159 return true;
161 #endif
162 if (paddr->ss_family == AF_INET) {
163 pkaddr->addr_type = KRB5_ADDRESS_INET;
164 pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
165 pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
166 return true;
168 return false;
170 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
171 /* MIT */
174 * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
176 * @param[in] paddr A pointer to a 'struct sockaddr_storage to extract the
177 * address from.
179 * @param[in] pkaddr A Kerberos address to store tha address in.
181 * @return True on success, false if an error occurred.
183 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
184 krb5_address *pkaddr)
186 memset(pkaddr, '\0', sizeof(krb5_address));
187 #ifdef HAVE_IPV6
188 if (paddr->ss_family == AF_INET6) {
189 pkaddr->addrtype = ADDRTYPE_INET6;
190 pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
191 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
192 return true;
194 #endif
195 if (paddr->ss_family == AF_INET) {
196 pkaddr->addrtype = ADDRTYPE_INET;
197 pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
198 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
199 return true;
201 return false;
203 #else
204 #error UNKNOWN_ADDRTYPE
205 #endif
207 krb5_error_code smb_krb5_mk_error(krb5_context context,
208 krb5_error_code error_code,
209 const char *e_text,
210 krb5_data *e_data,
211 const krb5_principal client,
212 const krb5_principal server,
213 krb5_data *enc_err)
215 krb5_error_code code = EINVAL;
216 #ifdef SAMBA4_USES_HEIMDAL
217 code = krb5_mk_error(context,
218 error_code,
219 e_text,
220 e_data,
221 client,
222 server,
223 NULL, /* client_time */
224 NULL, /* client_usec */
225 enc_err);
226 #else
227 krb5_principal unspec_server = NULL;
228 krb5_error errpkt;
230 errpkt.ctime = 0;
231 errpkt.cusec = 0;
233 code = krb5_us_timeofday(context,
234 &errpkt.stime,
235 &errpkt.susec);
236 if (code != 0) {
237 return code;
240 errpkt.error = error_code;
242 errpkt.text.length = 0;
243 if (e_text != NULL) {
244 errpkt.text.length = strlen(e_text);
245 errpkt.text.data = discard_const_p(char, e_text);
248 errpkt.e_data.magic = KV5M_DATA;
249 errpkt.e_data.length = 0;
250 errpkt.e_data.data = NULL;
251 if (e_data != NULL) {
252 errpkt.e_data = *e_data;
255 errpkt.client = client;
257 if (server != NULL) {
258 errpkt.server = server;
259 } else {
260 code = smb_krb5_make_principal(context,
261 &unspec_server,
262 "<unspecified realm>",
263 NULL);
264 if (code != 0) {
265 return code;
267 errpkt.server = unspec_server;
270 code = krb5_mk_error(context,
271 &errpkt,
272 enc_err);
273 krb5_free_principal(context, unspec_server);
274 #endif
275 return code;
279 * @brief Create a keyblock based on input parameters
281 * @param context The krb5_context
282 * @param host_princ The krb5_principal to use
283 * @param salt The optional salt, if omitted, salt is calculated with
284 * the provided principal.
285 * @param password The krb5_data containing the password
286 * @param enctype The krb5_enctype to use for the keyblock generation
287 * @param key The returned krb5_keyblock, caller needs to free with
288 * krb5_free_keyblock().
290 * @return krb5_error_code
292 int smb_krb5_create_key_from_string(krb5_context context,
293 krb5_const_principal host_princ,
294 krb5_data *salt,
295 krb5_data *password,
296 krb5_enctype enctype,
297 krb5_keyblock *key)
299 int ret = 0;
301 if (host_princ == NULL && salt == NULL) {
302 return -1;
305 if ((int)enctype == (int)ENCTYPE_ARCFOUR_HMAC) {
306 TALLOC_CTX *frame = talloc_stackframe();
307 uint8_t *utf16 = NULL;
308 size_t utf16_size = 0;
309 uint8_t nt_hash[16];
310 bool ok;
312 ok = convert_string_talloc(frame, CH_UNIX, CH_UTF16LE,
313 password->data, password->length,
314 (void **)&utf16, &utf16_size);
315 if (!ok) {
316 if (errno == 0) {
317 errno = EINVAL;
319 ret = errno;
320 TALLOC_FREE(frame);
321 return ret;
324 mdfour(nt_hash, utf16, utf16_size);
325 memset(utf16, 0, utf16_size);
326 ret = smb_krb5_keyblock_init_contents(context,
327 ENCTYPE_ARCFOUR_HMAC,
328 nt_hash,
329 sizeof(nt_hash),
330 key);
331 ZERO_STRUCT(nt_hash);
332 if (ret != 0) {
333 TALLOC_FREE(frame);
334 return ret;
337 TALLOC_FREE(frame);
338 return 0;
341 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_C_STRING_TO_KEY)
342 {/* MIT */
343 krb5_data _salt;
345 if (salt == NULL) {
346 ret = krb5_principal2salt(context, host_princ, &_salt);
347 if (ret) {
348 DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
349 return ret;
351 } else {
352 _salt = *salt;
354 ret = krb5_c_string_to_key(context, enctype, password, &_salt, key);
355 if (salt == NULL) {
356 SAFE_FREE(_salt.data);
359 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
360 {/* Heimdal */
361 krb5_salt _salt;
363 if (salt == NULL) {
364 ret = krb5_get_pw_salt(context, host_princ, &_salt);
365 if (ret) {
366 DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
367 return ret;
369 } else {
370 _salt.saltvalue = *salt;
371 _salt.salttype = KRB5_PW_SALT;
374 ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, _salt, key);
375 if (salt == NULL) {
376 krb5_free_salt(context, _salt);
379 #else
380 #error UNKNOWN_CREATE_KEY_FUNCTIONS
381 #endif
382 return ret;
386 * @brief Create a salt for a given principal
388 * @param context The initialized krb5_context
389 * @param host_princ The krb5_principal to create the salt for
390 * @param psalt A pointer to a krb5_data struct
392 * caller has to free the contents of psalt with smb_krb5_free_data_contents
393 * when function has succeeded
395 * @return krb5_error_code, returns 0 on success, error code otherwise
398 int smb_krb5_get_pw_salt(krb5_context context,
399 krb5_const_principal host_princ,
400 krb5_data *psalt)
401 #if defined(HAVE_KRB5_GET_PW_SALT)
402 /* Heimdal */
404 int ret;
405 krb5_salt salt;
407 ret = krb5_get_pw_salt(context, host_princ, &salt);
408 if (ret) {
409 return ret;
412 psalt->data = salt.saltvalue.data;
413 psalt->length = salt.saltvalue.length;
415 return ret;
417 #elif defined(HAVE_KRB5_PRINCIPAL2SALT)
418 /* MIT */
420 return krb5_principal2salt(context, host_princ, psalt);
422 #else
423 #error UNKNOWN_SALT_FUNCTIONS
424 #endif
427 * @brief This constructs the salt principal used by active directory
429 * Most Kerberos encryption types require a salt in order to
430 * calculate the long term private key for user/computer object
431 * based on a password.
433 * The returned _salt_principal is a string in forms like this:
434 * - host/somehost.example.com@EXAMPLE.COM
435 * - SomeAccount@EXAMPLE.COM
436 * - SomePrincipal@EXAMPLE.COM
438 * This is not the form that's used as salt, it's just
439 * the human readable form. It needs to be converted by
440 * smb_krb5_salt_principal2data().
442 * @param[in] realm The realm the user/computer is added too.
444 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
446 * @param[in] userPrincipalName The userPrincipalName attribute of the object
447 * or NULL is not available.
449 * @param[in] uac_flags UF_ACCOUNT_TYPE_MASKed userAccountControl field
451 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
453 * @param[out] _salt_principal The resulting principal as string.
455 * @retval 0 Success; otherwise - Kerberos error codes
457 * @see smb_krb5_salt_principal2data
459 int smb_krb5_salt_principal(krb5_context krb5_ctx,
460 const char *realm,
461 const char *sAMAccountName,
462 const char *userPrincipalName,
463 uint32_t uac_flags,
464 krb5_principal *salt_princ)
466 TALLOC_CTX *frame = talloc_stackframe();
467 char *upper_realm = NULL;
468 const char *principal = NULL;
469 int principal_len = 0;
470 krb5_error_code krb5_ret;
472 *salt_princ = NULL;
474 if (sAMAccountName == NULL) {
475 TALLOC_FREE(frame);
476 return EINVAL;
479 if (realm == NULL) {
480 TALLOC_FREE(frame);
481 return EINVAL;
484 if (uac_flags & ~UF_ACCOUNT_TYPE_MASK) {
486 * catch callers which still
487 * pass 'true'.
489 TALLOC_FREE(frame);
490 return EINVAL;
492 if (uac_flags == 0) {
494 * catch callers which still
495 * pass 'false'.
497 TALLOC_FREE(frame);
498 return EINVAL;
501 upper_realm = strupper_talloc(frame, realm);
502 if (upper_realm == NULL) {
503 TALLOC_FREE(frame);
504 return ENOMEM;
507 /* Many, many thanks to lukeh@padl.com for this
508 * algorithm, described in his Nov 10 2004 mail to
509 * samba-technical@lists.samba.org */
512 * Determine a salting principal
514 if (uac_flags & UF_TRUST_ACCOUNT_MASK) {
515 int computer_len = 0;
517 computer_len = strlen(sAMAccountName);
518 if (sAMAccountName[computer_len-1] == '$') {
519 computer_len -= 1;
522 if (uac_flags & UF_INTERDOMAIN_TRUST_ACCOUNT) {
523 const char *krbtgt = "krbtgt";
524 krb5_ret = krb5_build_principal_ext(krb5_ctx,
525 salt_princ,
526 strlen(upper_realm),
527 upper_realm,
528 strlen(krbtgt),
529 krbtgt,
530 computer_len,
531 sAMAccountName,
533 if (krb5_ret != 0) {
534 TALLOC_FREE(frame);
535 return krb5_ret;
537 } else {
538 const char *host = "host";
539 char *tmp = NULL;
540 char *tmp_lower = NULL;
542 tmp = talloc_asprintf(frame, "%*.*s.%s",
543 computer_len,
544 computer_len,
545 sAMAccountName,
546 realm);
547 if (tmp == NULL) {
548 TALLOC_FREE(frame);
549 return ENOMEM;
552 tmp_lower = strlower_talloc(frame, tmp);
553 if (tmp_lower == NULL) {
554 TALLOC_FREE(frame);
555 return ENOMEM;
558 krb5_ret = krb5_build_principal_ext(krb5_ctx,
559 salt_princ,
560 strlen(upper_realm),
561 upper_realm,
562 strlen(host),
563 host,
564 strlen(tmp_lower),
565 tmp_lower,
567 if (krb5_ret != 0) {
568 TALLOC_FREE(frame);
569 return krb5_ret;
573 } else if (userPrincipalName != NULL) {
575 * We parse the name not only to allow an easy
576 * replacement of the realm (no matter the realm in
577 * the UPN, the salt comes from the upper-case real
578 * realm, but also to correctly provide a salt when
579 * the UPN is host/foo.bar
581 * This can fail for a UPN of the form foo@bar@REALM
582 * (which is accepted by windows) however.
584 krb5_ret = krb5_parse_name(krb5_ctx,
585 userPrincipalName,
586 salt_princ);
588 if (krb5_ret != 0) {
589 TALLOC_FREE(frame);
590 return krb5_ret;
594 * No matter what realm (including none) in the UPN,
595 * the realm is replaced with our upper-case realm
597 krb5_ret = smb_krb5_principal_set_realm(krb5_ctx,
598 *salt_princ,
599 upper_realm);
600 if (krb5_ret != 0) {
601 krb5_free_principal(krb5_ctx, *salt_princ);
602 TALLOC_FREE(frame);
603 return krb5_ret;
605 } else {
606 principal = sAMAccountName;
607 principal_len = strlen(principal);
609 krb5_ret = krb5_build_principal_ext(krb5_ctx,
610 salt_princ,
611 strlen(upper_realm),
612 upper_realm,
613 principal_len,
614 principal,
616 if (krb5_ret != 0) {
617 TALLOC_FREE(frame);
618 return krb5_ret;
622 TALLOC_FREE(frame);
623 return 0;
627 * @brief This constructs the salt principal used by active directory
629 * Most Kerberos encryption types require a salt in order to
630 * calculate the long term private key for user/computer object
631 * based on a password.
633 * The returned _salt_principal is a string in forms like this:
634 * - host/somehost.example.com@EXAMPLE.COM
635 * - SomeAccount@EXAMPLE.COM
636 * - SomePrincipal@EXAMPLE.COM
638 * This is not the form that's used as salt, it's just
639 * the human readable form. It needs to be converted by
640 * smb_krb5_salt_principal2data().
642 * @param[in] realm The realm the user/computer is added too.
644 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
646 * @param[in] userPrincipalName The userPrincipalName attribute of the object
647 * or NULL is not available.
649 * @param[in] uac_flags UF_ACCOUNT_TYPE_MASKed userAccountControl field
651 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
653 * @param[out] _salt_principal The resulting principal as string.
655 * @retval 0 Success; otherwise - Kerberos error codes
657 * @see smb_krb5_salt_principal2data
659 int smb_krb5_salt_principal_str(const char *realm,
660 const char *sAMAccountName,
661 const char *userPrincipalName,
662 uint32_t uac_flags,
663 TALLOC_CTX *mem_ctx,
664 char **_salt_principal_str)
666 krb5_principal salt_principal = NULL;
667 char *salt_principal_malloc;
668 krb5_context krb5_ctx;
669 krb5_error_code krb5_ret
670 = smb_krb5_init_context_common(&krb5_ctx);
671 if (krb5_ret != 0) {
672 DBG_ERR("kerberos init context failed (%s)\n",
673 error_message(krb5_ret));
674 return krb5_ret;
677 krb5_ret = smb_krb5_salt_principal(krb5_ctx,
678 realm,
679 sAMAccountName,
680 userPrincipalName,
681 uac_flags,
682 &salt_principal);
684 krb5_ret = krb5_unparse_name(krb5_ctx, salt_principal,
685 &salt_principal_malloc);
686 if (krb5_ret != 0) {
687 krb5_free_principal(krb5_ctx, salt_principal);
688 DBG_ERR("kerberos unparse of salt principal failed (%s)\n",
689 error_message(krb5_ret));
690 return krb5_ret;
692 krb5_free_principal(krb5_ctx, salt_principal);
693 *_salt_principal_str
694 = talloc_strdup(mem_ctx, salt_principal_malloc);
695 krb5_free_unparsed_name(krb5_ctx, salt_principal_malloc);
697 if (*_salt_principal_str == NULL) {
698 return ENOMEM;
700 return 0;
704 * @brief Converts the salt principal string into the salt data blob
706 * This function takes a salt_principal as string in forms like this:
707 * - host/somehost.example.com@EXAMPLE.COM
708 * - SomeAccount@EXAMPLE.COM
709 * - SomePrincipal@EXAMPLE.COM
711 * It generates values like:
712 * - EXAMPLE.COMhost/somehost.example.com
713 * - EXAMPLE.COMSomeAccount
714 * - EXAMPLE.COMSomePrincipal
716 * @param[in] realm The realm the user/computer is added too.
718 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
720 * @param[in] userPrincipalName The userPrincipalName attribute of the object
721 * or NULL is not available.
723 * @param[in] is_computer The indication of the object includes
724 * objectClass=computer.
726 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
728 * @param[out] _salt_principal The resulting principal as string.
730 * @retval 0 Success; otherwise - Kerberos error codes
732 * @see smb_krb5_salt_principal
734 int smb_krb5_salt_principal2data(krb5_context context,
735 const char *salt_principal,
736 TALLOC_CTX *mem_ctx,
737 char **_salt_data)
739 krb5_error_code ret;
740 krb5_principal salt_princ = NULL;
741 krb5_data salt;
743 *_salt_data = NULL;
745 ret = krb5_parse_name(context, salt_principal, &salt_princ);
746 if (ret != 0) {
747 return ret;
750 ret = smb_krb5_get_pw_salt(context, salt_princ, &salt);
751 krb5_free_principal(context, salt_princ);
752 if (ret != 0) {
753 return ret;
756 *_salt_data = talloc_strndup(mem_ctx,
757 (char *)salt.data,
758 salt.length);
759 smb_krb5_free_data_contents(context, &salt);
760 if (*_salt_data == NULL) {
761 return ENOMEM;
764 return 0;
767 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
769 * @brief Get a list of encryption types allowed for session keys
771 * @param[in] context The library context
773 * @param[in] enctypes An allocated, zero-terminated list of encryption types
775 * This function returns an allocated list of encryption types allowed for
776 * session keys.
778 * Use free() to free the enctypes when it is no longer needed.
780 * @retval 0 Success; otherwise - Kerberos error codes
782 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
783 krb5_enctype **enctypes)
785 return krb5_get_permitted_enctypes(context, enctypes);
787 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
788 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
789 krb5_enctype **enctypes)
791 #ifdef HAVE_KRB5_PDU_NONE_DECL
792 return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, enctypes);
793 #else
794 return krb5_get_default_in_tkt_etypes(context, enctypes);
795 #endif
797 #else
798 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
799 #endif
803 * @brief Convert a string principal name to a Kerberos principal.
805 * @param[in] context The library context
807 * @param[in] name The principal as a unix charset string.
809 * @param[out] principal The newly allocated principal.
811 * Use krb5_free_principal() to free a principal when it is no longer needed.
813 * @return 0 on success, a Kerberos error code otherwise.
815 krb5_error_code smb_krb5_parse_name(krb5_context context,
816 const char *name,
817 krb5_principal *principal)
819 krb5_error_code ret;
820 char *utf8_name;
821 size_t converted_size;
822 TALLOC_CTX *frame = talloc_stackframe();
824 if (!push_utf8_talloc(frame, &utf8_name, name, &converted_size)) {
825 talloc_free(frame);
826 return ENOMEM;
829 ret = krb5_parse_name(context, utf8_name, principal);
830 if (ret == KRB5_PARSE_MALFORMED) {
831 ret = krb5_parse_name_flags(context, utf8_name,
832 KRB5_PRINCIPAL_PARSE_ENTERPRISE,
833 principal);
835 TALLOC_FREE(frame);
836 return ret;
840 * @brief Convert a Kerberos principal structure to a string representation.
842 * The resulting string representation will be a unix charset name and is
843 * talloc'ed.
845 * @param[in] mem_ctx The talloc context to allocate memory on.
847 * @param[in] context The library context.
849 * @param[in] principal The principal.
851 * @param[out] unix_name A string representation of the princpial name as with
852 * unix charset.
854 * Use talloc_free() to free the string representation if it is no longer
855 * needed.
857 * @return 0 on success, a Kerberos error code otherwise.
859 krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
860 krb5_context context,
861 krb5_const_principal principal,
862 char **unix_name)
864 krb5_error_code ret;
865 char *utf8_name;
866 size_t converted_size;
868 *unix_name = NULL;
869 ret = krb5_unparse_name(context, principal, &utf8_name);
870 if (ret) {
871 return ret;
874 if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
875 krb5_free_unparsed_name(context, utf8_name);
876 return ENOMEM;
878 krb5_free_unparsed_name(context, utf8_name);
879 return 0;
883 * @brief Free the contents of a krb5_data structure and zero the data field.
885 * @param[in] context The krb5 context
887 * @param[in] pdata The data structure to free contents of
889 * This function frees the contents, not the structure itself.
891 void smb_krb5_free_data_contents(krb5_context context, krb5_data *pdata)
893 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
894 if (pdata->data) {
895 krb5_free_data_contents(context, pdata);
897 #elif defined(HAVE_KRB5_DATA_FREE)
898 krb5_data_free(context, pdata);
899 #else
900 SAFE_FREE(pdata->data);
901 #endif
905 * @brief copy a buffer into a krb5_data struct
907 * @param[in] p The krb5_data
908 * @param[in] data The data to copy
909 * @param[in] length The length of the data to copy
910 * @return krb5_error_code
912 * Caller has to free krb5_data with smb_krb5_free_data_contents().
914 krb5_error_code smb_krb5_copy_data_contents(krb5_data *p,
915 const void *data,
916 size_t len)
918 #if defined(HAVE_KRB5_DATA_COPY)
919 return krb5_data_copy(p, data, len);
920 #else
921 if (len) {
922 p->data = malloc(len);
923 if (p->data == NULL) {
924 return ENOMEM;
926 memmove(p->data, data, len);
927 } else {
928 p->data = NULL;
930 p->length = len;
931 p->magic = KV5M_DATA;
932 return 0;
933 #endif
936 bool smb_krb5_get_smb_session_key(TALLOC_CTX *mem_ctx,
937 krb5_context context,
938 krb5_auth_context auth_context,
939 DATA_BLOB *session_key,
940 bool remote)
942 krb5_keyblock *skey = NULL;
943 krb5_error_code err = 0;
944 bool ret = false;
946 if (remote) {
947 #ifdef HAVE_KRB5_AUTH_CON_GETRECVSUBKEY
948 err = krb5_auth_con_getrecvsubkey(context,
949 auth_context,
950 &skey);
951 #else /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
952 err = krb5_auth_con_getremotesubkey(context,
953 auth_context, &skey);
954 #endif /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
955 } else {
956 #ifdef HAVE_KRB5_AUTH_CON_GETSENDSUBKEY
957 err = krb5_auth_con_getsendsubkey(context,
958 auth_context,
959 &skey);
960 #else /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
961 err = krb5_auth_con_getlocalsubkey(context,
962 auth_context, &skey);
963 #endif /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
966 if (err || skey == NULL) {
967 DEBUG(10, ("KRB5 error getting session key %d\n", err));
968 goto done;
971 DEBUG(10, ("Got KRB5 session key of length %d\n",
972 (int)KRB5_KEY_LENGTH(skey)));
974 *session_key = data_blob_talloc(mem_ctx,
975 KRB5_KEY_DATA(skey),
976 KRB5_KEY_LENGTH(skey));
977 dump_data_pw("KRB5 Session Key:\n",
978 session_key->data,
979 session_key->length);
981 ret = true;
983 done:
984 if (skey) {
985 krb5_free_keyblock(context, skey);
988 return ret;
993 * @brief Get talloced string component of a principal
995 * @param[in] mem_ctx The TALLOC_CTX
996 * @param[in] context The krb5_context
997 * @param[in] principal The principal
998 * @param[in] component The component
999 * @return string component
1001 * Caller must talloc_free if the return value is not NULL.
1004 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
1005 krb5_context context,
1006 krb5_const_principal principal,
1007 unsigned int component)
1009 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
1010 return talloc_strdup(mem_ctx, krb5_principal_get_comp_string(context, principal, component));
1011 #else
1012 krb5_data *data;
1014 if (component >= krb5_princ_size(context, principal)) {
1015 return NULL;
1018 data = krb5_princ_component(context, principal, component);
1019 if (data == NULL) {
1020 return NULL;
1023 return talloc_strndup(mem_ctx, data->data, data->length);
1024 #endif
1028 * @brief
1030 * @param[in] ccache_string A string pointing to the cache to renew the ticket
1031 * (e.g. FILE:/tmp/krb5cc_0) or NULL. If the principal
1032 * ccache has not been specified, the default ccache
1033 * will be used.
1035 * @param[in] client_string The client principal string (e.g. user@SAMBA.SITE)
1036 * or NULL. If the principal string has not been
1037 * specified, the principal from the ccache will be
1038 * retrieved.
1040 * @param[in] service_string The service ticket string
1041 * (e.g. krbtgt/SAMBA.SITE@SAMBA.SITE) or NULL. If
1042 * the sevice ticket is specified, it is parsed (
1043 * with the realm part ignored) and used as the
1044 * server principal of the credential. Otherwise
1045 * the ticket-granting service is used.
1047 * @param[in] expire_time A pointer to store the credentials end time or
1048 * NULL.
1050 * @return 0 on Succes, a Kerberos error code otherwise.
1052 krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,
1053 const char *client_string,
1054 const char *service_string,
1055 time_t *expire_time)
1057 krb5_error_code ret;
1058 krb5_context context = NULL;
1059 krb5_ccache ccache = NULL;
1060 krb5_principal client = NULL;
1061 krb5_creds creds, creds_in;
1063 ZERO_STRUCT(creds);
1064 ZERO_STRUCT(creds_in);
1066 ret = smb_krb5_init_context_common(&context);
1067 if (ret) {
1068 DBG_ERR("kerberos init context failed (%s)\n",
1069 error_message(ret));
1070 goto done;
1073 if (!ccache_string) {
1074 ccache_string = krb5_cc_default_name(context);
1077 if (!ccache_string) {
1078 ret = EINVAL;
1079 goto done;
1082 DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
1084 /* FIXME: we should not fall back to defaults */
1085 ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
1086 if (ret) {
1087 goto done;
1090 if (client_string) {
1091 ret = smb_krb5_parse_name(context, client_string, &client);
1092 if (ret) {
1093 goto done;
1095 } else {
1096 ret = krb5_cc_get_principal(context, ccache, &client);
1097 if (ret) {
1098 goto done;
1102 ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
1103 if (ret) {
1104 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
1105 goto done;
1108 /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
1109 ret = krb5_cc_initialize(context, ccache, client);
1110 if (ret) {
1111 goto done;
1114 ret = krb5_cc_store_cred(context, ccache, &creds);
1116 if (expire_time) {
1117 *expire_time = (time_t) creds.times.endtime;
1120 done:
1121 krb5_free_cred_contents(context, &creds_in);
1122 krb5_free_cred_contents(context, &creds);
1124 if (client) {
1125 krb5_free_principal(context, client);
1127 if (ccache) {
1128 krb5_cc_close(context, ccache);
1130 if (context) {
1131 krb5_free_context(context);
1134 return ret;
1138 * @brief Free the data stored in an smb_krb5_addresses structure.
1140 * @param[in] context The library context
1142 * @param[in] addr The address structure to free.
1144 * @return 0 on success, a Kerberos error code otherwise.
1146 krb5_error_code smb_krb5_free_addresses(krb5_context context,
1147 smb_krb5_addresses *addr)
1149 krb5_error_code ret = 0;
1150 if (addr == NULL) {
1151 return ret;
1153 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1154 krb5_free_addresses(context, addr->addrs);
1155 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1156 ret = krb5_free_addresses(context, addr->addrs);
1157 SAFE_FREE(addr->addrs);
1158 #endif
1159 SAFE_FREE(addr);
1160 addr = NULL;
1161 return ret;
1164 #define MAX_NETBIOSNAME_LEN 16
1167 * @brief Add a netbios name to the array of addresses
1169 * @param[in] kerb_addr A pointer to the smb_krb5_addresses to add the
1170 * netbios name to.
1172 * @param[in] netbios_name The netbios name to add.
1174 * @return 0 on success, a Kerberos error code otherwise.
1176 krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
1177 const char *netbios_name)
1179 krb5_error_code ret = 0;
1180 char buf[MAX_NETBIOSNAME_LEN];
1181 int len;
1182 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1183 krb5_address **addrs = NULL;
1184 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1185 krb5_addresses *addrs = NULL;
1186 #endif
1188 *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1189 if (*kerb_addr == NULL) {
1190 return ENOMEM;
1193 /* temporarily duplicate put_name() code here to avoid dependency
1194 * issues for a 5 lines function */
1195 len = strlen(netbios_name);
1196 memcpy(buf, netbios_name,
1197 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
1198 if (len < MAX_NETBIOSNAME_LEN - 1) {
1199 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
1201 buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
1203 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1205 int num_addr = 2;
1207 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1208 if (addrs == NULL) {
1209 SAFE_FREE(*kerb_addr);
1210 return ENOMEM;
1213 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1215 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1216 if (addrs[0] == NULL) {
1217 SAFE_FREE(addrs);
1218 SAFE_FREE(*kerb_addr);
1219 return ENOMEM;
1222 addrs[0]->magic = KV5M_ADDRESS;
1223 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1224 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1225 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1226 if (addrs[0]->contents == NULL) {
1227 SAFE_FREE(addrs[0]);
1228 SAFE_FREE(addrs);
1229 SAFE_FREE(*kerb_addr);
1230 return ENOMEM;
1233 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1235 addrs[1] = NULL;
1237 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1239 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1240 if (addrs == NULL) {
1241 SAFE_FREE(*kerb_addr);
1242 return ENOMEM;
1245 memset(addrs, 0, sizeof(krb5_addresses));
1247 addrs->len = 1;
1248 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1249 if (addrs->val == NULL) {
1250 SAFE_FREE(addrs);
1251 SAFE_FREE(*kerb_addr);
1252 return ENOMEM;
1255 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1256 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1257 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1258 if (addrs->val[0].address.data == NULL) {
1259 SAFE_FREE(addrs->val);
1260 SAFE_FREE(addrs);
1261 SAFE_FREE(*kerb_addr);
1262 return ENOMEM;
1265 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1267 #else
1268 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1269 #endif
1270 (*kerb_addr)->addrs = addrs;
1272 return ret;
1276 * @brief Get the enctype from a key table entry
1278 * @param[in] kt_entry Key table entry to get the enctype from.
1280 * @return The enctype from the entry.
1282 krb5_enctype smb_krb5_kt_get_enctype_from_entry(krb5_keytab_entry *kt_entry)
1284 return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1288 * @brief Free the contents of a key table entry.
1290 * @param[in] context The library context.
1292 * @param[in] kt_entry The key table entry to free the contents of.
1294 * @return 0 on success, a Kerberos error code otherwise.
1296 * The pointer itself is not freed.
1298 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1299 krb5_keytab_entry *kt_entry)
1301 /* Try krb5_free_keytab_entry_contents first, since
1302 * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1303 * krb5_kt_free_entry but only has a prototype for the first, while the
1304 * second is considered private.
1306 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1307 return krb5_free_keytab_entry_contents(context, kt_entry);
1308 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1309 return krb5_kt_free_entry(context, kt_entry);
1310 #else
1311 #error UNKNOWN_KT_FREE_FUNCTION
1312 #endif
1317 * @brief Convert an encryption type to a string.
1319 * @param[in] context The library context.
1321 * @param[in] enctype The encryption type.
1323 * @param[in] etype_s A pointer to store the allocated encryption type as a
1324 * string.
1326 * @return 0 on success, a Kerberos error code otherwise.
1328 * The caller needs to free the allocated string etype_s.
1330 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1331 krb5_enctype enctype,
1332 char **etype_s)
1334 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1335 return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1336 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1337 char buf[256];
1338 krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1339 if (ret) {
1340 return ret;
1342 *etype_s = SMB_STRDUP(buf);
1343 if (!*etype_s) {
1344 return ENOMEM;
1346 return ret;
1347 #else
1348 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1349 #endif
1352 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1353 #ifndef MAX_KEYTAB_NAME_LEN
1354 #define MAX_KEYTAB_NAME_LEN 1100
1355 #endif
1358 * @brief Open a key table readonly or with readwrite access.
1360 * Allows one to use a different keytab than the default one using a relative
1361 * path to the keytab.
1363 * @param[in] context The library context
1365 * @param[in] keytab_name_req The path to the key table.
1367 * @param[in] write_access Open with readwrite access.
1369 * @param[in] keytab A pointer o the opended key table.
1371 * The keytab pointer should be freed using krb5_kt_close().
1373 * @return 0 on success, a Kerberos error code otherwise.
1375 krb5_error_code smb_krb5_kt_open_relative(krb5_context context,
1376 const char *keytab_name_req,
1377 bool write_access,
1378 krb5_keytab *keytab)
1380 krb5_error_code ret = 0;
1381 TALLOC_CTX *mem_ctx;
1382 char keytab_string[MAX_KEYTAB_NAME_LEN];
1383 char *kt_str = NULL;
1384 bool found_valid_name = false;
1385 const char *pragma = "FILE";
1386 const char *tmp = NULL;
1388 if (!write_access && !keytab_name_req) {
1389 /* caller just wants to read the default keytab readonly, so be it */
1390 return krb5_kt_default(context, keytab);
1393 mem_ctx = talloc_init("smb_krb5_open_keytab");
1394 if (!mem_ctx) {
1395 return ENOMEM;
1398 #ifdef HAVE_WRFILE_KEYTAB
1399 if (write_access) {
1400 pragma = "WRFILE";
1402 #endif
1404 if (keytab_name_req) {
1406 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1407 ret = KRB5_CONFIG_NOTENUFSPACE;
1408 goto out;
1411 if ((strncmp(keytab_name_req, "WRFILE:", 7) == 0) ||
1412 (strncmp(keytab_name_req, "FILE:", 5) == 0)) {
1413 tmp = keytab_name_req;
1414 goto resolve;
1417 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1418 if (!tmp) {
1419 ret = ENOMEM;
1420 goto out;
1423 goto resolve;
1426 /* we need to handle more complex keytab_strings, like:
1427 * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1429 ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1430 if (ret) {
1431 goto out;
1434 DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1436 tmp = talloc_strdup(mem_ctx, keytab_string);
1437 if (!tmp) {
1438 ret = ENOMEM;
1439 goto out;
1442 if (strncmp(tmp, "ANY:", 4) == 0) {
1443 tmp += 4;
1446 memset(&keytab_string, '\0', sizeof(keytab_string));
1448 while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1449 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1450 found_valid_name = true;
1451 tmp = kt_str;
1452 tmp += 7;
1455 if (strncmp(kt_str, "FILE:", 5) == 0) {
1456 found_valid_name = true;
1457 tmp = kt_str;
1458 tmp += 5;
1461 if (tmp[0] == '/') {
1462 /* Treat as a FILE: keytab definition. */
1463 found_valid_name = true;
1466 if (found_valid_name) {
1467 if (tmp[0] != '/') {
1468 ret = KRB5_KT_BADNAME;
1469 goto out;
1472 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1473 if (!tmp) {
1474 ret = ENOMEM;
1475 goto out;
1477 break;
1481 if (!found_valid_name) {
1482 ret = KRB5_KT_UNKNOWN_TYPE;
1483 goto out;
1486 resolve:
1487 DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1488 ret = krb5_kt_resolve(context, tmp, keytab);
1490 out:
1491 TALLOC_FREE(mem_ctx);
1492 return ret;
1496 * @brief Open a key table readonly or with readwrite access.
1498 * Allows one to use a different keytab than the default one. The path needs to be
1499 * an absolute path or an error will be returned.
1501 * @param[in] context The library context
1503 * @param[in] keytab_name_req The path to the key table.
1505 * @param[in] write_access Open with readwrite access.
1507 * @param[in] keytab A pointer o the opended key table.
1509 * The keytab pointer should be freed using krb5_kt_close().
1511 * @return 0 on success, a Kerberos error code otherwise.
1513 krb5_error_code smb_krb5_kt_open(krb5_context context,
1514 const char *keytab_name_req,
1515 bool write_access,
1516 krb5_keytab *keytab)
1518 int cmp;
1520 if (keytab_name_req == NULL) {
1521 return KRB5_KT_BADNAME;
1524 if (keytab_name_req[0] == '/') {
1525 goto open_keytab;
1528 cmp = strncmp(keytab_name_req, "FILE:/", 6);
1529 if (cmp == 0) {
1530 goto open_keytab;
1533 cmp = strncmp(keytab_name_req, "WRFILE:/", 8);
1534 if (cmp == 0) {
1535 goto open_keytab;
1538 DBG_WARNING("ERROR: Invalid keytab name: %s\n", keytab_name_req);
1540 return KRB5_KT_BADNAME;
1542 open_keytab:
1543 return smb_krb5_kt_open_relative(context,
1544 keytab_name_req,
1545 write_access,
1546 keytab);
1550 * @brief Get a key table name.
1552 * @param[in] mem_ctx The talloc context to use for allocation.
1554 * @param[in] context The library context.
1556 * @param[in] keytab The key table to get the name from.
1558 * @param[in] keytab_name A talloc'ed string of the key table name.
1560 * The talloc'ed name string needs to be freed with talloc_free().
1562 * @return 0 on success, a Kerberos error code otherwise.
1564 krb5_error_code smb_krb5_kt_get_name(TALLOC_CTX *mem_ctx,
1565 krb5_context context,
1566 krb5_keytab keytab,
1567 const char **keytab_name)
1569 char keytab_string[MAX_KEYTAB_NAME_LEN];
1570 krb5_error_code ret = 0;
1572 ret = krb5_kt_get_name(context, keytab,
1573 keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1574 if (ret) {
1575 return ret;
1578 *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1579 if (!*keytab_name) {
1580 return ENOMEM;
1583 return ret;
1587 * @brief Seek and delete old entries in a keytab based on the passed
1588 * principal.
1590 * @param[in] context The KRB5 context to use.
1592 * @param[in] keytab The keytab to operate on.
1594 * @param[in] kvno The kvnco to use.
1596 * @param[in] princ_s The principal as a string to search for.
1598 * @param[in] princ The principal as a krb5_principal to search for.
1600 * @param[in] flush Whether to flush the complete keytab.
1602 * @param[in] keep_old_entries Keep the entry with the previous kvno.
1604 * @retval 0 on Sucess
1606 * @return An appropriate KRB5 error code.
1608 krb5_error_code smb_krb5_kt_seek_and_delete_old_entries(krb5_context context,
1609 krb5_keytab keytab,
1610 krb5_kvno kvno,
1611 krb5_enctype enctype,
1612 const char *princ_s,
1613 krb5_principal princ,
1614 bool flush,
1615 bool keep_old_entries)
1617 krb5_error_code ret;
1618 krb5_kt_cursor cursor;
1619 krb5_keytab_entry kt_entry;
1620 char *ktprinc = NULL;
1621 krb5_kvno old_kvno = kvno - 1;
1622 TALLOC_CTX *tmp_ctx;
1624 ZERO_STRUCT(cursor);
1625 ZERO_STRUCT(kt_entry);
1627 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1628 if (ret == KRB5_KT_END || ret == ENOENT ) {
1629 /* no entries */
1630 return 0;
1633 tmp_ctx = talloc_new(NULL);
1634 if (tmp_ctx == NULL) {
1635 return ENOMEM;
1638 DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1639 while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1640 bool name_ok = false;
1641 krb5_enctype kt_entry_enctype =
1642 smb_krb5_kt_get_enctype_from_entry(&kt_entry);
1644 if (!flush && (princ_s != NULL)) {
1645 ret = smb_krb5_unparse_name(tmp_ctx, context,
1646 kt_entry.principal,
1647 &ktprinc);
1648 if (ret) {
1649 DEBUG(1, (__location__
1650 ": smb_krb5_unparse_name failed "
1651 "(%s)\n", error_message(ret)));
1652 goto out;
1655 #ifdef HAVE_KRB5_KT_COMPARE
1656 name_ok = krb5_kt_compare(context, &kt_entry,
1657 princ, 0, 0);
1658 #else
1659 name_ok = (strcmp(ktprinc, princ_s) == 0);
1660 #endif
1662 if (!name_ok) {
1663 DEBUG(10, (__location__ ": ignoring keytab "
1664 "entry principal %s, kvno = %d\n",
1665 ktprinc, kt_entry.vno));
1667 /* Not a match,
1668 * just free this entry and continue. */
1669 ret = smb_krb5_kt_free_entry(context,
1670 &kt_entry);
1671 ZERO_STRUCT(kt_entry);
1672 if (ret) {
1673 DEBUG(1, (__location__
1674 ": smb_krb5_kt_free_entry "
1675 "failed (%s)\n",
1676 error_message(ret)));
1677 goto out;
1680 TALLOC_FREE(ktprinc);
1681 continue;
1684 TALLOC_FREE(ktprinc);
1687 /*------------------------------------------------------------
1688 * Save the entries with kvno - 1. This is what microsoft does
1689 * to allow people with existing sessions that have kvno - 1
1690 * to still work. Otherwise, when the password for the machine
1691 * changes, all kerberizied sessions will 'break' until either
1692 * the client reboots or the client's session key expires and
1693 * they get a new session ticket with the new kvno.
1694 * Some keytab files only store the kvno in 8bits, limit
1695 * the compare accordingly.
1698 if (!flush && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1699 DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1700 "entry for principal: %s.\n",
1701 old_kvno, princ_s));
1702 continue;
1705 if (keep_old_entries) {
1706 DEBUG(5, (__location__ ": Saving old (kvno %d) "
1707 "entry for principal: %s.\n",
1708 kvno, princ_s));
1709 continue;
1712 if (!flush &&
1713 ((kt_entry.vno & 0xff) == (kvno & 0xff)) &&
1714 (kt_entry_enctype != enctype))
1716 DEBUG(5, (__location__ ": Saving entry with kvno [%d] "
1717 "enctype [%d] for principal: %s.\n",
1718 kvno, kt_entry_enctype, princ_s));
1719 continue;
1722 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1723 "(kvno %d) - trying to remove it.\n",
1724 princ_s, kt_entry.vno));
1726 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1727 ZERO_STRUCT(cursor);
1728 if (ret) {
1729 DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1730 "failed (%s)\n", error_message(ret)));
1731 goto out;
1733 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1734 if (ret) {
1735 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1736 "failed (%s)\n", error_message(ret)));
1737 goto out;
1740 DEBUG(5, (__location__ ": removed old entry for principal: "
1741 "%s (kvno %d).\n", princ_s, kt_entry.vno));
1743 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1744 if (ret) {
1745 DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1746 "(%s)\n", error_message(ret)));
1747 goto out;
1749 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1750 ZERO_STRUCT(kt_entry);
1751 if (ret) {
1752 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1753 "failed (%s)\n", error_message(ret)));
1754 goto out;
1758 out:
1759 talloc_free(tmp_ctx);
1760 if (!all_zero((uint8_t *)&kt_entry, sizeof(kt_entry))) {
1761 smb_krb5_kt_free_entry(context, &kt_entry);
1763 if (!all_zero((uint8_t *)&cursor, sizeof(cursor))) {
1764 krb5_kt_end_seq_get(context, keytab, &cursor);
1766 return ret;
1770 * @brief Add a keytab entry for the given principal
1772 * @param[in] context The krb5 context to use.
1774 * @param[in] keytab The keytab to add the entry to.
1776 * @param[in] kvno The kvno to use.
1778 * @param[in] princ_s The principal as a string.
1780 * @param[in] salt_principal The salt principal to salt the password with.
1781 * Only needed for keys which support salting.
1782 * If no salt is used set no_salt to false and
1783 * pass NULL here.
1785 * @param[in] enctype The encryption type of the keytab entry.
1787 * @param[in] password The password of the keytab entry.
1789 * @param[in] no_salt If the password should not be salted. Normally
1790 * this is only set to false for encryption types
1791 * which do not support salting like RC4.
1793 * @param[in] keep_old_entries Whether to keep or delete old keytab entries.
1795 * @retval 0 on Success
1797 * @return A corresponding KRB5 error code.
1799 * @see smb_krb5_kt_open()
1801 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1802 krb5_keytab keytab,
1803 krb5_kvno kvno,
1804 const char *princ_s,
1805 const char *salt_principal,
1806 krb5_enctype enctype,
1807 krb5_data *password,
1808 bool no_salt,
1809 bool keep_old_entries)
1811 krb5_error_code ret;
1812 krb5_keytab_entry kt_entry;
1813 krb5_principal princ = NULL;
1814 krb5_keyblock *keyp;
1816 ZERO_STRUCT(kt_entry);
1818 ret = smb_krb5_parse_name(context, princ_s, &princ);
1819 if (ret) {
1820 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1821 "failed (%s)\n", princ_s, error_message(ret)));
1822 goto out;
1825 /* Seek and delete old keytab entries */
1826 ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1827 keytab,
1828 kvno,
1829 enctype,
1830 princ_s,
1831 princ,
1832 false,
1833 keep_old_entries);
1834 if (ret) {
1835 goto out;
1838 /* If we get here, we have deleted all the old entries with kvno's
1839 * not equal to the current kvno-1. */
1841 keyp = KRB5_KT_KEY(&kt_entry);
1843 if (no_salt) {
1844 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1845 if (KRB5_KEY_DATA(keyp) == NULL) {
1846 ret = ENOMEM;
1847 goto out;
1849 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1850 KRB5_KEY_LENGTH(keyp) = password->length;
1851 KRB5_KEY_TYPE(keyp) = enctype;
1852 } else {
1853 krb5_principal salt_princ = NULL;
1855 /* Now add keytab entries for all encryption types */
1856 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1857 if (ret) {
1858 DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1859 salt_principal, error_message(ret));
1860 goto out;
1863 ret = smb_krb5_create_key_from_string(context,
1864 salt_princ,
1865 NULL,
1866 password,
1867 enctype,
1868 keyp);
1869 krb5_free_principal(context, salt_princ);
1870 if (ret != 0) {
1871 goto out;
1875 kt_entry.principal = princ;
1876 kt_entry.vno = kvno;
1878 DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1879 "encryption type (%d) and version (%d)\n",
1880 princ_s, enctype, kt_entry.vno));
1881 ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1882 krb5_free_keyblock_contents(context, keyp);
1883 ZERO_STRUCT(kt_entry);
1884 if (ret) {
1885 DEBUG(1, (__location__ ": adding entry to keytab "
1886 "failed (%s)\n", error_message(ret)));
1887 goto out;
1890 out:
1891 if (princ) {
1892 krb5_free_principal(context, princ);
1895 return ret;
1898 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1899 defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1900 defined(HAVE_KRB5_GET_CREDS)
1901 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1902 krb5_ccache ccache,
1903 krb5_principal me,
1904 krb5_principal server,
1905 krb5_principal impersonate_princ,
1906 krb5_creds **out_creds)
1908 krb5_error_code ret;
1909 krb5_get_creds_opt opt;
1911 ret = krb5_get_creds_opt_alloc(context, &opt);
1912 if (ret) {
1913 goto done;
1915 krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1917 if (impersonate_princ) {
1918 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1919 impersonate_princ);
1920 if (ret) {
1921 goto done;
1925 ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1926 if (ret) {
1927 goto done;
1930 done:
1931 if (opt) {
1932 krb5_get_creds_opt_free(context, opt);
1934 return ret;
1936 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1938 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1940 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1941 krb5_error_code KRB5_CALLCONV
1942 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1943 krb5_ccache ccache, krb5_creds *in_creds,
1944 krb5_data *subject_cert,
1945 krb5_creds **out_creds);
1946 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1948 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1949 krb5_ccache ccache,
1950 krb5_principal me,
1951 krb5_principal server,
1952 krb5_principal impersonate_princ,
1953 krb5_creds **out_creds)
1955 krb5_error_code ret;
1956 krb5_creds in_creds;
1958 ZERO_STRUCT(in_creds);
1960 if (impersonate_princ) {
1962 in_creds.server = me;
1963 in_creds.client = impersonate_princ;
1965 ret = krb5_get_credentials_for_user(context,
1966 0, /* krb5_flags options */
1967 ccache,
1968 &in_creds,
1969 NULL, /* krb5_data *subject_cert */
1970 out_creds);
1971 } else {
1972 in_creds.client = me;
1973 in_creds.server = server;
1975 ret = krb5_get_credentials(context, 0, ccache,
1976 &in_creds, out_creds);
1979 return ret;
1981 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1984 * smb_krb5_get_credentials
1986 * @brief Get krb5 credentials for a server
1988 * @param[in] context An initialized krb5_context
1989 * @param[in] ccache An initialized krb5_ccache
1990 * @param[in] me The krb5_principal of the caller
1991 * @param[in] server The krb5_principal of the requested service
1992 * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1993 * @param[out] out_creds The returned krb5_creds structure
1994 * @return krb5_error_code
1997 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1998 krb5_ccache ccache,
1999 krb5_principal me,
2000 krb5_principal server,
2001 krb5_principal impersonate_princ,
2002 krb5_creds **out_creds)
2004 krb5_error_code ret;
2005 krb5_creds *creds = NULL;
2007 if (out_creds != NULL) {
2008 *out_creds = NULL;
2011 if (impersonate_princ) {
2012 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
2013 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
2014 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
2015 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
2016 #else
2017 ret = ENOTSUP;
2018 #endif
2019 } else {
2020 krb5_creds in_creds;
2022 ZERO_STRUCT(in_creds);
2024 in_creds.client = me;
2025 in_creds.server = server;
2027 ret = krb5_get_credentials(context, 0, ccache,
2028 &in_creds, &creds);
2030 if (ret) {
2031 goto done;
2034 if (out_creds) {
2035 *out_creds = creds;
2038 done:
2039 if (creds && ret) {
2040 krb5_free_creds(context, creds);
2043 return ret;
2047 * @brief Initialize a krb5_keyblock with the given data.
2049 * Initialized a new keyblock, allocates the contents fo the key and
2050 * copies the data into the keyblock.
2052 * @param[in] context The library context
2054 * @param[in] enctype The encryption type.
2056 * @param[in] data The date to initialize the keyblock with.
2058 * @param[in] length The length of the keyblock.
2060 * @param[in] key Newly allocated keyblock structure.
2062 * The key date must be freed using krb5_free_keyblock_contents() when it is
2063 * no longer needed.
2065 * @return 0 on success, a Kerberos error code otherwise.
2067 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
2068 krb5_enctype enctype,
2069 const void *data,
2070 size_t length,
2071 krb5_keyblock *key)
2073 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
2074 return krb5_keyblock_init(context, enctype, data, length, key);
2075 #else
2076 memset(key, 0, sizeof(krb5_keyblock));
2077 KRB5_KEY_DATA(key) = SMB_MALLOC(length);
2078 if (NULL == KRB5_KEY_DATA(key)) {
2079 return ENOMEM;
2081 memcpy(KRB5_KEY_DATA(key), data, length);
2082 KRB5_KEY_LENGTH(key) = length;
2083 KRB5_KEY_TYPE(key) = enctype;
2084 return 0;
2085 #endif
2089 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2091 * This function uses a keyblock rather than needing the original password.
2093 * @param[in] ctx The library context
2095 * @param[in] cc The credential cache to put the tgt in.
2097 * @param[in] principal The client princial
2099 * @param[in] keyblock The keyblock to use.
2101 * @param[in] target_service The service name of the initial credentials (or NULL).
2103 * @param[in] krb_options Initial credential options.
2105 * @param[in] expire_time A pointer to store the experation time of the
2106 * credentials (or NULL).
2108 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2109 * valid (or NULL).
2111 * @return 0 on success, a Kerberos error code otherwise.
2113 krb5_error_code smb_krb5_kinit_keyblock_ccache(krb5_context ctx,
2114 krb5_ccache cc,
2115 krb5_principal principal,
2116 krb5_keyblock *keyblock,
2117 const char *target_service,
2118 krb5_get_init_creds_opt *krb_options,
2119 time_t *expire_time,
2120 time_t *kdc_time)
2122 krb5_error_code code = 0;
2123 krb5_creds my_creds;
2125 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
2126 code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
2127 keyblock, 0, target_service,
2128 krb_options);
2129 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
2131 #define SMB_CREDS_KEYTAB "MEMORY:tmp_kinit_keyblock_ccache"
2132 char tmp_name[64] = {0};
2133 krb5_keytab_entry entry;
2134 krb5_keytab keytab;
2135 int rc;
2137 memset(&entry, 0, sizeof(entry));
2138 entry.principal = principal;
2139 *(KRB5_KT_KEY(&entry)) = *keyblock;
2141 rc = snprintf(tmp_name, sizeof(tmp_name),
2142 "%s-%p",
2143 SMB_CREDS_KEYTAB,
2144 &my_creds);
2145 if (rc < 0) {
2146 return KRB5_KT_BADNAME;
2148 code = krb5_kt_resolve(ctx, tmp_name, &keytab);
2149 if (code) {
2150 return code;
2153 code = krb5_kt_add_entry(ctx, keytab, &entry);
2154 if (code) {
2155 (void)krb5_kt_close(ctx, keytab);
2156 goto done;
2159 code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
2160 keytab, 0, target_service,
2161 krb_options);
2162 (void)krb5_kt_close(ctx, keytab);
2164 #else
2165 #error krb5_get_init_creds_keyblock not available!
2166 #endif
2167 if (code) {
2168 return code;
2171 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2173 * We need to store the principal as returned from the KDC to the
2174 * credentials cache. If we don't do that the KRB5 library is not
2175 * able to find the tickets it is looking for
2177 principal = my_creds.client;
2178 #endif
2179 code = krb5_cc_initialize(ctx, cc, principal);
2180 if (code) {
2181 goto done;
2184 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2185 if (code) {
2186 goto done;
2189 if (expire_time) {
2190 *expire_time = (time_t) my_creds.times.endtime;
2193 if (kdc_time) {
2194 *kdc_time = (time_t) my_creds.times.starttime;
2197 code = 0;
2198 done:
2199 krb5_free_cred_contents(ctx, &my_creds);
2200 return code;
2204 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2206 * @param[in] ctx The library context
2208 * @param[in] cc The credential cache to put the tgt in.
2210 * @param[in] principal The client princial
2212 * @param[in] password The password (or NULL).
2214 * @param[in] target_service The service name of the initial credentials (or NULL).
2216 * @param[in] krb_options Initial credential options.
2218 * @param[in] expire_time A pointer to store the experation time of the
2219 * credentials (or NULL).
2221 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2222 * valid (or NULL).
2224 * @return 0 on success, a Kerberos error code otherwise.
2226 krb5_error_code smb_krb5_kinit_password_ccache(krb5_context ctx,
2227 krb5_ccache cc,
2228 krb5_principal principal,
2229 const char *password,
2230 const char *target_service,
2231 krb5_get_init_creds_opt *krb_options,
2232 time_t *expire_time,
2233 time_t *kdc_time)
2235 krb5_error_code code = 0;
2236 krb5_creds my_creds;
2238 code = krb5_get_init_creds_password(ctx, &my_creds, principal,
2239 password, NULL, NULL, 0,
2240 target_service, krb_options);
2241 if (code) {
2242 return code;
2246 * We need to store the principal as returned from the KDC to the
2247 * credentials cache. If we don't do that the KRB5 library is not
2248 * able to find the tickets it is looking for
2250 principal = my_creds.client;
2251 code = krb5_cc_initialize(ctx, cc, principal);
2252 if (code) {
2253 goto done;
2256 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2257 if (code) {
2258 goto done;
2261 if (expire_time) {
2262 *expire_time = (time_t) my_creds.times.endtime;
2265 if (kdc_time) {
2266 *kdc_time = (time_t) my_creds.times.starttime;
2269 code = 0;
2270 done:
2271 krb5_free_cred_contents(ctx, &my_creds);
2272 return code;
2275 #ifdef SAMBA4_USES_HEIMDAL
2277 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2279 * @param[in] ctx The library context
2281 * @param[in] cc The credential cache to store the tgt in.
2283 * @param[in] principal The initial client princial.
2285 * @param[in] password The password (or NULL).
2287 * @param[in] impersonate_principal The impersonatiion principal (or NULL).
2289 * @param[in] self_service The local service for S4U2Self if
2290 * impersonate_principal is specified).
2292 * @param[in] target_service The service name of the initial credentials
2293 * (kpasswd/REALM or a remote service). It defaults
2294 * to the krbtgt if NULL.
2296 * @param[in] krb_options Initial credential options.
2298 * @param[in] expire_time A pointer to store the experation time of the
2299 * credentials (or NULL).
2301 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2302 * valid (or NULL).
2304 * @return 0 on success, a Kerberos error code otherwise.
2306 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
2307 krb5_ccache store_cc,
2308 krb5_principal init_principal,
2309 const char *init_password,
2310 krb5_principal impersonate_principal,
2311 const char *self_service,
2312 const char *target_service,
2313 krb5_get_init_creds_opt *krb_options,
2314 time_t *expire_time,
2315 time_t *kdc_time)
2317 krb5_error_code code = 0;
2318 krb5_get_creds_opt options;
2319 krb5_principal store_principal;
2320 krb5_creds store_creds;
2321 krb5_creds *s4u2self_creds;
2322 Ticket s4u2self_ticket;
2323 size_t s4u2self_ticketlen;
2324 krb5_creds *s4u2proxy_creds;
2325 krb5_principal self_princ;
2326 bool s4u2proxy;
2327 krb5_principal target_princ;
2328 krb5_ccache tmp_cc;
2329 const char *self_realm;
2330 const char *client_realm = NULL;
2331 krb5_principal blacklist_principal = NULL;
2332 krb5_principal whitelist_principal = NULL;
2334 code = krb5_get_init_creds_password(ctx, &store_creds,
2335 init_principal,
2336 init_password,
2337 NULL, NULL,
2339 NULL,
2340 krb_options);
2341 if (code != 0) {
2342 return code;
2345 store_principal = init_principal;
2348 * We are trying S4U2Self now:
2350 * As we do not want to expose our TGT in the
2351 * krb5_ccache, which is also holds the impersonated creds.
2353 * Some low level krb5/gssapi function might use the TGT
2354 * identity and let the client act as our machine account.
2356 * We need to avoid that and use a temporary krb5_ccache
2357 * in order to pass our TGT to the krb5_get_creds() function.
2359 code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
2360 if (code != 0) {
2361 krb5_free_cred_contents(ctx, &store_creds);
2362 return code;
2365 code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
2366 if (code != 0) {
2367 krb5_cc_destroy(ctx, tmp_cc);
2368 krb5_free_cred_contents(ctx, &store_creds);
2369 return code;
2372 code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
2373 if (code != 0) {
2374 krb5_free_cred_contents(ctx, &store_creds);
2375 krb5_cc_destroy(ctx, tmp_cc);
2376 return code;
2380 * we need to remember the client principal of our
2381 * TGT and make sure the KDC does not return this
2382 * in the impersonated tickets. This can happen
2383 * if the KDC does not support S4U2Self and S4U2Proxy.
2385 blacklist_principal = store_creds.client;
2386 store_creds.client = NULL;
2387 krb5_free_cred_contents(ctx, &store_creds);
2390 * Check if we also need S4U2Proxy or if S4U2Self is
2391 * enough in order to get a ticket for the target.
2393 if (target_service == NULL) {
2394 s4u2proxy = false;
2395 } else if (strcmp(target_service, self_service) == 0) {
2396 s4u2proxy = false;
2397 } else {
2398 s4u2proxy = true;
2402 * For S4U2Self we need our own service principal,
2403 * which belongs to our own realm (available on
2404 * our client principal).
2406 self_realm = krb5_principal_get_realm(ctx, init_principal);
2408 code = krb5_parse_name(ctx, self_service, &self_princ);
2409 if (code != 0) {
2410 krb5_free_principal(ctx, blacklist_principal);
2411 krb5_cc_destroy(ctx, tmp_cc);
2412 return code;
2415 code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2416 if (code != 0) {
2417 krb5_free_principal(ctx, blacklist_principal);
2418 krb5_free_principal(ctx, self_princ);
2419 krb5_cc_destroy(ctx, tmp_cc);
2420 return code;
2423 code = krb5_get_creds_opt_alloc(ctx, &options);
2424 if (code != 0) {
2425 krb5_free_principal(ctx, blacklist_principal);
2426 krb5_free_principal(ctx, self_princ);
2427 krb5_cc_destroy(ctx, tmp_cc);
2428 return code;
2431 if (s4u2proxy) {
2433 * If we want S4U2Proxy, we need the forwardable flag
2434 * on the S4U2Self ticket.
2436 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2439 code = krb5_get_creds_opt_set_impersonate(ctx, options,
2440 impersonate_principal);
2441 if (code != 0) {
2442 krb5_get_creds_opt_free(ctx, options);
2443 krb5_free_principal(ctx, blacklist_principal);
2444 krb5_free_principal(ctx, self_princ);
2445 krb5_cc_destroy(ctx, tmp_cc);
2446 return code;
2449 code = krb5_get_creds(ctx, options, tmp_cc,
2450 self_princ, &s4u2self_creds);
2451 krb5_get_creds_opt_free(ctx, options);
2452 krb5_free_principal(ctx, self_princ);
2453 if (code != 0) {
2454 krb5_free_principal(ctx, blacklist_principal);
2455 krb5_cc_destroy(ctx, tmp_cc);
2456 return code;
2459 if (!s4u2proxy) {
2460 krb5_cc_destroy(ctx, tmp_cc);
2463 * Now make sure we store the impersonated principal
2464 * and creds instead of the TGT related stuff
2465 * in the krb5_ccache of the caller.
2467 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2468 &store_creds);
2469 krb5_free_creds(ctx, s4u2self_creds);
2470 if (code != 0) {
2471 return code;
2475 * It's important to store the principal the KDC
2476 * returned, as otherwise the caller would not find
2477 * the S4U2Self ticket in the krb5_ccache lookup.
2479 store_principal = store_creds.client;
2480 goto store;
2484 * We are trying S4U2Proxy:
2486 * We need the ticket from the S4U2Self step
2487 * and our TGT in order to get the delegated ticket.
2489 code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2490 s4u2self_creds->ticket.length,
2491 &s4u2self_ticket,
2492 &s4u2self_ticketlen);
2493 if (code != 0) {
2494 krb5_free_creds(ctx, s4u2self_creds);
2495 krb5_free_principal(ctx, blacklist_principal);
2496 krb5_cc_destroy(ctx, tmp_cc);
2497 return code;
2501 * we need to remember the client principal of the
2502 * S4U2Self stage and as it needs to match the one we
2503 * will get for the S4U2Proxy stage. We need this
2504 * in order to detect KDCs which does not support S4U2Proxy.
2506 whitelist_principal = s4u2self_creds->client;
2507 s4u2self_creds->client = NULL;
2508 krb5_free_creds(ctx, s4u2self_creds);
2511 * For S4U2Proxy we also got a target service principal,
2512 * which also belongs to our own realm (available on
2513 * our client principal).
2515 code = krb5_parse_name(ctx, target_service, &target_princ);
2516 if (code != 0) {
2517 free_Ticket(&s4u2self_ticket);
2518 krb5_free_principal(ctx, whitelist_principal);
2519 krb5_free_principal(ctx, blacklist_principal);
2520 krb5_cc_destroy(ctx, tmp_cc);
2521 return code;
2524 code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2525 if (code != 0) {
2526 free_Ticket(&s4u2self_ticket);
2527 krb5_free_principal(ctx, target_princ);
2528 krb5_free_principal(ctx, whitelist_principal);
2529 krb5_free_principal(ctx, blacklist_principal);
2530 krb5_cc_destroy(ctx, tmp_cc);
2531 return code;
2534 code = krb5_get_creds_opt_alloc(ctx, &options);
2535 if (code != 0) {
2536 free_Ticket(&s4u2self_ticket);
2537 krb5_free_principal(ctx, target_princ);
2538 krb5_free_principal(ctx, whitelist_principal);
2539 krb5_free_principal(ctx, blacklist_principal);
2540 krb5_cc_destroy(ctx, tmp_cc);
2541 return code;
2544 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2545 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2547 code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2548 free_Ticket(&s4u2self_ticket);
2549 if (code != 0) {
2550 krb5_get_creds_opt_free(ctx, options);
2551 krb5_free_principal(ctx, target_princ);
2552 krb5_free_principal(ctx, whitelist_principal);
2553 krb5_free_principal(ctx, blacklist_principal);
2554 krb5_cc_destroy(ctx, tmp_cc);
2555 return code;
2558 code = krb5_get_creds(ctx, options, tmp_cc,
2559 target_princ, &s4u2proxy_creds);
2560 krb5_get_creds_opt_free(ctx, options);
2561 krb5_free_principal(ctx, target_princ);
2562 krb5_cc_destroy(ctx, tmp_cc);
2563 if (code != 0) {
2564 krb5_free_principal(ctx, whitelist_principal);
2565 krb5_free_principal(ctx, blacklist_principal);
2566 return code;
2570 * Now make sure we store the impersonated principal
2571 * and creds instead of the TGT related stuff
2572 * in the krb5_ccache of the caller.
2574 code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2575 &store_creds);
2576 krb5_free_creds(ctx, s4u2proxy_creds);
2577 if (code != 0) {
2578 krb5_free_principal(ctx, whitelist_principal);
2579 krb5_free_principal(ctx, blacklist_principal);
2580 return code;
2584 * It's important to store the principal the KDC
2585 * returned, as otherwise the caller would not find
2586 * the S4U2Self ticket in the krb5_ccache lookup.
2588 store_principal = store_creds.client;
2590 store:
2591 if (blacklist_principal &&
2592 krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2593 char *sp = NULL;
2594 char *ip = NULL;
2596 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2597 if (code != 0) {
2598 sp = NULL;
2600 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2601 if (code != 0) {
2602 ip = NULL;
2604 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2605 "KDC returned self principal[%s] while impersonating [%s]\n",
2606 sp?sp:"<no memory>",
2607 ip?ip:"<no memory>"));
2609 SAFE_FREE(sp);
2610 SAFE_FREE(ip);
2612 krb5_free_principal(ctx, whitelist_principal);
2613 krb5_free_principal(ctx, blacklist_principal);
2614 krb5_free_cred_contents(ctx, &store_creds);
2615 return KRB5_FWD_BAD_PRINCIPAL;
2617 if (blacklist_principal) {
2618 krb5_free_principal(ctx, blacklist_principal);
2621 if (whitelist_principal &&
2622 !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2623 char *sp = NULL;
2624 char *ep = NULL;
2626 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2627 if (code != 0) {
2628 sp = NULL;
2630 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2631 if (code != 0) {
2632 ep = NULL;
2634 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2635 "KDC returned wrong principal[%s] we expected [%s]\n",
2636 sp?sp:"<no memory>",
2637 ep?ep:"<no memory>"));
2639 SAFE_FREE(sp);
2640 SAFE_FREE(ep);
2642 krb5_free_principal(ctx, whitelist_principal);
2643 krb5_free_cred_contents(ctx, &store_creds);
2644 return KRB5_FWD_BAD_PRINCIPAL;
2646 if (whitelist_principal) {
2647 krb5_free_principal(ctx, whitelist_principal);
2650 code = krb5_cc_initialize(ctx, store_cc, store_principal);
2651 if (code != 0) {
2652 krb5_free_cred_contents(ctx, &store_creds);
2653 return code;
2656 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2657 if (code != 0) {
2658 krb5_free_cred_contents(ctx, &store_creds);
2659 return code;
2662 client_realm = krb5_principal_get_realm(ctx, store_creds.client);
2663 if (client_realm != NULL) {
2665 * Because the CANON flag doesn't have any impact
2666 * on the impersonate_principal => store_creds.client
2667 * realm mapping. We need to store the credentials twice,
2668 * once with the returned realm and once with the
2669 * realm of impersonate_principal.
2671 code = krb5_principal_set_realm(ctx, store_creds.server,
2672 client_realm);
2673 if (code != 0) {
2674 krb5_free_cred_contents(ctx, &store_creds);
2675 return code;
2678 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2679 if (code != 0) {
2680 krb5_free_cred_contents(ctx, &store_creds);
2681 return code;
2685 if (expire_time) {
2686 *expire_time = (time_t) store_creds.times.endtime;
2689 if (kdc_time) {
2690 *kdc_time = (time_t) store_creds.times.starttime;
2693 krb5_free_cred_contents(ctx, &store_creds);
2695 return 0;
2697 #endif
2699 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2701 * @brief Create a principal name using a variable argument list.
2703 * @param[in] context The library context.
2705 * @param[inout] principal A pointer to the principal structure.
2707 * @param[in] _realm The realm to use. If NULL then the function will
2708 * get the default realm name.
2710 * @param[in] ... A list of 'char *' components, ending with NULL.
2712 * Use krb5_free_principal() to free the principal when it is no longer needed.
2714 * @return 0 on success, a Kerberos error code otherwise.
2716 krb5_error_code smb_krb5_make_principal(krb5_context context,
2717 krb5_principal *principal,
2718 const char *_realm, ...)
2720 krb5_error_code code;
2721 bool free_realm;
2722 char *realm;
2723 va_list ap;
2725 if (_realm) {
2726 realm = discard_const_p(char, _realm);
2727 free_realm = false;
2728 } else {
2729 code = krb5_get_default_realm(context, &realm);
2730 if (code) {
2731 return code;
2733 free_realm = true;
2736 va_start(ap, _realm);
2737 code = krb5_build_principal_alloc_va(context, principal,
2738 strlen(realm), realm,
2739 ap);
2740 va_end(ap);
2742 if (free_realm) {
2743 krb5_free_default_realm(context, realm);
2746 return code;
2748 #endif
2750 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2752 * @brief Get the lifetime of the initial ticket in the cache.
2754 * @param[in] context The kerberos context.
2756 * @param[in] id The credential cache to get the ticket lifetime.
2758 * @param[out] t A pointer to a time value to store the lifetime.
2760 * @return 0 on success, a krb5_error_code on error.
2762 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2763 krb5_ccache id,
2764 time_t *t)
2766 krb5_cc_cursor cursor;
2767 krb5_error_code kerr;
2768 krb5_creds cred;
2769 krb5_timestamp now;
2771 *t = 0;
2773 kerr = krb5_timeofday(context, &now);
2774 if (kerr) {
2775 return kerr;
2778 kerr = krb5_cc_start_seq_get(context, id, &cursor);
2779 if (kerr) {
2780 return kerr;
2783 while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2784 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2785 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2786 #else
2787 if (cred.flags.b.initial) {
2788 #endif
2789 if (now < cred.times.endtime) {
2790 *t = (time_t) (cred.times.endtime - now);
2792 krb5_free_cred_contents(context, &cred);
2793 break;
2795 krb5_free_cred_contents(context, &cred);
2798 krb5_cc_end_seq_get(context, id, &cursor);
2800 return kerr;
2802 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2804 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2805 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2807 free_Checksum(cksum);
2809 #endif
2812 * @brief Compute a checksum operating on a keyblock.
2814 * This function computes a checksum over a PAC using the keyblock for a keyed
2815 * checksum.
2817 * @param[in] mem_ctx A talloc context to alocate the signature on.
2819 * @param[in] pac_data The PAC as input.
2821 * @param[in] context The library context.
2823 * @param[in] keyblock Encryption key for a keyed checksum.
2825 * @param[out] sig_type The checksum type
2827 * @param[out] sig_blob The talloc'ed checksum
2829 * The caller must free the sig_blob with talloc_free() when it is not needed
2830 * anymore.
2832 * @return 0 on success, a Kerberos error code otherwise.
2834 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2835 DATA_BLOB *pac_data,
2836 krb5_context context,
2837 const krb5_keyblock *keyblock,
2838 uint32_t *sig_type,
2839 DATA_BLOB *sig_blob)
2841 krb5_error_code ret;
2842 krb5_checksum cksum;
2843 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2844 krb5_crypto crypto;
2847 ret = krb5_crypto_init(context,
2848 keyblock,
2850 &crypto);
2851 if (ret) {
2852 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2853 smb_get_krb5_error_message(context, ret, mem_ctx)));
2854 return ret;
2856 ret = krb5_create_checksum(context,
2857 crypto,
2858 KRB5_KU_OTHER_CKSUM,
2860 pac_data->data,
2861 pac_data->length,
2862 &cksum);
2863 if (ret) {
2864 DEBUG(2, ("PAC Verification failed: %s\n",
2865 smb_get_krb5_error_message(context, ret, mem_ctx)));
2868 krb5_crypto_destroy(context, crypto);
2870 if (ret) {
2871 return ret;
2874 *sig_type = cksum.cksumtype;
2875 *sig_blob = data_blob_talloc(mem_ctx,
2876 cksum.checksum.data,
2877 cksum.checksum.length);
2878 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2879 krb5_data input;
2881 input.data = (char *)pac_data->data;
2882 input.length = pac_data->length;
2884 ret = krb5_c_make_checksum(context,
2886 keyblock,
2887 KRB5_KEYUSAGE_APP_DATA_CKSUM,
2888 &input,
2889 &cksum);
2890 if (ret) {
2891 DEBUG(2, ("PAC Verification failed: %s\n",
2892 smb_get_krb5_error_message(context, ret, mem_ctx)));
2893 return ret;
2896 *sig_type = cksum.checksum_type;
2897 *sig_blob = data_blob_talloc(mem_ctx,
2898 cksum.contents,
2899 cksum.length);
2901 #else
2902 #error krb5_create_checksum or krb5_c_make_checksum not available
2903 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2904 smb_krb5_free_checksum_contents(context, &cksum);
2906 return 0;
2911 * @brief Get realm of a principal
2913 * @param[in] mem_ctx The talloc ctx to put the result on
2915 * @param[in] context The library context
2917 * @param[in] principal The principal to get the realm from.
2919 * @return A talloced string with the realm or NULL if an error occurred.
2921 char *smb_krb5_principal_get_realm(TALLOC_CTX *mem_ctx,
2922 krb5_context context,
2923 krb5_const_principal principal)
2925 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2926 return talloc_strdup(mem_ctx,
2927 krb5_principal_get_realm(context, principal));
2928 #elif defined(krb5_princ_realm) /* MIT */
2929 const krb5_data *realm;
2930 realm = krb5_princ_realm(context, principal);
2931 return talloc_strndup(mem_ctx, realm->data, realm->length);
2932 #else
2933 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
2934 #endif
2938 * @brief Get realm of a principal
2940 * @param[in] context The library context
2942 * @param[in] principal The principal to set the realm
2944 * @param[in] realm The realm as a string to set.
2946 * @retur 0 on success, a Kerberos error code otherwise.
2948 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
2949 krb5_principal principal,
2950 const char *realm)
2952 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
2953 return krb5_principal_set_realm(context, principal, realm);
2954 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
2955 krb5_error_code ret;
2956 krb5_data data;
2957 krb5_data *old_data;
2959 old_data = krb5_princ_realm(context, principal);
2961 ret = smb_krb5_copy_data_contents(&data,
2962 realm,
2963 strlen(realm));
2964 if (ret) {
2965 return ret;
2968 /* free realm before setting */
2969 free(old_data->data);
2971 krb5_princ_set_realm(context, principal, &data);
2973 return ret;
2974 #else
2975 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
2976 #endif
2981 * @brief Get the realm from the service hostname.
2983 * This function will look for a domain realm mapping in the [domain_realm]
2984 * section of the krb5.conf first and fallback to extract the realm from
2985 * the provided service hostname. As a last resort it will return the
2986 * provided client_realm.
2988 * @param[in] mem_ctx The talloc context
2990 * @param[in] hostname The service hostname
2992 * @param[in] client_realm If we can not find a mapping, fall back to
2993 * this realm.
2995 * @return The realm to use for the service hostname, NULL if a fatal error
2996 * occured.
2998 char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2999 const char *hostname,
3000 const char *client_realm)
3002 #if defined(HAVE_KRB5_REALM_TYPE)
3003 /* Heimdal. */
3004 krb5_realm *realm_list = NULL;
3005 #else
3006 /* MIT */
3007 char **realm_list = NULL;
3008 #endif
3009 char *realm = NULL;
3010 krb5_error_code kerr;
3011 krb5_context ctx = NULL;
3013 kerr = smb_krb5_init_context_common(&ctx);
3014 if (kerr) {
3015 DBG_ERR("kerberos init context failed (%s)\n",
3016 error_message(kerr));
3017 return NULL;
3020 kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
3021 if (kerr == KRB5_ERR_HOST_REALM_UNKNOWN) {
3022 realm_list = NULL;
3023 kerr = 0;
3025 if (kerr != 0) {
3026 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
3027 "failed %s\n",
3028 hostname ? hostname : "(NULL)",
3029 error_message(kerr) ));
3030 goto out;
3033 if (realm_list != NULL &&
3034 realm_list[0] != NULL &&
3035 realm_list[0][0] != '\0') {
3036 realm = talloc_strdup(mem_ctx, realm_list[0]);
3037 if (realm == NULL) {
3038 goto out;
3040 } else {
3041 const char *p = NULL;
3044 * "dc6.samba2003.example.com"
3045 * returns a realm of "SAMBA2003.EXAMPLE.COM"
3047 * "dc6." returns realm as NULL
3049 p = strchr_m(hostname, '.');
3050 if (p != NULL && p[1] != '\0') {
3051 realm = talloc_strdup_upper(mem_ctx, p + 1);
3052 if (realm == NULL) {
3053 goto out;
3058 if (realm == NULL) {
3059 realm = talloc_strdup(mem_ctx, client_realm);
3062 out:
3064 if (ctx) {
3065 if (realm_list) {
3066 krb5_free_host_realm(ctx, realm_list);
3067 realm_list = NULL;
3069 krb5_free_context(ctx);
3070 ctx = NULL;
3072 return realm;
3076 * @brief Get an error string from a Kerberos error code.
3078 * @param[in] context The library context.
3080 * @param[in] code The Kerberos error code.
3082 * @param[in] mem_ctx The talloc context to allocate the error string on.
3084 * @return A talloc'ed error string or NULL if an error occurred.
3086 * The caller must free the returned error string with talloc_free() if not
3087 * needed anymore
3089 char *smb_get_krb5_error_message(krb5_context context,
3090 krb5_error_code code,
3091 TALLOC_CTX *mem_ctx)
3093 char *ret;
3095 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
3096 const char *context_error = krb5_get_error_message(context, code);
3097 if (context_error) {
3098 ret = talloc_asprintf(mem_ctx, "%s: %s",
3099 error_message(code), context_error);
3100 krb5_free_error_message(context, context_error);
3101 return ret;
3103 #endif
3104 ret = talloc_strdup(mem_ctx, error_message(code));
3105 return ret;
3109 * @brief Return the type of a krb5_principal
3111 * @param[in] context The library context.
3113 * @param[in] principal The principal to get the type from.
3115 * @return The integer type of the principal.
3117 int smb_krb5_principal_get_type(krb5_context context,
3118 krb5_const_principal principal)
3120 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
3121 return krb5_principal_get_type(context, principal);
3122 #elif defined(krb5_princ_type) /* MIT */
3123 return krb5_princ_type(context, principal);
3124 #else
3125 #error UNKNOWN_PRINC_GET_TYPE_FUNCTION
3126 #endif
3130 * @brief Set the type of a principal
3132 * @param[in] context The library context
3134 * @param[inout] principal The principal to set the type for.
3136 * @param[in] type The principal type to set.
3138 void smb_krb5_principal_set_type(krb5_context context,
3139 krb5_principal principal,
3140 int type)
3142 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
3143 krb5_principal_set_type(context, principal, type);
3144 #elif defined(krb5_princ_type) /* MIT */
3145 krb5_princ_type(context, principal) = type;
3146 #else
3147 #error UNKNOWN_PRINC_SET_TYPE_FUNCTION
3148 #endif
3151 #if !defined(HAVE_KRB5_WARNX)
3153 * @brief Log a Kerberos message
3155 * It sends the message to com_err.
3157 * @param[in] context The library context
3159 * @param[in] fmt The message format
3161 * @param[in] ... The message arguments
3163 * @return 0 on success.
3165 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
3167 va_list args;
3169 va_start(args, fmt);
3170 com_err_va("samba-kdc", errno, fmt, args);
3171 va_end(args);
3173 return 0;
3175 #endif
3178 * @brief Copy a credential cache.
3180 * @param[in] context The library context.
3182 * @param[in] incc Credential cache to be copied.
3184 * @param[inout] outcc Copy of credential cache to be filled in.
3186 * @return 0 on success, a Kerberos error code otherwise.
3188 krb5_error_code smb_krb5_cc_copy_creds(krb5_context context,
3189 krb5_ccache incc, krb5_ccache outcc)
3191 #ifdef HAVE_KRB5_CC_COPY_CACHE /* Heimdal */
3192 return krb5_cc_copy_cache(context, incc, outcc);
3193 #elif defined(HAVE_KRB5_CC_COPY_CREDS)
3194 krb5_error_code ret;
3195 krb5_principal princ = NULL;
3197 ret = krb5_cc_get_principal(context, incc, &princ);
3198 if (ret != 0) {
3199 return ret;
3201 ret = krb5_cc_initialize(context, outcc, princ);
3202 krb5_free_principal(context, princ);
3203 if (ret != 0) {
3204 return ret;
3206 return krb5_cc_copy_creds(context, incc, outcc);
3207 #else
3208 #error UNKNOWN_KRB5_CC_COPY_CACHE_OR_CREDS_FUNCTION
3209 #endif
3212 /**********************************************************
3213 * ADS KRB5 CALLS
3214 **********************************************************/
3216 static bool ads_cleanup_expired_creds(krb5_context context,
3217 krb5_ccache ccache,
3218 krb5_creds *credsp)
3220 krb5_error_code retval;
3221 const char *cc_type = krb5_cc_get_type(context, ccache);
3223 DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
3224 cc_type, krb5_cc_get_name(context, ccache),
3225 http_timestring(talloc_tos(), credsp->times.endtime)));
3227 /* we will probably need new tickets if the current ones
3228 will expire within 10 seconds.
3230 if (credsp->times.endtime >= (time(NULL) + 10))
3231 return false;
3233 /* heimdal won't remove creds from a file ccache, and
3234 perhaps we shouldn't anyway, since internally we
3235 use memory ccaches, and a FILE one probably means that
3236 we're using creds obtained outside of our exectuable
3238 if (strequal(cc_type, "FILE")) {
3239 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
3240 return false;
3243 retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
3244 if (retval) {
3245 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
3246 error_message(retval)));
3247 /* If we have an error in this, we want to display it,
3248 but continue as though we deleted it */
3250 return true;
3253 /* Allocate and setup the auth context into the state we need. */
3255 static krb5_error_code ads_setup_auth_context(krb5_context context,
3256 krb5_auth_context *auth_context)
3258 krb5_error_code retval;
3260 retval = krb5_auth_con_init(context, auth_context );
3261 if (retval) {
3262 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
3263 error_message(retval)));
3264 return retval;
3267 /* Ensure this is an addressless ticket. */
3268 retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
3269 if (retval) {
3270 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
3271 error_message(retval)));
3274 return retval;
3277 #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)
3278 static krb5_error_code ads_create_gss_checksum(krb5_data *in_data, /* [inout] */
3279 uint32_t gss_flags)
3281 unsigned int orig_length = in_data->length;
3282 unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
3283 char *gss_cksum = NULL;
3285 if (orig_length) {
3286 /* Extra length field for delgated ticket. */
3287 base_cksum_size += 4;
3290 if ((unsigned int)base_cksum_size + orig_length <
3291 (unsigned int)base_cksum_size) {
3292 return EINVAL;
3295 gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
3296 if (gss_cksum == NULL) {
3297 return ENOMEM;
3300 memset(gss_cksum, '\0', base_cksum_size + orig_length);
3301 SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
3304 * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
3305 * This matches the behavior of heimdal and mit.
3307 * And it is needed to work against some closed source
3308 * SMB servers.
3310 * See bug #7883
3312 memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
3314 SIVAL(gss_cksum, 20, gss_flags);
3316 if (orig_length && in_data->data != NULL) {
3317 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
3318 SSVAL(gss_cksum, 26, orig_length);
3319 /* Copy the kerberos KRB_CRED data */
3320 memcpy(gss_cksum + 28, in_data->data, orig_length);
3321 free(in_data->data);
3322 in_data->data = NULL;
3323 in_data->length = 0;
3325 in_data->data = gss_cksum;
3326 in_data->length = base_cksum_size + orig_length;
3327 return 0;
3329 #endif
3332 * We can't use krb5_mk_req because w2k wants the service to be in a particular
3333 * format.
3335 static krb5_error_code ads_krb5_mk_req(krb5_context context,
3336 krb5_auth_context *auth_context,
3337 const krb5_flags ap_req_options,
3338 const char *principal,
3339 krb5_ccache ccache,
3340 krb5_data *outbuf,
3341 time_t *expire_time,
3342 const char *impersonate_princ_s)
3344 krb5_error_code retval;
3345 krb5_principal server;
3346 krb5_principal impersonate_princ = NULL;
3347 krb5_creds *credsp;
3348 krb5_creds creds;
3349 krb5_data in_data;
3350 bool creds_ready = false;
3351 int i = 0, maxtries = 3;
3352 bool ok;
3354 ZERO_STRUCT(in_data);
3356 retval = smb_krb5_parse_name(context, principal, &server);
3357 if (retval != 0) {
3358 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
3359 return retval;
3362 if (impersonate_princ_s) {
3363 retval = smb_krb5_parse_name(context, impersonate_princ_s,
3364 &impersonate_princ);
3365 if (retval) {
3366 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
3367 goto cleanup_princ;
3371 /* obtain ticket & session key */
3372 ZERO_STRUCT(creds);
3373 if ((retval = krb5_copy_principal(context, server, &creds.server))) {
3374 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
3375 error_message(retval)));
3376 goto cleanup_princ;
3379 retval = krb5_cc_get_principal(context, ccache, &creds.client);
3380 if (retval != 0) {
3381 /* This can commonly fail on smbd startup with no ticket in the cache.
3382 * Report at higher level than 1. */
3383 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
3384 error_message(retval)));
3385 goto cleanup_creds;
3388 while (!creds_ready && (i < maxtries)) {
3390 retval = smb_krb5_get_credentials(context,
3391 ccache,
3392 creds.client,
3393 creds.server,
3394 impersonate_princ,
3395 &credsp);
3396 if (retval != 0) {
3397 DBG_WARNING("smb_krb5_get_credentials failed for %s "
3398 "(%s)\n",
3399 principal,
3400 error_message(retval));
3401 goto cleanup_creds;
3404 /* cope with ticket being in the future due to clock skew */
3405 if ((unsigned)credsp->times.starttime > time(NULL)) {
3406 time_t t = time(NULL);
3407 int time_offset =(int)((unsigned)credsp->times.starttime-t);
3408 DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
3409 krb5_set_real_time(context, t + time_offset + 1, 0);
3412 ok = ads_cleanup_expired_creds(context, ccache, credsp);
3413 if (!ok) {
3414 creds_ready = true;
3417 i++;
3420 DBG_DEBUG("Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
3421 principal,
3422 krb5_cc_get_type(context, ccache),
3423 krb5_cc_get_name(context, ccache),
3424 http_timestring(talloc_tos(),
3425 (unsigned)credsp->times.endtime),
3426 (unsigned)credsp->times.endtime);
3428 if (expire_time) {
3429 *expire_time = (time_t)credsp->times.endtime;
3432 /* Allocate the auth_context. */
3433 retval = ads_setup_auth_context(context, auth_context);
3434 if (retval != 0) {
3435 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3436 error_message(retval));
3437 goto cleanup_creds;
3440 #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)
3442 uint32_t gss_flags = 0;
3444 if (credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE) {
3446 * Fetch a forwarded TGT from the KDC so that we can
3447 * hand off a 2nd ticket as part of the kerberos
3448 * exchange.
3451 DBG_INFO("Server marked as OK to delegate to, building "
3452 "forwardable TGT\n");
3454 retval = krb5_auth_con_setuseruserkey(context,
3455 *auth_context,
3456 &credsp->keyblock );
3457 if (retval != 0) {
3458 DBG_WARNING("krb5_auth_con_setuseruserkey "
3459 "failed (%s)\n",
3460 error_message(retval));
3461 goto cleanup_creds;
3464 /* Must use a subkey for forwarded tickets. */
3465 retval = krb5_auth_con_setflags(context,
3466 *auth_context,
3467 KRB5_AUTH_CONTEXT_USE_SUBKEY);
3468 if (retval != 0) {
3469 DBG_WARNING("krb5_auth_con_setflags failed (%s)\n",
3470 error_message(retval));
3471 goto cleanup_creds;
3474 retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
3475 *auth_context, /* Authentication context [in] */
3476 discard_const_p(char, KRB5_TGS_NAME), /* Ticket service name ("krbtgt") [in] */
3477 credsp->client, /* Client principal for the tgt [in] */
3478 credsp->server, /* Server principal for the tgt [in] */
3479 ccache, /* Credential cache to use for storage [in] */
3480 1, /* Turn on for "Forwardable ticket" [in] */
3481 &in_data ); /* Resulting response [out] */
3483 if (retval) {
3484 DBG_INFO("krb5_fwd_tgt_creds failed (%s)\n",
3485 error_message(retval));
3488 * This is not fatal. Delete the *auth_context and continue
3489 * with krb5_mk_req_extended to get a non-forwardable ticket.
3492 if (in_data.data) {
3493 free( in_data.data );
3494 in_data.data = NULL;
3495 in_data.length = 0;
3497 krb5_auth_con_free(context, *auth_context);
3498 *auth_context = NULL;
3499 retval = ads_setup_auth_context(context, auth_context);
3500 if (retval != 0) {
3501 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3502 error_message(retval));
3503 goto cleanup_creds;
3505 } else {
3506 /* We got a delegated ticket. */
3507 gss_flags |= GSS_C_DELEG_FLAG;
3511 /* Frees and reallocates in_data into a GSS checksum blob. */
3512 retval = ads_create_gss_checksum(&in_data, gss_flags);
3513 if (retval != 0) {
3514 goto cleanup_data;
3517 /* We always want GSS-checksum types. */
3518 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
3519 if (retval != 0) {
3520 DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
3521 error_message(retval)));
3522 goto cleanup_data;
3525 #endif
3527 retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
3528 &in_data, credsp, outbuf);
3529 if (retval != 0) {
3530 DBG_WARNING("krb5_mk_req_extended failed (%s)\n",
3531 error_message(retval));
3534 #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)
3535 cleanup_data:
3536 #endif
3538 if (in_data.data) {
3539 free( in_data.data );
3540 in_data.length = 0;
3543 krb5_free_creds(context, credsp);
3545 cleanup_creds:
3546 krb5_free_cred_contents(context, &creds);
3548 cleanup_princ:
3549 krb5_free_principal(context, server);
3550 if (impersonate_princ) {
3551 krb5_free_principal(context, impersonate_princ);
3554 return retval;
3558 get a kerberos5 ticket for the given service
3560 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3561 const char *principal,
3562 time_t time_offset,
3563 DATA_BLOB *ticket,
3564 DATA_BLOB *session_key_krb5,
3565 uint32_t extra_ap_opts, const char *ccname,
3566 time_t *tgs_expire,
3567 const char *impersonate_princ_s)
3569 krb5_error_code retval;
3570 krb5_data packet;
3571 krb5_context context = NULL;
3572 krb5_ccache ccdef = NULL;
3573 krb5_auth_context auth_context = NULL;
3574 krb5_enctype enc_types[] = {
3575 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
3576 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
3577 #endif
3578 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
3579 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
3580 #endif
3581 ENCTYPE_ARCFOUR_HMAC,
3582 ENCTYPE_DES_CBC_MD5,
3583 ENCTYPE_DES_CBC_CRC,
3584 ENCTYPE_NULL};
3585 bool ok;
3587 retval = smb_krb5_init_context_common(&context);
3588 if (retval != 0) {
3589 DBG_ERR("kerberos init context failed (%s)\n",
3590 error_message(retval));
3591 goto failed;
3594 if (time_offset != 0) {
3595 krb5_set_real_time(context, time(NULL) + time_offset, 0);
3598 retval = krb5_cc_resolve(context,
3599 ccname ? ccname : krb5_cc_default_name(context),
3600 &ccdef);
3601 if (retval != 0) {
3602 DBG_WARNING("krb5_cc_default failed (%s)\n",
3603 error_message(retval));
3604 goto failed;
3607 retval = krb5_set_default_tgs_ktypes(context, enc_types);
3608 if (retval != 0) {
3609 DBG_WARNING("krb5_set_default_tgs_ktypes failed (%s)\n",
3610 error_message(retval));
3611 goto failed;
3614 retval = ads_krb5_mk_req(context,
3615 &auth_context,
3616 AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
3617 principal,
3618 ccdef,
3619 &packet,
3620 tgs_expire,
3621 impersonate_princ_s);
3622 if (retval != 0) {
3623 goto failed;
3626 ok = smb_krb5_get_smb_session_key(mem_ctx,
3627 context,
3628 auth_context,
3629 session_key_krb5,
3630 false);
3631 if (!ok) {
3632 retval = ENOMEM;
3633 goto failed;
3636 *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
3638 smb_krb5_free_data_contents(context, &packet);
3640 failed:
3642 if (context) {
3643 if (ccdef) {
3644 krb5_cc_close(context, ccdef);
3646 if (auth_context) {
3647 krb5_auth_con_free(context, auth_context);
3649 krb5_free_context(context);
3652 return retval;
3655 #ifndef SAMBA4_USES_HEIMDAL /* MITKRB5 tracing callback */
3656 static void smb_krb5_trace_cb(krb5_context ctx,
3657 #ifdef HAVE_KRB5_TRACE_INFO
3658 const krb5_trace_info *info,
3659 #elif defined(HAVE_KRB5_TRACE_INFO_STRUCT)
3660 const struct krb5_trace_info *info,
3661 #else
3662 #error unknown krb5_trace_info
3663 #endif
3664 void *data)
3666 if (info != NULL) {
3667 DBGC_DEBUG(DBGC_KERBEROS, "%s", info->message);
3670 #endif
3672 krb5_error_code smb_krb5_init_context_common(krb5_context *_krb5_context)
3674 krb5_error_code ret;
3675 krb5_context krb5_ctx;
3677 initialize_krb5_error_table();
3679 ret = krb5_init_context(&krb5_ctx);
3680 if (ret) {
3681 DBG_ERR("Krb5 context initialization failed (%s)\n",
3682 error_message(ret));
3683 return ret;
3686 /* The MIT Kerberos build relies on using the system krb5.conf file.
3687 * If you really want to use another file please set KRB5_CONFIG
3688 * accordingly. */
3689 #ifndef SAMBA4_USES_HEIMDAL
3690 ret = krb5_set_trace_callback(krb5_ctx, smb_krb5_trace_cb, NULL);
3691 if (ret) {
3692 DBG_ERR("Failed to set MIT kerberos trace callback! (%s)\n",
3693 error_message(ret));
3695 #endif
3697 #ifdef SAMBA4_USES_HEIMDAL
3698 /* Set options in kerberos */
3699 krb5_set_dns_canonicalize_hostname(krb5_ctx, false);
3700 #endif
3702 *_krb5_context = krb5_ctx;
3703 return 0;
3706 #else /* HAVE_KRB5 */
3707 /* This saves a few linking headaches */
3708 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3709 const char *principal,
3710 time_t time_offset,
3711 DATA_BLOB *ticket,
3712 DATA_BLOB *session_key_krb5,
3713 uint32_t extra_ap_opts, const char *ccname,
3714 time_t *tgs_expire,
3715 const char *impersonate_princ_s)
3717 DEBUG(0,("NO KERBEROS SUPPORT\n"));
3718 return 1;
3721 #endif /* HAVE_KRB5 */