dsdb:repl_meta_data: allow CONTROL_DBCHECK_FIX_LINK_DN_NAME to by pass rename
[Samba.git] / lib / krb5_wrap / krb5_samba.c
bloba6ff97640cae80274429c81e6a77b09fb3b1709d
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/crypto.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(const char *realm,
460 const char *sAMAccountName,
461 const char *userPrincipalName,
462 uint32_t uac_flags,
463 TALLOC_CTX *mem_ctx,
464 char **_salt_principal)
466 TALLOC_CTX *frame = talloc_stackframe();
467 char *upper_realm = NULL;
468 const char *principal = NULL;
469 int principal_len = 0;
471 *_salt_principal = NULL;
473 if (sAMAccountName == NULL) {
474 TALLOC_FREE(frame);
475 return EINVAL;
478 if (realm == NULL) {
479 TALLOC_FREE(frame);
480 return EINVAL;
483 if (uac_flags & ~UF_ACCOUNT_TYPE_MASK) {
485 * catch callers which still
486 * pass 'true'.
488 TALLOC_FREE(frame);
489 return EINVAL;
491 if (uac_flags == 0) {
493 * catch callers which still
494 * pass 'false'.
496 TALLOC_FREE(frame);
497 return EINVAL;
500 upper_realm = strupper_talloc(frame, realm);
501 if (upper_realm == NULL) {
502 TALLOC_FREE(frame);
503 return ENOMEM;
506 /* Many, many thanks to lukeh@padl.com for this
507 * algorithm, described in his Nov 10 2004 mail to
508 * samba-technical@lists.samba.org */
511 * Determine a salting principal
513 if (uac_flags & UF_TRUST_ACCOUNT_MASK) {
514 int computer_len = 0;
515 char *tmp = NULL;
517 computer_len = strlen(sAMAccountName);
518 if (sAMAccountName[computer_len-1] == '$') {
519 computer_len -= 1;
522 if (uac_flags & UF_INTERDOMAIN_TRUST_ACCOUNT) {
523 principal = talloc_asprintf(frame, "krbtgt/%*.*s",
524 computer_len, computer_len,
525 sAMAccountName);
526 if (principal == NULL) {
527 TALLOC_FREE(frame);
528 return ENOMEM;
530 } else {
532 tmp = talloc_asprintf(frame, "host/%*.*s.%s",
533 computer_len, computer_len,
534 sAMAccountName, realm);
535 if (tmp == NULL) {
536 TALLOC_FREE(frame);
537 return ENOMEM;
540 principal = strlower_talloc(frame, tmp);
541 TALLOC_FREE(tmp);
542 if (principal == NULL) {
543 TALLOC_FREE(frame);
544 return ENOMEM;
548 principal_len = strlen(principal);
550 } else if (userPrincipalName != NULL) {
551 char *p;
553 principal = userPrincipalName;
554 p = strchr(principal, '@');
555 if (p != NULL) {
556 principal_len = PTR_DIFF(p, principal);
557 } else {
558 principal_len = strlen(principal);
560 } else {
561 principal = sAMAccountName;
562 principal_len = strlen(principal);
565 *_salt_principal = talloc_asprintf(mem_ctx, "%*.*s@%s",
566 principal_len, principal_len,
567 principal, upper_realm);
568 if (*_salt_principal == NULL) {
569 TALLOC_FREE(frame);
570 return ENOMEM;
573 TALLOC_FREE(frame);
574 return 0;
578 * @brief Converts the salt principal string into the salt data blob
580 * This function takes a salt_principal as string in forms like this:
581 * - host/somehost.example.com@EXAMPLE.COM
582 * - SomeAccount@EXAMPLE.COM
583 * - SomePrincipal@EXAMPLE.COM
585 * It generates values like:
586 * - EXAMPLE.COMhost/somehost.example.com
587 * - EXAMPLE.COMSomeAccount
588 * - EXAMPLE.COMSomePrincipal
590 * @param[in] realm The realm the user/computer is added too.
592 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
594 * @param[in] userPrincipalName The userPrincipalName attribute of the object
595 * or NULL is not available.
597 * @param[in] is_computer The indication of the object includes
598 * objectClass=computer.
600 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
602 * @param[out] _salt_principal The resulting principal as string.
604 * @retval 0 Success; otherwise - Kerberos error codes
606 * @see smb_krb5_salt_principal
608 int smb_krb5_salt_principal2data(krb5_context context,
609 const char *salt_principal,
610 TALLOC_CTX *mem_ctx,
611 char **_salt_data)
613 krb5_error_code ret;
614 krb5_principal salt_princ = NULL;
615 krb5_data salt;
617 *_salt_data = NULL;
619 ret = krb5_parse_name(context, salt_principal, &salt_princ);
620 if (ret != 0) {
621 return ret;
624 ret = smb_krb5_get_pw_salt(context, salt_princ, &salt);
625 krb5_free_principal(context, salt_princ);
626 if (ret != 0) {
627 return ret;
630 *_salt_data = talloc_strndup(mem_ctx,
631 (char *)salt.data,
632 salt.length);
633 smb_krb5_free_data_contents(context, &salt);
634 if (*_salt_data == NULL) {
635 return ENOMEM;
638 return 0;
641 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
643 * @brief Get a list of encryption types allowed for session keys
645 * @param[in] context The library context
647 * @param[in] enctypes An allocated, zero-terminated list of encryption types
649 * This function returns an allocated list of encryption types allowed for
650 * session keys.
652 * Use free() to free the enctypes when it is no longer needed.
654 * @retval 0 Success; otherwise - Kerberos error codes
656 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
657 krb5_enctype **enctypes)
659 return krb5_get_permitted_enctypes(context, enctypes);
661 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
662 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
663 krb5_enctype **enctypes)
665 #ifdef HAVE_KRB5_PDU_NONE_DECL
666 return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, enctypes);
667 #else
668 return krb5_get_default_in_tkt_etypes(context, enctypes);
669 #endif
671 #else
672 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
673 #endif
677 * @brief Convert a string principal name to a Kerberos principal.
679 * @param[in] context The library context
681 * @param[in] name The principal as a unix charset string.
683 * @param[out] principal The newly allocated principal.
685 * Use krb5_free_principal() to free a principal when it is no longer needed.
687 * @return 0 on success, a Kerberos error code otherwise.
689 krb5_error_code smb_krb5_parse_name(krb5_context context,
690 const char *name,
691 krb5_principal *principal)
693 krb5_error_code ret;
694 char *utf8_name;
695 size_t converted_size;
696 TALLOC_CTX *frame = talloc_stackframe();
698 if (!push_utf8_talloc(frame, &utf8_name, name, &converted_size)) {
699 talloc_free(frame);
700 return ENOMEM;
703 ret = krb5_parse_name(context, utf8_name, principal);
704 TALLOC_FREE(frame);
705 return ret;
709 * @brief Convert a Kerberos principal structure to a string representation.
711 * The resulting string representation will be a unix charset name and is
712 * talloc'ed.
714 * @param[in] mem_ctx The talloc context to allocate memory on.
716 * @param[in] context The library context.
718 * @param[in] principal The principal.
720 * @param[out] unix_name A string representation of the princpial name as with
721 * unix charset.
723 * Use talloc_free() to free the string representation if it is no longer
724 * needed.
726 * @return 0 on success, a Kerberos error code otherwise.
728 krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
729 krb5_context context,
730 krb5_const_principal principal,
731 char **unix_name)
733 krb5_error_code ret;
734 char *utf8_name;
735 size_t converted_size;
737 *unix_name = NULL;
738 ret = krb5_unparse_name(context, principal, &utf8_name);
739 if (ret) {
740 return ret;
743 if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
744 krb5_free_unparsed_name(context, utf8_name);
745 return ENOMEM;
747 krb5_free_unparsed_name(context, utf8_name);
748 return 0;
752 * @brief Free the contents of a krb5_data structure and zero the data field.
754 * @param[in] context The krb5 context
756 * @param[in] pdata The data structure to free contents of
758 * This function frees the contents, not the structure itself.
760 void smb_krb5_free_data_contents(krb5_context context, krb5_data *pdata)
762 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
763 if (pdata->data) {
764 krb5_free_data_contents(context, pdata);
766 #elif defined(HAVE_KRB5_DATA_FREE)
767 krb5_data_free(context, pdata);
768 #else
769 SAFE_FREE(pdata->data);
770 #endif
774 * @brief copy a buffer into a krb5_data struct
776 * @param[in] p The krb5_data
777 * @param[in] data The data to copy
778 * @param[in] length The length of the data to copy
779 * @return krb5_error_code
781 * Caller has to free krb5_data with smb_krb5_free_data_contents().
783 krb5_error_code smb_krb5_copy_data_contents(krb5_data *p,
784 const void *data,
785 size_t len)
787 #if defined(HAVE_KRB5_DATA_COPY)
788 return krb5_data_copy(p, data, len);
789 #else
790 if (len) {
791 p->data = malloc(len);
792 if (p->data == NULL) {
793 return ENOMEM;
795 memmove(p->data, data, len);
796 } else {
797 p->data = NULL;
799 p->length = len;
800 p->magic = KV5M_DATA;
801 return 0;
802 #endif
805 bool smb_krb5_get_smb_session_key(TALLOC_CTX *mem_ctx,
806 krb5_context context,
807 krb5_auth_context auth_context,
808 DATA_BLOB *session_key,
809 bool remote)
811 krb5_keyblock *skey = NULL;
812 krb5_error_code err = 0;
813 bool ret = false;
815 if (remote) {
816 #ifdef HAVE_KRB5_AUTH_CON_GETRECVSUBKEY
817 err = krb5_auth_con_getrecvsubkey(context,
818 auth_context,
819 &skey);
820 #else /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
821 err = krb5_auth_con_getremotesubkey(context,
822 auth_context, &skey);
823 #endif /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
824 } else {
825 #ifdef HAVE_KRB5_AUTH_CON_GETSENDSUBKEY
826 err = krb5_auth_con_getsendsubkey(context,
827 auth_context,
828 &skey);
829 #else /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
830 err = krb5_auth_con_getlocalsubkey(context,
831 auth_context, &skey);
832 #endif /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
835 if (err || skey == NULL) {
836 DEBUG(10, ("KRB5 error getting session key %d\n", err));
837 goto done;
840 DEBUG(10, ("Got KRB5 session key of length %d\n",
841 (int)KRB5_KEY_LENGTH(skey)));
843 *session_key = data_blob_talloc(mem_ctx,
844 KRB5_KEY_DATA(skey),
845 KRB5_KEY_LENGTH(skey));
846 dump_data_pw("KRB5 Session Key:\n",
847 session_key->data,
848 session_key->length);
850 ret = true;
852 done:
853 if (skey) {
854 krb5_free_keyblock(context, skey);
857 return ret;
862 * @brief Get talloced string component of a principal
864 * @param[in] mem_ctx The TALLOC_CTX
865 * @param[in] context The krb5_context
866 * @param[in] principal The principal
867 * @param[in] component The component
868 * @return string component
870 * Caller must talloc_free if the return value is not NULL.
873 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
874 krb5_context context,
875 krb5_const_principal principal,
876 unsigned int component)
878 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
879 return talloc_strdup(mem_ctx, krb5_principal_get_comp_string(context, principal, component));
880 #else
881 krb5_data *data;
883 if (component >= krb5_princ_size(context, principal)) {
884 return NULL;
887 data = krb5_princ_component(context, principal, component);
888 if (data == NULL) {
889 return NULL;
892 return talloc_strndup(mem_ctx, data->data, data->length);
893 #endif
897 * @brief
899 * @param[in] ccache_string A string pointing to the cache to renew the ticket
900 * (e.g. FILE:/tmp/krb5cc_0) or NULL. If the principal
901 * ccache has not been specified, the default ccache
902 * will be used.
904 * @param[in] client_string The client principal string (e.g. user@SAMBA.SITE)
905 * or NULL. If the principal string has not been
906 * specified, the principal from the ccache will be
907 * retrieved.
909 * @param[in] service_string The service ticket string
910 * (e.g. krbtgt/SAMBA.SITE@SAMBA.SITE) or NULL. If
911 * the sevice ticket is specified, it is parsed (
912 * with the realm part ignored) and used as the
913 * server principal of the credential. Otherwise
914 * the ticket-granting service is used.
916 * @param[in] expire_time A pointer to store the credentials end time or
917 * NULL.
919 * @return 0 on Succes, a Kerberos error code otherwise.
921 krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,
922 const char *client_string,
923 const char *service_string,
924 time_t *expire_time)
926 krb5_error_code ret;
927 krb5_context context = NULL;
928 krb5_ccache ccache = NULL;
929 krb5_principal client = NULL;
930 krb5_creds creds, creds_in;
932 ZERO_STRUCT(creds);
933 ZERO_STRUCT(creds_in);
935 initialize_krb5_error_table();
936 ret = krb5_init_context(&context);
937 if (ret) {
938 goto done;
941 if (!ccache_string) {
942 ccache_string = krb5_cc_default_name(context);
945 if (!ccache_string) {
946 ret = EINVAL;
947 goto done;
950 DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
952 /* FIXME: we should not fall back to defaults */
953 ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
954 if (ret) {
955 goto done;
958 if (client_string) {
959 ret = smb_krb5_parse_name(context, client_string, &client);
960 if (ret) {
961 goto done;
963 } else {
964 ret = krb5_cc_get_principal(context, ccache, &client);
965 if (ret) {
966 goto done;
970 ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
971 if (ret) {
972 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
973 goto done;
976 /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
977 ret = krb5_cc_initialize(context, ccache, client);
978 if (ret) {
979 goto done;
982 ret = krb5_cc_store_cred(context, ccache, &creds);
984 if (expire_time) {
985 *expire_time = (time_t) creds.times.endtime;
988 done:
989 krb5_free_cred_contents(context, &creds_in);
990 krb5_free_cred_contents(context, &creds);
992 if (client) {
993 krb5_free_principal(context, client);
995 if (ccache) {
996 krb5_cc_close(context, ccache);
998 if (context) {
999 krb5_free_context(context);
1002 return ret;
1006 * @brief Free the data stored in an smb_krb5_addresses structure.
1008 * @param[in] context The library context
1010 * @param[in] addr The address structure to free.
1012 * @return 0 on success, a Kerberos error code otherwise.
1014 krb5_error_code smb_krb5_free_addresses(krb5_context context,
1015 smb_krb5_addresses *addr)
1017 krb5_error_code ret = 0;
1018 if (addr == NULL) {
1019 return ret;
1021 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1022 krb5_free_addresses(context, addr->addrs);
1023 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1024 ret = krb5_free_addresses(context, addr->addrs);
1025 SAFE_FREE(addr->addrs);
1026 #endif
1027 SAFE_FREE(addr);
1028 addr = NULL;
1029 return ret;
1032 #define MAX_NETBIOSNAME_LEN 16
1035 * @brief Add a netbios name to the array of addresses
1037 * @param[in] kerb_addr A pointer to the smb_krb5_addresses to add the
1038 * netbios name to.
1040 * @param[in] netbios_name The netbios name to add.
1042 * @return 0 on success, a Kerberos error code otherwise.
1044 krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
1045 const char *netbios_name)
1047 krb5_error_code ret = 0;
1048 char buf[MAX_NETBIOSNAME_LEN];
1049 int len;
1050 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1051 krb5_address **addrs = NULL;
1052 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1053 krb5_addresses *addrs = NULL;
1054 #endif
1056 *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1057 if (*kerb_addr == NULL) {
1058 return ENOMEM;
1061 /* temporarily duplicate put_name() code here to avoid dependency
1062 * issues for a 5 lines function */
1063 len = strlen(netbios_name);
1064 memcpy(buf, netbios_name,
1065 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
1066 if (len < MAX_NETBIOSNAME_LEN - 1) {
1067 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
1069 buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
1071 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1073 int num_addr = 2;
1075 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1076 if (addrs == NULL) {
1077 SAFE_FREE(*kerb_addr);
1078 return ENOMEM;
1081 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1083 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1084 if (addrs[0] == NULL) {
1085 SAFE_FREE(addrs);
1086 SAFE_FREE(*kerb_addr);
1087 return ENOMEM;
1090 addrs[0]->magic = KV5M_ADDRESS;
1091 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1092 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1093 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1094 if (addrs[0]->contents == NULL) {
1095 SAFE_FREE(addrs[0]);
1096 SAFE_FREE(addrs);
1097 SAFE_FREE(*kerb_addr);
1098 return ENOMEM;
1101 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1103 addrs[1] = NULL;
1105 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1107 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1108 if (addrs == NULL) {
1109 SAFE_FREE(*kerb_addr);
1110 return ENOMEM;
1113 memset(addrs, 0, sizeof(krb5_addresses));
1115 addrs->len = 1;
1116 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1117 if (addrs->val == NULL) {
1118 SAFE_FREE(addrs);
1119 SAFE_FREE(*kerb_addr);
1120 return ENOMEM;
1123 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1124 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1125 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1126 if (addrs->val[0].address.data == NULL) {
1127 SAFE_FREE(addrs->val);
1128 SAFE_FREE(addrs);
1129 SAFE_FREE(*kerb_addr);
1130 return ENOMEM;
1133 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1135 #else
1136 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1137 #endif
1138 (*kerb_addr)->addrs = addrs;
1140 return ret;
1144 * @brief Get the enctype from a key table entry
1146 * @param[in] kt_entry Key table entry to get the enctype from.
1148 * @return The enctype from the entry.
1150 krb5_enctype smb_krb5_kt_get_enctype_from_entry(krb5_keytab_entry *kt_entry)
1152 return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1156 * @brief Free the contents of a key table entry.
1158 * @param[in] context The library context.
1160 * @param[in] kt_entry The key table entry to free the contents of.
1162 * @return 0 on success, a Kerberos error code otherwise.
1164 * The pointer itself is not freed.
1166 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1167 krb5_keytab_entry *kt_entry)
1169 /* Try krb5_free_keytab_entry_contents first, since
1170 * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1171 * krb5_kt_free_entry but only has a prototype for the first, while the
1172 * second is considered private.
1174 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1175 return krb5_free_keytab_entry_contents(context, kt_entry);
1176 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1177 return krb5_kt_free_entry(context, kt_entry);
1178 #else
1179 #error UNKNOWN_KT_FREE_FUNCTION
1180 #endif
1185 * @brief Convert an encryption type to a string.
1187 * @param[in] context The library context.
1189 * @param[in] enctype The encryption type.
1191 * @param[in] etype_s A pointer to store the allocated encryption type as a
1192 * string.
1194 * @return 0 on success, a Kerberos error code otherwise.
1196 * The caller needs to free the allocated string etype_s.
1198 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1199 krb5_enctype enctype,
1200 char **etype_s)
1202 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1203 return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1204 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1205 char buf[256];
1206 krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1207 if (ret) {
1208 return ret;
1210 *etype_s = SMB_STRDUP(buf);
1211 if (!*etype_s) {
1212 return ENOMEM;
1214 return ret;
1215 #else
1216 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1217 #endif
1220 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1221 #ifndef MAX_KEYTAB_NAME_LEN
1222 #define MAX_KEYTAB_NAME_LEN 1100
1223 #endif
1226 * @brief Open a key table readonly or with readwrite access.
1228 * Allows one to use a different keytab than the default one using a relative
1229 * path to the keytab.
1231 * @param[in] context The library context
1233 * @param[in] keytab_name_req The path to the key table.
1235 * @param[in] write_access Open with readwrite access.
1237 * @param[in] keytab A pointer o the opended key table.
1239 * The keytab pointer should be freed using krb5_kt_close().
1241 * @return 0 on success, a Kerberos error code otherwise.
1243 krb5_error_code smb_krb5_kt_open_relative(krb5_context context,
1244 const char *keytab_name_req,
1245 bool write_access,
1246 krb5_keytab *keytab)
1248 krb5_error_code ret = 0;
1249 TALLOC_CTX *mem_ctx;
1250 char keytab_string[MAX_KEYTAB_NAME_LEN];
1251 char *kt_str = NULL;
1252 bool found_valid_name = false;
1253 const char *pragma = "FILE";
1254 const char *tmp = NULL;
1256 if (!write_access && !keytab_name_req) {
1257 /* caller just wants to read the default keytab readonly, so be it */
1258 return krb5_kt_default(context, keytab);
1261 mem_ctx = talloc_init("smb_krb5_open_keytab");
1262 if (!mem_ctx) {
1263 return ENOMEM;
1266 #ifdef HAVE_WRFILE_KEYTAB
1267 if (write_access) {
1268 pragma = "WRFILE";
1270 #endif
1272 if (keytab_name_req) {
1274 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1275 ret = KRB5_CONFIG_NOTENUFSPACE;
1276 goto out;
1279 if ((strncmp(keytab_name_req, "WRFILE:", 7) == 0) ||
1280 (strncmp(keytab_name_req, "FILE:", 5) == 0)) {
1281 tmp = keytab_name_req;
1282 goto resolve;
1285 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1286 if (!tmp) {
1287 ret = ENOMEM;
1288 goto out;
1291 goto resolve;
1294 /* we need to handle more complex keytab_strings, like:
1295 * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1297 ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1298 if (ret) {
1299 goto out;
1302 DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1304 tmp = talloc_strdup(mem_ctx, keytab_string);
1305 if (!tmp) {
1306 ret = ENOMEM;
1307 goto out;
1310 if (strncmp(tmp, "ANY:", 4) == 0) {
1311 tmp += 4;
1314 memset(&keytab_string, '\0', sizeof(keytab_string));
1316 while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1317 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1318 found_valid_name = true;
1319 tmp = kt_str;
1320 tmp += 7;
1323 if (strncmp(kt_str, "FILE:", 5) == 0) {
1324 found_valid_name = true;
1325 tmp = kt_str;
1326 tmp += 5;
1329 if (tmp[0] == '/') {
1330 /* Treat as a FILE: keytab definition. */
1331 found_valid_name = true;
1334 if (found_valid_name) {
1335 if (tmp[0] != '/') {
1336 ret = KRB5_KT_BADNAME;
1337 goto out;
1340 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1341 if (!tmp) {
1342 ret = ENOMEM;
1343 goto out;
1345 break;
1349 if (!found_valid_name) {
1350 ret = KRB5_KT_UNKNOWN_TYPE;
1351 goto out;
1354 resolve:
1355 DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1356 ret = krb5_kt_resolve(context, tmp, keytab);
1358 out:
1359 TALLOC_FREE(mem_ctx);
1360 return ret;
1364 * @brief Open a key table readonly or with readwrite access.
1366 * Allows one to use a different keytab than the default one. The path needs to be
1367 * an absolute path or an error will be returned.
1369 * @param[in] context The library context
1371 * @param[in] keytab_name_req The path to the key table.
1373 * @param[in] write_access Open with readwrite access.
1375 * @param[in] keytab A pointer o the opended key table.
1377 * The keytab pointer should be freed using krb5_kt_close().
1379 * @return 0 on success, a Kerberos error code otherwise.
1381 krb5_error_code smb_krb5_kt_open(krb5_context context,
1382 const char *keytab_name_req,
1383 bool write_access,
1384 krb5_keytab *keytab)
1386 int cmp;
1388 if (keytab_name_req == NULL) {
1389 return KRB5_KT_BADNAME;
1392 if (keytab_name_req[0] == '/') {
1393 goto open_keytab;
1396 cmp = strncmp(keytab_name_req, "FILE:/", 6);
1397 if (cmp == 0) {
1398 goto open_keytab;
1401 cmp = strncmp(keytab_name_req, "WRFILE:/", 8);
1402 if (cmp == 0) {
1403 goto open_keytab;
1406 DBG_WARNING("ERROR: Invalid keytab name: %s\n", keytab_name_req);
1408 return KRB5_KT_BADNAME;
1410 open_keytab:
1411 return smb_krb5_kt_open_relative(context,
1412 keytab_name_req,
1413 write_access,
1414 keytab);
1418 * @brief Get a key table name.
1420 * @param[in] mem_ctx The talloc context to use for allocation.
1422 * @param[in] context The library context.
1424 * @param[in] keytab The key table to get the name from.
1426 * @param[in] keytab_name A talloc'ed string of the key table name.
1428 * The talloc'ed name string needs to be freed with talloc_free().
1430 * @return 0 on success, a Kerberos error code otherwise.
1432 krb5_error_code smb_krb5_kt_get_name(TALLOC_CTX *mem_ctx,
1433 krb5_context context,
1434 krb5_keytab keytab,
1435 const char **keytab_name)
1437 char keytab_string[MAX_KEYTAB_NAME_LEN];
1438 krb5_error_code ret = 0;
1440 ret = krb5_kt_get_name(context, keytab,
1441 keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1442 if (ret) {
1443 return ret;
1446 *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1447 if (!*keytab_name) {
1448 return ENOMEM;
1451 return ret;
1455 * @brief Seek and delete old entries in a keytab based on the passed
1456 * principal.
1458 * @param[in] context The KRB5 context to use.
1460 * @param[in] keytab The keytab to operate on.
1462 * @param[in] kvno The kvnco to use.
1464 * @param[in] princ_s The principal as a string to search for.
1466 * @param[in] princ The principal as a krb5_principal to search for.
1468 * @param[in] flush Weather to flush the complete keytab.
1470 * @param[in] keep_old_entries Keep the entry with the previous kvno.
1472 * @retval 0 on Sucess
1474 * @return An appropriate KRB5 error code.
1476 krb5_error_code smb_krb5_kt_seek_and_delete_old_entries(krb5_context context,
1477 krb5_keytab keytab,
1478 krb5_kvno kvno,
1479 krb5_enctype enctype,
1480 const char *princ_s,
1481 krb5_principal princ,
1482 bool flush,
1483 bool keep_old_entries)
1485 krb5_error_code ret;
1486 krb5_kt_cursor cursor;
1487 krb5_keytab_entry kt_entry;
1488 char *ktprinc = NULL;
1489 krb5_kvno old_kvno = kvno - 1;
1490 TALLOC_CTX *tmp_ctx;
1492 ZERO_STRUCT(cursor);
1493 ZERO_STRUCT(kt_entry);
1495 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1496 if (ret == KRB5_KT_END || ret == ENOENT ) {
1497 /* no entries */
1498 return 0;
1501 tmp_ctx = talloc_new(NULL);
1502 if (tmp_ctx == NULL) {
1503 return ENOMEM;
1506 DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1507 while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1508 bool name_ok = false;
1509 krb5_enctype kt_entry_enctype =
1510 smb_krb5_kt_get_enctype_from_entry(&kt_entry);
1512 if (!flush && (princ_s != NULL)) {
1513 ret = smb_krb5_unparse_name(tmp_ctx, context,
1514 kt_entry.principal,
1515 &ktprinc);
1516 if (ret) {
1517 DEBUG(1, (__location__
1518 ": smb_krb5_unparse_name failed "
1519 "(%s)\n", error_message(ret)));
1520 goto out;
1523 #ifdef HAVE_KRB5_KT_COMPARE
1524 name_ok = krb5_kt_compare(context, &kt_entry,
1525 princ, 0, 0);
1526 #else
1527 name_ok = (strcmp(ktprinc, princ_s) == 0);
1528 #endif
1530 if (!name_ok) {
1531 DEBUG(10, (__location__ ": ignoring keytab "
1532 "entry principal %s, kvno = %d\n",
1533 ktprinc, kt_entry.vno));
1535 /* Not a match,
1536 * just free this entry and continue. */
1537 ret = smb_krb5_kt_free_entry(context,
1538 &kt_entry);
1539 ZERO_STRUCT(kt_entry);
1540 if (ret) {
1541 DEBUG(1, (__location__
1542 ": smb_krb5_kt_free_entry "
1543 "failed (%s)\n",
1544 error_message(ret)));
1545 goto out;
1548 TALLOC_FREE(ktprinc);
1549 continue;
1552 TALLOC_FREE(ktprinc);
1555 /*------------------------------------------------------------
1556 * Save the entries with kvno - 1. This is what microsoft does
1557 * to allow people with existing sessions that have kvno - 1
1558 * to still work. Otherwise, when the password for the machine
1559 * changes, all kerberizied sessions will 'break' until either
1560 * the client reboots or the client's session key expires and
1561 * they get a new session ticket with the new kvno.
1562 * Some keytab files only store the kvno in 8bits, limit
1563 * the compare accordingly.
1566 if (!flush && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1567 DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1568 "entry for principal: %s.\n",
1569 old_kvno, princ_s));
1570 continue;
1573 if (keep_old_entries) {
1574 DEBUG(5, (__location__ ": Saving old (kvno %d) "
1575 "entry for principal: %s.\n",
1576 kvno, princ_s));
1577 continue;
1580 if (!flush &&
1581 ((kt_entry.vno & 0xff) == (kvno & 0xff)) &&
1582 (kt_entry_enctype != enctype))
1584 DEBUG(5, (__location__ ": Saving entry with kvno [%d] "
1585 "enctype [%d] for principal: %s.\n",
1586 kvno, kt_entry_enctype, princ_s));
1587 continue;
1590 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1591 "(kvno %d) - trying to remove it.\n",
1592 princ_s, kt_entry.vno));
1594 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1595 ZERO_STRUCT(cursor);
1596 if (ret) {
1597 DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1598 "failed (%s)\n", error_message(ret)));
1599 goto out;
1601 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1602 if (ret) {
1603 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1604 "failed (%s)\n", error_message(ret)));
1605 goto out;
1608 DEBUG(5, (__location__ ": removed old entry for principal: "
1609 "%s (kvno %d).\n", princ_s, kt_entry.vno));
1611 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1612 if (ret) {
1613 DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1614 "(%s)\n", error_message(ret)));
1615 goto out;
1617 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1618 ZERO_STRUCT(kt_entry);
1619 if (ret) {
1620 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1621 "failed (%s)\n", error_message(ret)));
1622 goto out;
1626 out:
1627 talloc_free(tmp_ctx);
1628 if (!all_zero((uint8_t *)&kt_entry, sizeof(kt_entry))) {
1629 smb_krb5_kt_free_entry(context, &kt_entry);
1631 if (!all_zero((uint8_t *)&cursor, sizeof(cursor))) {
1632 krb5_kt_end_seq_get(context, keytab, &cursor);
1634 return ret;
1638 * @brief Add a keytab entry for the given principal
1640 * @param[in] context The krb5 context to use.
1642 * @param[in] keytab The keytab to add the entry to.
1644 * @param[in] kvno The kvno to use.
1646 * @param[in] princ_s The principal as a string.
1648 * @param[in] salt_principal The salt principal to salt the password with.
1649 * Only needed for keys which support salting.
1650 * If no salt is used set no_salt to false and
1651 * pass NULL here.
1653 * @param[in] enctype The encryption type of the keytab entry.
1655 * @param[in] password The password of the keytab entry.
1657 * @param[in] no_salt If the password should not be salted. Normally
1658 * this is only set to false for encryption types
1659 * which do not support salting like RC4.
1661 * @param[in] keep_old_entries Wether to keep or delte old keytab entries.
1663 * @retval 0 on Success
1665 * @return A corresponding KRB5 error code.
1667 * @see smb_krb5_kt_open()
1669 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1670 krb5_keytab keytab,
1671 krb5_kvno kvno,
1672 const char *princ_s,
1673 const char *salt_principal,
1674 krb5_enctype enctype,
1675 krb5_data *password,
1676 bool no_salt,
1677 bool keep_old_entries)
1679 krb5_error_code ret;
1680 krb5_keytab_entry kt_entry;
1681 krb5_principal princ = NULL;
1682 krb5_keyblock *keyp;
1684 ZERO_STRUCT(kt_entry);
1686 ret = smb_krb5_parse_name(context, princ_s, &princ);
1687 if (ret) {
1688 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1689 "failed (%s)\n", princ_s, error_message(ret)));
1690 goto out;
1693 /* Seek and delete old keytab entries */
1694 ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1695 keytab,
1696 kvno,
1697 enctype,
1698 princ_s,
1699 princ,
1700 false,
1701 keep_old_entries);
1702 if (ret) {
1703 goto out;
1706 /* If we get here, we have deleted all the old entries with kvno's
1707 * not equal to the current kvno-1. */
1709 keyp = KRB5_KT_KEY(&kt_entry);
1711 if (no_salt) {
1712 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1713 if (KRB5_KEY_DATA(keyp) == NULL) {
1714 ret = ENOMEM;
1715 goto out;
1717 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1718 KRB5_KEY_LENGTH(keyp) = password->length;
1719 KRB5_KEY_TYPE(keyp) = enctype;
1720 } else {
1721 krb5_principal salt_princ = NULL;
1723 /* Now add keytab entries for all encryption types */
1724 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1725 if (ret) {
1726 DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1727 salt_principal, error_message(ret));
1728 goto out;
1731 ret = smb_krb5_create_key_from_string(context,
1732 salt_princ,
1733 NULL,
1734 password,
1735 enctype,
1736 keyp);
1737 krb5_free_principal(context, salt_princ);
1738 if (ret != 0) {
1739 goto out;
1743 kt_entry.principal = princ;
1744 kt_entry.vno = kvno;
1746 DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1747 "encryption type (%d) and version (%d)\n",
1748 princ_s, enctype, kt_entry.vno));
1749 ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1750 krb5_free_keyblock_contents(context, keyp);
1751 ZERO_STRUCT(kt_entry);
1752 if (ret) {
1753 DEBUG(1, (__location__ ": adding entry to keytab "
1754 "failed (%s)\n", error_message(ret)));
1755 goto out;
1758 out:
1759 if (princ) {
1760 krb5_free_principal(context, princ);
1763 return ret;
1766 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1767 defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1768 defined(HAVE_KRB5_GET_CREDS)
1769 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1770 krb5_ccache ccache,
1771 krb5_principal me,
1772 krb5_principal server,
1773 krb5_principal impersonate_princ,
1774 krb5_creds **out_creds)
1776 krb5_error_code ret;
1777 krb5_get_creds_opt opt;
1779 ret = krb5_get_creds_opt_alloc(context, &opt);
1780 if (ret) {
1781 goto done;
1783 krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1785 if (impersonate_princ) {
1786 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1787 impersonate_princ);
1788 if (ret) {
1789 goto done;
1793 ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1794 if (ret) {
1795 goto done;
1798 done:
1799 if (opt) {
1800 krb5_get_creds_opt_free(context, opt);
1802 return ret;
1804 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1806 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1808 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1809 krb5_error_code KRB5_CALLCONV
1810 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1811 krb5_ccache ccache, krb5_creds *in_creds,
1812 krb5_data *subject_cert,
1813 krb5_creds **out_creds);
1814 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1816 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1817 krb5_ccache ccache,
1818 krb5_principal me,
1819 krb5_principal server,
1820 krb5_principal impersonate_princ,
1821 krb5_creds **out_creds)
1823 krb5_error_code ret;
1824 krb5_creds in_creds;
1826 ZERO_STRUCT(in_creds);
1828 if (impersonate_princ) {
1830 in_creds.server = me;
1831 in_creds.client = impersonate_princ;
1833 ret = krb5_get_credentials_for_user(context,
1834 0, /* krb5_flags options */
1835 ccache,
1836 &in_creds,
1837 NULL, /* krb5_data *subject_cert */
1838 out_creds);
1839 } else {
1840 in_creds.client = me;
1841 in_creds.server = server;
1843 ret = krb5_get_credentials(context, 0, ccache,
1844 &in_creds, out_creds);
1847 return ret;
1849 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1852 * smb_krb5_get_credentials
1854 * @brief Get krb5 credentials for a server
1856 * @param[in] context An initialized krb5_context
1857 * @param[in] ccache An initialized krb5_ccache
1858 * @param[in] me The krb5_principal of the caller
1859 * @param[in] server The krb5_principal of the requested service
1860 * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1861 * @param[out] out_creds The returned krb5_creds structure
1862 * @return krb5_error_code
1865 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1866 krb5_ccache ccache,
1867 krb5_principal me,
1868 krb5_principal server,
1869 krb5_principal impersonate_princ,
1870 krb5_creds **out_creds)
1872 krb5_error_code ret;
1873 krb5_creds *creds = NULL;
1875 if (out_creds != NULL) {
1876 *out_creds = NULL;
1879 if (impersonate_princ) {
1880 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1881 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1882 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1883 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1884 #else
1885 ret = ENOTSUP;
1886 #endif
1887 } else {
1888 krb5_creds in_creds;
1890 ZERO_STRUCT(in_creds);
1892 in_creds.client = me;
1893 in_creds.server = server;
1895 ret = krb5_get_credentials(context, 0, ccache,
1896 &in_creds, &creds);
1898 if (ret) {
1899 goto done;
1902 if (out_creds) {
1903 *out_creds = creds;
1906 done:
1907 if (creds && ret) {
1908 krb5_free_creds(context, creds);
1911 return ret;
1915 * @brief Initialize a krb5_keyblock with the given data.
1917 * Initialized a new keyblock, allocates the contents fo the key and
1918 * copies the data into the keyblock.
1920 * @param[in] context The library context
1922 * @param[in] enctype The encryption type.
1924 * @param[in] data The date to initialize the keyblock with.
1926 * @param[in] length The length of the keyblock.
1928 * @param[in] key Newly allocated keyblock structure.
1930 * The key date must be freed using krb5_free_keyblock_contents() when it is
1931 * no longer needed.
1933 * @return 0 on success, a Kerberos error code otherwise.
1935 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
1936 krb5_enctype enctype,
1937 const void *data,
1938 size_t length,
1939 krb5_keyblock *key)
1941 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
1942 return krb5_keyblock_init(context, enctype, data, length, key);
1943 #else
1944 memset(key, 0, sizeof(krb5_keyblock));
1945 KRB5_KEY_DATA(key) = SMB_MALLOC(length);
1946 if (NULL == KRB5_KEY_DATA(key)) {
1947 return ENOMEM;
1949 memcpy(KRB5_KEY_DATA(key), data, length);
1950 KRB5_KEY_LENGTH(key) = length;
1951 KRB5_KEY_TYPE(key) = enctype;
1952 return 0;
1953 #endif
1957 * @brief Simulate a kinit by putting the tgt in the given credential cache.
1959 * This function uses a keyblock rather than needingthe original password.
1961 * @param[in] ctx The library context
1963 * @param[in] cc The credential cache to put the tgt in.
1965 * @param[in] principal The client princial
1967 * @param[in] keyblock The keyblock to use.
1969 * @param[in] target_service The service name of the initial credentials (or NULL).
1971 * @param[in] krb_options Initial credential options.
1973 * @param[in] expire_time A pointer to store the experation time of the
1974 * credentials (or NULL).
1976 * @param[in] kdc_time A pointer to store the time when the ticket becomes
1977 * valid (or NULL).
1979 * @return 0 on success, a Kerberos error code otherwise.
1981 krb5_error_code smb_krb5_kinit_keyblock_ccache(krb5_context ctx,
1982 krb5_ccache cc,
1983 krb5_principal principal,
1984 krb5_keyblock *keyblock,
1985 const char *target_service,
1986 krb5_get_init_creds_opt *krb_options,
1987 time_t *expire_time,
1988 time_t *kdc_time)
1990 krb5_error_code code = 0;
1991 krb5_creds my_creds;
1993 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
1994 code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
1995 keyblock, 0, target_service,
1996 krb_options);
1997 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
1999 #define SMB_CREDS_KEYTAB "MEMORY:tmp_smb_creds_XXXXXX"
2000 char tmp_name[sizeof(SMB_CREDS_KEYTAB)];
2001 krb5_keytab_entry entry;
2002 krb5_keytab keytab;
2003 mode_t mask;
2005 memset(&entry, 0, sizeof(entry));
2006 entry.principal = principal;
2007 *(KRB5_KT_KEY(&entry)) = *keyblock;
2009 memcpy(tmp_name, SMB_CREDS_KEYTAB, sizeof(SMB_CREDS_KEYTAB));
2010 mask = umask(S_IRWXO | S_IRWXG);
2011 mktemp(tmp_name);
2012 umask(mask);
2013 if (tmp_name[0] == 0) {
2014 return KRB5_KT_BADNAME;
2016 code = krb5_kt_resolve(ctx, tmp_name, &keytab);
2017 if (code) {
2018 return code;
2021 code = krb5_kt_add_entry(ctx, keytab, &entry);
2022 if (code) {
2023 (void)krb5_kt_close(ctx, keytab);
2024 goto done;
2027 code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
2028 keytab, 0, target_service,
2029 krb_options);
2030 (void)krb5_kt_close(ctx, keytab);
2032 #else
2033 #error krb5_get_init_creds_keyblock not available!
2034 #endif
2035 if (code) {
2036 return code;
2039 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2041 * We need to store the principal as returned from the KDC to the
2042 * credentials cache. If we don't do that the KRB5 library is not
2043 * able to find the tickets it is looking for
2045 principal = my_creds.client;
2046 #endif
2047 code = krb5_cc_initialize(ctx, cc, principal);
2048 if (code) {
2049 goto done;
2052 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2053 if (code) {
2054 goto done;
2057 if (expire_time) {
2058 *expire_time = (time_t) my_creds.times.endtime;
2061 if (kdc_time) {
2062 *kdc_time = (time_t) my_creds.times.starttime;
2065 code = 0;
2066 done:
2067 krb5_free_cred_contents(ctx, &my_creds);
2068 return code;
2072 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2074 * @param[in] ctx The library context
2076 * @param[in] cc The credential cache to put the tgt in.
2078 * @param[in] principal The client princial
2080 * @param[in] password The password (or NULL).
2082 * @param[in] target_service The service name of the initial credentials (or NULL).
2084 * @param[in] krb_options Initial credential options.
2086 * @param[in] expire_time A pointer to store the experation time of the
2087 * credentials (or NULL).
2089 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2090 * valid (or NULL).
2092 * @return 0 on success, a Kerberos error code otherwise.
2094 krb5_error_code smb_krb5_kinit_password_ccache(krb5_context ctx,
2095 krb5_ccache cc,
2096 krb5_principal principal,
2097 const char *password,
2098 const char *target_service,
2099 krb5_get_init_creds_opt *krb_options,
2100 time_t *expire_time,
2101 time_t *kdc_time)
2103 krb5_error_code code = 0;
2104 krb5_creds my_creds;
2106 code = krb5_get_init_creds_password(ctx, &my_creds, principal,
2107 password, NULL, NULL, 0,
2108 target_service, krb_options);
2109 if (code) {
2110 return code;
2113 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2115 * We need to store the principal as returned from the KDC to the
2116 * credentials cache. If we don't do that the KRB5 library is not
2117 * able to find the tickets it is looking for
2119 principal = my_creds.client;
2120 #endif
2121 code = krb5_cc_initialize(ctx, cc, principal);
2122 if (code) {
2123 goto done;
2126 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2127 if (code) {
2128 goto done;
2131 if (expire_time) {
2132 *expire_time = (time_t) my_creds.times.endtime;
2135 if (kdc_time) {
2136 *kdc_time = (time_t) my_creds.times.starttime;
2139 code = 0;
2140 done:
2141 krb5_free_cred_contents(ctx, &my_creds);
2142 return code;
2145 #ifdef SAMBA4_USES_HEIMDAL
2147 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2149 * @param[in] ctx The library context
2151 * @param[in] cc The credential cache to store the tgt in.
2153 * @param[in] principal The initial client princial.
2155 * @param[in] password The password (or NULL).
2157 * @param[in] impersonate_principal The impersonatiion principal (or NULL).
2159 * @param[in] self_service The local service for S4U2Self if
2160 * impersonate_principal is specified).
2162 * @param[in] target_service The service name of the initial credentials
2163 * (kpasswd/REALM or a remote service). It defaults
2164 * to the krbtgt if NULL.
2166 * @param[in] krb_options Initial credential options.
2168 * @param[in] expire_time A pointer to store the experation time of the
2169 * credentials (or NULL).
2171 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2172 * valid (or NULL).
2174 * @return 0 on success, a Kerberos error code otherwise.
2176 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
2177 krb5_ccache store_cc,
2178 krb5_principal init_principal,
2179 const char *init_password,
2180 krb5_principal impersonate_principal,
2181 const char *self_service,
2182 const char *target_service,
2183 krb5_get_init_creds_opt *krb_options,
2184 time_t *expire_time,
2185 time_t *kdc_time)
2187 krb5_error_code code = 0;
2188 krb5_get_creds_opt options;
2189 krb5_principal store_principal;
2190 krb5_creds store_creds;
2191 krb5_creds *s4u2self_creds;
2192 Ticket s4u2self_ticket;
2193 size_t s4u2self_ticketlen;
2194 krb5_creds *s4u2proxy_creds;
2195 krb5_principal self_princ;
2196 bool s4u2proxy;
2197 krb5_principal target_princ;
2198 krb5_ccache tmp_cc;
2199 const char *self_realm;
2200 const char *client_realm = NULL;
2201 krb5_principal blacklist_principal = NULL;
2202 krb5_principal whitelist_principal = NULL;
2204 code = krb5_get_init_creds_password(ctx, &store_creds,
2205 init_principal,
2206 init_password,
2207 NULL, NULL,
2209 NULL,
2210 krb_options);
2211 if (code != 0) {
2212 return code;
2215 store_principal = init_principal;
2218 * We are trying S4U2Self now:
2220 * As we do not want to expose our TGT in the
2221 * krb5_ccache, which is also holds the impersonated creds.
2223 * Some low level krb5/gssapi function might use the TGT
2224 * identity and let the client act as our machine account.
2226 * We need to avoid that and use a temporary krb5_ccache
2227 * in order to pass our TGT to the krb5_get_creds() function.
2229 code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
2230 if (code != 0) {
2231 krb5_free_cred_contents(ctx, &store_creds);
2232 return code;
2235 code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
2236 if (code != 0) {
2237 krb5_cc_destroy(ctx, tmp_cc);
2238 krb5_free_cred_contents(ctx, &store_creds);
2239 return code;
2242 code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
2243 if (code != 0) {
2244 krb5_free_cred_contents(ctx, &store_creds);
2245 krb5_cc_destroy(ctx, tmp_cc);
2246 return code;
2250 * we need to remember the client principal of our
2251 * TGT and make sure the KDC does not return this
2252 * in the impersonated tickets. This can happen
2253 * if the KDC does not support S4U2Self and S4U2Proxy.
2255 blacklist_principal = store_creds.client;
2256 store_creds.client = NULL;
2257 krb5_free_cred_contents(ctx, &store_creds);
2260 * Check if we also need S4U2Proxy or if S4U2Self is
2261 * enough in order to get a ticket for the target.
2263 if (target_service == NULL) {
2264 s4u2proxy = false;
2265 } else if (strcmp(target_service, self_service) == 0) {
2266 s4u2proxy = false;
2267 } else {
2268 s4u2proxy = true;
2272 * For S4U2Self we need our own service principal,
2273 * which belongs to our own realm (available on
2274 * our client principal).
2276 self_realm = krb5_principal_get_realm(ctx, init_principal);
2278 code = krb5_parse_name(ctx, self_service, &self_princ);
2279 if (code != 0) {
2280 krb5_free_principal(ctx, blacklist_principal);
2281 krb5_cc_destroy(ctx, tmp_cc);
2282 return code;
2285 code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2286 if (code != 0) {
2287 krb5_free_principal(ctx, blacklist_principal);
2288 krb5_free_principal(ctx, self_princ);
2289 krb5_cc_destroy(ctx, tmp_cc);
2290 return code;
2293 code = krb5_get_creds_opt_alloc(ctx, &options);
2294 if (code != 0) {
2295 krb5_free_principal(ctx, blacklist_principal);
2296 krb5_free_principal(ctx, self_princ);
2297 krb5_cc_destroy(ctx, tmp_cc);
2298 return code;
2301 if (s4u2proxy) {
2303 * If we want S4U2Proxy, we need the forwardable flag
2304 * on the S4U2Self ticket.
2306 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2309 code = krb5_get_creds_opt_set_impersonate(ctx, options,
2310 impersonate_principal);
2311 if (code != 0) {
2312 krb5_get_creds_opt_free(ctx, options);
2313 krb5_free_principal(ctx, blacklist_principal);
2314 krb5_free_principal(ctx, self_princ);
2315 krb5_cc_destroy(ctx, tmp_cc);
2316 return code;
2319 code = krb5_get_creds(ctx, options, tmp_cc,
2320 self_princ, &s4u2self_creds);
2321 krb5_get_creds_opt_free(ctx, options);
2322 krb5_free_principal(ctx, self_princ);
2323 if (code != 0) {
2324 krb5_free_principal(ctx, blacklist_principal);
2325 krb5_cc_destroy(ctx, tmp_cc);
2326 return code;
2329 if (!s4u2proxy) {
2330 krb5_cc_destroy(ctx, tmp_cc);
2333 * Now make sure we store the impersonated principal
2334 * and creds instead of the TGT related stuff
2335 * in the krb5_ccache of the caller.
2337 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2338 &store_creds);
2339 krb5_free_creds(ctx, s4u2self_creds);
2340 if (code != 0) {
2341 return code;
2345 * It's important to store the principal the KDC
2346 * returned, as otherwise the caller would not find
2347 * the S4U2Self ticket in the krb5_ccache lookup.
2349 store_principal = store_creds.client;
2350 goto store;
2354 * We are trying S4U2Proxy:
2356 * We need the ticket from the S4U2Self step
2357 * and our TGT in order to get the delegated ticket.
2359 code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2360 s4u2self_creds->ticket.length,
2361 &s4u2self_ticket,
2362 &s4u2self_ticketlen);
2363 if (code != 0) {
2364 krb5_free_creds(ctx, s4u2self_creds);
2365 krb5_free_principal(ctx, blacklist_principal);
2366 krb5_cc_destroy(ctx, tmp_cc);
2367 return code;
2371 * we need to remember the client principal of the
2372 * S4U2Self stage and as it needs to match the one we
2373 * will get for the S4U2Proxy stage. We need this
2374 * in order to detect KDCs which does not support S4U2Proxy.
2376 whitelist_principal = s4u2self_creds->client;
2377 s4u2self_creds->client = NULL;
2378 krb5_free_creds(ctx, s4u2self_creds);
2381 * For S4U2Proxy we also got a target service principal,
2382 * which also belongs to our own realm (available on
2383 * our client principal).
2385 code = krb5_parse_name(ctx, target_service, &target_princ);
2386 if (code != 0) {
2387 free_Ticket(&s4u2self_ticket);
2388 krb5_free_principal(ctx, whitelist_principal);
2389 krb5_free_principal(ctx, blacklist_principal);
2390 krb5_cc_destroy(ctx, tmp_cc);
2391 return code;
2394 code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2395 if (code != 0) {
2396 free_Ticket(&s4u2self_ticket);
2397 krb5_free_principal(ctx, target_princ);
2398 krb5_free_principal(ctx, whitelist_principal);
2399 krb5_free_principal(ctx, blacklist_principal);
2400 krb5_cc_destroy(ctx, tmp_cc);
2401 return code;
2404 code = krb5_get_creds_opt_alloc(ctx, &options);
2405 if (code != 0) {
2406 free_Ticket(&s4u2self_ticket);
2407 krb5_free_principal(ctx, target_princ);
2408 krb5_free_principal(ctx, whitelist_principal);
2409 krb5_free_principal(ctx, blacklist_principal);
2410 krb5_cc_destroy(ctx, tmp_cc);
2411 return code;
2414 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2415 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2417 code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2418 free_Ticket(&s4u2self_ticket);
2419 if (code != 0) {
2420 krb5_get_creds_opt_free(ctx, options);
2421 krb5_free_principal(ctx, target_princ);
2422 krb5_free_principal(ctx, whitelist_principal);
2423 krb5_free_principal(ctx, blacklist_principal);
2424 krb5_cc_destroy(ctx, tmp_cc);
2425 return code;
2428 code = krb5_get_creds(ctx, options, tmp_cc,
2429 target_princ, &s4u2proxy_creds);
2430 krb5_get_creds_opt_free(ctx, options);
2431 krb5_free_principal(ctx, target_princ);
2432 krb5_cc_destroy(ctx, tmp_cc);
2433 if (code != 0) {
2434 krb5_free_principal(ctx, whitelist_principal);
2435 krb5_free_principal(ctx, blacklist_principal);
2436 return code;
2440 * Now make sure we store the impersonated principal
2441 * and creds instead of the TGT related stuff
2442 * in the krb5_ccache of the caller.
2444 code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2445 &store_creds);
2446 krb5_free_creds(ctx, s4u2proxy_creds);
2447 if (code != 0) {
2448 krb5_free_principal(ctx, whitelist_principal);
2449 krb5_free_principal(ctx, blacklist_principal);
2450 return code;
2454 * It's important to store the principal the KDC
2455 * returned, as otherwise the caller would not find
2456 * the S4U2Self ticket in the krb5_ccache lookup.
2458 store_principal = store_creds.client;
2460 store:
2461 if (blacklist_principal &&
2462 krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2463 char *sp = NULL;
2464 char *ip = NULL;
2466 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2467 if (code != 0) {
2468 sp = NULL;
2470 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2471 if (code != 0) {
2472 ip = NULL;
2474 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2475 "KDC returned self principal[%s] while impersonating [%s]\n",
2476 sp?sp:"<no memory>",
2477 ip?ip:"<no memory>"));
2479 SAFE_FREE(sp);
2480 SAFE_FREE(ip);
2482 krb5_free_principal(ctx, whitelist_principal);
2483 krb5_free_principal(ctx, blacklist_principal);
2484 krb5_free_cred_contents(ctx, &store_creds);
2485 return KRB5_FWD_BAD_PRINCIPAL;
2487 if (blacklist_principal) {
2488 krb5_free_principal(ctx, blacklist_principal);
2491 if (whitelist_principal &&
2492 !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2493 char *sp = NULL;
2494 char *ep = NULL;
2496 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2497 if (code != 0) {
2498 sp = NULL;
2500 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2501 if (code != 0) {
2502 ep = NULL;
2504 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2505 "KDC returned wrong principal[%s] we expected [%s]\n",
2506 sp?sp:"<no memory>",
2507 ep?ep:"<no memory>"));
2509 SAFE_FREE(sp);
2510 SAFE_FREE(ep);
2512 krb5_free_principal(ctx, whitelist_principal);
2513 krb5_free_cred_contents(ctx, &store_creds);
2514 return KRB5_FWD_BAD_PRINCIPAL;
2516 if (whitelist_principal) {
2517 krb5_free_principal(ctx, whitelist_principal);
2520 code = krb5_cc_initialize(ctx, store_cc, store_principal);
2521 if (code != 0) {
2522 krb5_free_cred_contents(ctx, &store_creds);
2523 return code;
2526 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2527 if (code != 0) {
2528 krb5_free_cred_contents(ctx, &store_creds);
2529 return code;
2532 client_realm = krb5_principal_get_realm(ctx, store_creds.client);
2533 if (client_realm != NULL) {
2535 * Because the CANON flag doesn't have any impact
2536 * on the impersonate_principal => store_creds.client
2537 * realm mapping. We need to store the credentials twice,
2538 * once with the returned realm and once with the
2539 * realm of impersonate_principal.
2541 code = krb5_principal_set_realm(ctx, store_creds.server,
2542 client_realm);
2543 if (code != 0) {
2544 krb5_free_cred_contents(ctx, &store_creds);
2545 return code;
2548 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2549 if (code != 0) {
2550 krb5_free_cred_contents(ctx, &store_creds);
2551 return code;
2555 if (expire_time) {
2556 *expire_time = (time_t) store_creds.times.endtime;
2559 if (kdc_time) {
2560 *kdc_time = (time_t) store_creds.times.starttime;
2563 krb5_free_cred_contents(ctx, &store_creds);
2565 return 0;
2567 #endif
2569 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2571 * @brief Create a principal name using a variable argument list.
2573 * @param[in] context The library context.
2575 * @param[inout] principal A pointer to the principal structure.
2577 * @param[in] _realm The realm to use. If NULL then the function will
2578 * get the default realm name.
2580 * @param[in] ... A list of 'char *' components, ending with NULL.
2582 * Use krb5_free_principal() to free the principal when it is no longer needed.
2584 * @return 0 on success, a Kerberos error code otherwise.
2586 krb5_error_code smb_krb5_make_principal(krb5_context context,
2587 krb5_principal *principal,
2588 const char *_realm, ...)
2590 krb5_error_code code;
2591 bool free_realm;
2592 char *realm;
2593 va_list ap;
2595 if (_realm) {
2596 realm = discard_const_p(char, _realm);
2597 free_realm = false;
2598 } else {
2599 code = krb5_get_default_realm(context, &realm);
2600 if (code) {
2601 return code;
2603 free_realm = true;
2606 va_start(ap, _realm);
2607 code = krb5_build_principal_alloc_va(context, principal,
2608 strlen(realm), realm,
2609 ap);
2610 va_end(ap);
2612 if (free_realm) {
2613 krb5_free_default_realm(context, realm);
2616 return code;
2618 #endif
2620 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2622 * @brief Get the lifetime of the initial ticket in the cache.
2624 * @param[in] context The kerberos context.
2626 * @param[in] id The credential cache to get the ticket lifetime.
2628 * @param[out] t A pointer to a time value to store the lifetime.
2630 * @return 0 on success, a krb5_error_code on error.
2632 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2633 krb5_ccache id,
2634 time_t *t)
2636 krb5_cc_cursor cursor;
2637 krb5_error_code kerr;
2638 krb5_creds cred;
2639 krb5_timestamp now;
2641 *t = 0;
2643 kerr = krb5_timeofday(context, &now);
2644 if (kerr) {
2645 return kerr;
2648 kerr = krb5_cc_start_seq_get(context, id, &cursor);
2649 if (kerr) {
2650 return kerr;
2653 while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2654 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2655 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2656 #else
2657 if (cred.flags.b.initial) {
2658 #endif
2659 if (now < cred.times.endtime) {
2660 *t = (time_t) (cred.times.endtime - now);
2662 krb5_free_cred_contents(context, &cred);
2663 break;
2665 krb5_free_cred_contents(context, &cred);
2668 krb5_cc_end_seq_get(context, id, &cursor);
2670 return kerr;
2672 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2674 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2675 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2677 free_Checksum(cksum);
2679 #endif
2682 * @brief Compute a checksum operating on a keyblock.
2684 * This function computes a checksum over a PAC using the keyblock for a keyed
2685 * checksum.
2687 * @param[in] mem_ctx A talloc context to alocate the signature on.
2689 * @param[in] pac_data The PAC as input.
2691 * @param[in] context The library context.
2693 * @param[in] keyblock Encryption key for a keyed checksum.
2695 * @param[out] sig_type The checksum type
2697 * @param[out] sig_blob The talloc'ed checksum
2699 * The caller must free the sig_blob with talloc_free() when it is not needed
2700 * anymore.
2702 * @return 0 on success, a Kerberos error code otherwise.
2704 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2705 DATA_BLOB *pac_data,
2706 krb5_context context,
2707 const krb5_keyblock *keyblock,
2708 uint32_t *sig_type,
2709 DATA_BLOB *sig_blob)
2711 krb5_error_code ret;
2712 krb5_checksum cksum;
2713 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2714 krb5_crypto crypto;
2717 ret = krb5_crypto_init(context,
2718 keyblock,
2720 &crypto);
2721 if (ret) {
2722 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2723 smb_get_krb5_error_message(context, ret, mem_ctx)));
2724 return ret;
2726 ret = krb5_create_checksum(context,
2727 crypto,
2728 KRB5_KU_OTHER_CKSUM,
2730 pac_data->data,
2731 pac_data->length,
2732 &cksum);
2733 if (ret) {
2734 DEBUG(2, ("PAC Verification failed: %s\n",
2735 smb_get_krb5_error_message(context, ret, mem_ctx)));
2738 krb5_crypto_destroy(context, crypto);
2740 if (ret) {
2741 return ret;
2744 *sig_type = cksum.cksumtype;
2745 *sig_blob = data_blob_talloc(mem_ctx,
2746 cksum.checksum.data,
2747 cksum.checksum.length);
2748 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2749 krb5_data input;
2751 input.data = (char *)pac_data->data;
2752 input.length = pac_data->length;
2754 ret = krb5_c_make_checksum(context,
2756 keyblock,
2757 KRB5_KEYUSAGE_APP_DATA_CKSUM,
2758 &input,
2759 &cksum);
2760 if (ret) {
2761 DEBUG(2, ("PAC Verification failed: %s\n",
2762 smb_get_krb5_error_message(context, ret, mem_ctx)));
2763 return ret;
2766 *sig_type = cksum.checksum_type;
2767 *sig_blob = data_blob_talloc(mem_ctx,
2768 cksum.contents,
2769 cksum.length);
2771 #else
2772 #error krb5_create_checksum or krb5_c_make_checksum not available
2773 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2774 smb_krb5_free_checksum_contents(context, &cksum);
2776 return 0;
2781 * @brief Get realm of a principal
2783 * @param[in] context The library context
2785 * @param[in] principal The principal to get the realm from.
2787 * @return An allocated string with the realm or NULL if an error occurred.
2789 * The caller must free the realm string with free() if not needed anymore.
2791 char *smb_krb5_principal_get_realm(krb5_context context,
2792 krb5_const_principal principal)
2794 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2795 return strdup(discard_const_p(char, krb5_principal_get_realm(context, principal)));
2796 #elif defined(krb5_princ_realm) /* MIT */
2797 krb5_data *realm;
2798 realm = discard_const_p(krb5_data,
2799 krb5_princ_realm(context, principal));
2800 return strndup(realm->data, realm->length);
2801 #else
2802 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
2803 #endif
2807 * @brief Get realm of a principal
2809 * @param[in] context The library context
2811 * @param[in] principal The principal to set the realm
2813 * @param[in] realm The realm as a string to set.
2815 * @retur 0 on success, a Kerberos error code otherwise.
2817 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
2818 krb5_principal principal,
2819 const char *realm)
2821 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
2822 return krb5_principal_set_realm(context, principal, realm);
2823 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
2824 krb5_error_code ret;
2825 krb5_data data;
2826 krb5_data *old_data;
2828 old_data = krb5_princ_realm(context, principal);
2830 ret = smb_krb5_copy_data_contents(&data,
2831 realm,
2832 strlen(realm));
2833 if (ret) {
2834 return ret;
2837 /* free realm before setting */
2838 free(old_data->data);
2840 krb5_princ_set_realm(context, principal, &data);
2842 return ret;
2843 #else
2844 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
2845 #endif
2850 * @brief Get the realm from the service hostname.
2852 * This function will look for a domain realm mapping in the [domain_realm]
2853 * section of the krb5.conf first and fallback to extract the realm from
2854 * the provided service hostname. As a last resort it will return the
2855 * provided client_realm.
2857 * @param[in] mem_ctx The talloc context
2859 * @param[in] hostname The service hostname
2861 * @param[in] client_realm If we can not find a mapping, fall back to
2862 * this realm.
2864 * @return The realm to use for the service hostname, NULL if a fatal error
2865 * occured.
2867 char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2868 const char *hostname,
2869 const char *client_realm)
2871 #if defined(HAVE_KRB5_REALM_TYPE)
2872 /* Heimdal. */
2873 krb5_realm *realm_list = NULL;
2874 #else
2875 /* MIT */
2876 char **realm_list = NULL;
2877 #endif
2878 char *realm = NULL;
2879 krb5_error_code kerr;
2880 krb5_context ctx = NULL;
2882 initialize_krb5_error_table();
2883 if (krb5_init_context(&ctx)) {
2884 return NULL;
2887 kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
2888 if (kerr == KRB5_ERR_HOST_REALM_UNKNOWN) {
2889 realm_list = NULL;
2890 kerr = 0;
2892 if (kerr != 0) {
2893 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
2894 "failed %s\n",
2895 hostname ? hostname : "(NULL)",
2896 error_message(kerr) ));
2897 goto out;
2900 if (realm_list != NULL &&
2901 realm_list[0] != NULL &&
2902 realm_list[0][0] != '\0') {
2903 realm = talloc_strdup(mem_ctx, realm_list[0]);
2904 if (realm == NULL) {
2905 goto out;
2907 } else {
2908 const char *p = NULL;
2911 * "dc6.samba2003.example.com"
2912 * returns a realm of "SAMBA2003.EXAMPLE.COM"
2914 * "dc6." returns realm as NULL
2916 p = strchr_m(hostname, '.');
2917 if (p != NULL && p[1] != '\0') {
2918 realm = talloc_strdup_upper(mem_ctx, p + 1);
2919 if (realm == NULL) {
2920 goto out;
2925 if (realm == NULL) {
2926 realm = talloc_strdup(mem_ctx, client_realm);
2929 out:
2931 if (ctx) {
2932 if (realm_list) {
2933 krb5_free_host_realm(ctx, realm_list);
2934 realm_list = NULL;
2936 krb5_free_context(ctx);
2937 ctx = NULL;
2939 return realm;
2943 * @brief Get an error string from a Kerberos error code.
2945 * @param[in] context The library context.
2947 * @param[in] code The Kerberos error code.
2949 * @param[in] mem_ctx The talloc context to allocate the error string on.
2951 * @return A talloc'ed error string or NULL if an error occurred.
2953 * The caller must free the returned error string with talloc_free() if not
2954 * needed anymore
2956 char *smb_get_krb5_error_message(krb5_context context,
2957 krb5_error_code code,
2958 TALLOC_CTX *mem_ctx)
2960 char *ret;
2962 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
2963 const char *context_error = krb5_get_error_message(context, code);
2964 if (context_error) {
2965 ret = talloc_asprintf(mem_ctx, "%s: %s",
2966 error_message(code), context_error);
2967 krb5_free_error_message(context, context_error);
2968 return ret;
2970 #endif
2971 ret = talloc_strdup(mem_ctx, error_message(code));
2972 return ret;
2977 * @brief Return the kerberos library setting for: libdefaults:allow_weak_crypto
2979 * @param[in] context The library context
2981 * @return True if weak crypto is allowed, false if not.
2983 krb5_boolean smb_krb5_get_allowed_weak_crypto(krb5_context context)
2984 #if defined(HAVE_KRB5_CONFIG_GET_BOOL_DEFAULT)
2986 return krb5_config_get_bool_default(context,
2987 NULL,
2988 FALSE,
2989 "libdefaults",
2990 "allow_weak_crypto",
2991 NULL);
2993 #elif defined(HAVE_PROFILE_H) && defined(HAVE_KRB5_GET_PROFILE)
2995 #include <profile.h>
2996 krb5_error_code ret;
2997 krb5_boolean ret_default = false;
2998 profile_t profile;
2999 int ret_profile;
3001 ret = krb5_get_profile(context,
3002 &profile);
3003 if (ret) {
3004 return ret_default;
3007 ret = profile_get_boolean(profile,
3008 "libdefaults",
3009 "allow_weak_crypto",
3010 NULL, /* subsubname */
3011 ret_default, /* def_val */
3012 &ret_profile /* *ret_default */);
3013 if (ret) {
3014 return ret_default;
3017 profile_release(profile);
3019 return ret_profile;
3021 #else
3022 #error UNKNOWN_KRB5_CONFIG_ROUTINES
3023 #endif
3026 * @brief Return the type of a krb5_principal
3028 * @param[in] context The library context.
3030 * @param[in] principal The principal to get the type from.
3032 * @return The integer type of the principal.
3034 int smb_krb5_principal_get_type(krb5_context context,
3035 krb5_const_principal principal)
3037 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
3038 return krb5_principal_get_type(context, principal);
3039 #elif defined(krb5_princ_type) /* MIT */
3040 return krb5_princ_type(context, principal);
3041 #else
3042 #error UNKNOWN_PRINC_GET_TYPE_FUNCTION
3043 #endif
3047 * @brief Set the type of a principal
3049 * @param[in] context The library context
3051 * @param[inout] principal The principal to set the type for.
3053 * @param[in] type The principal type to set.
3055 void smb_krb5_principal_set_type(krb5_context context,
3056 krb5_principal principal,
3057 int type)
3059 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
3060 krb5_principal_set_type(context, principal, type);
3061 #elif defined(krb5_princ_type) /* MIT */
3062 krb5_princ_type(context, principal) = type;
3063 #else
3064 #error UNKNOWN_PRINC_SET_TYPE_FUNCTION
3065 #endif
3068 #if !defined(HAVE_KRB5_WARNX)
3070 * @brief Log a Kerberos message
3072 * It sends the message to com_err.
3074 * @param[in] context The library context
3076 * @param[in] fmt The message format
3078 * @param[in] ... The message arguments
3080 * @return 0 on success.
3082 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
3084 va_list args;
3086 va_start(args, fmt);
3087 com_err_va("samba-kdc", errno, fmt, args);
3088 va_end(args);
3090 return 0;
3092 #endif
3095 * @brief Copy a credential cache.
3097 * @param[in] context The library context.
3099 * @param[in] incc Credential cache to be copied.
3101 * @param[inout] outcc Copy of credential cache to be filled in.
3103 * @return 0 on success, a Kerberos error code otherwise.
3105 krb5_error_code smb_krb5_cc_copy_creds(krb5_context context,
3106 krb5_ccache incc, krb5_ccache outcc)
3108 #ifdef HAVE_KRB5_CC_COPY_CACHE /* Heimdal */
3109 return krb5_cc_copy_cache(context, incc, outcc);
3110 #elif defined(HAVE_KRB5_CC_COPY_CREDS)
3111 krb5_error_code ret;
3112 krb5_principal princ = NULL;
3114 ret = krb5_cc_get_principal(context, incc, &princ);
3115 if (ret != 0) {
3116 return ret;
3118 ret = krb5_cc_initialize(context, outcc, princ);
3119 krb5_free_principal(context, princ);
3120 if (ret != 0) {
3121 return ret;
3123 return krb5_cc_copy_creds(context, incc, outcc);
3124 #else
3125 #error UNKNOWN_KRB5_CC_COPY_CACHE_OR_CREDS_FUNCTION
3126 #endif
3129 /**********************************************************
3130 * ADS KRB5 CALLS
3131 **********************************************************/
3133 static bool ads_cleanup_expired_creds(krb5_context context,
3134 krb5_ccache ccache,
3135 krb5_creds *credsp)
3137 krb5_error_code retval;
3138 const char *cc_type = krb5_cc_get_type(context, ccache);
3140 DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
3141 cc_type, krb5_cc_get_name(context, ccache),
3142 http_timestring(talloc_tos(), credsp->times.endtime)));
3144 /* we will probably need new tickets if the current ones
3145 will expire within 10 seconds.
3147 if (credsp->times.endtime >= (time(NULL) + 10))
3148 return false;
3150 /* heimdal won't remove creds from a file ccache, and
3151 perhaps we shouldn't anyway, since internally we
3152 use memory ccaches, and a FILE one probably means that
3153 we're using creds obtained outside of our exectuable
3155 if (strequal(cc_type, "FILE")) {
3156 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
3157 return false;
3160 retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
3161 if (retval) {
3162 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
3163 error_message(retval)));
3164 /* If we have an error in this, we want to display it,
3165 but continue as though we deleted it */
3167 return true;
3170 /* Allocate and setup the auth context into the state we need. */
3172 static krb5_error_code ads_setup_auth_context(krb5_context context,
3173 krb5_auth_context *auth_context)
3175 krb5_error_code retval;
3177 retval = krb5_auth_con_init(context, auth_context );
3178 if (retval) {
3179 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
3180 error_message(retval)));
3181 return retval;
3184 /* Ensure this is an addressless ticket. */
3185 retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
3186 if (retval) {
3187 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
3188 error_message(retval)));
3191 return retval;
3194 #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)
3195 static krb5_error_code ads_create_gss_checksum(krb5_data *in_data, /* [inout] */
3196 uint32_t gss_flags)
3198 unsigned int orig_length = in_data->length;
3199 unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
3200 char *gss_cksum = NULL;
3202 if (orig_length) {
3203 /* Extra length field for delgated ticket. */
3204 base_cksum_size += 4;
3207 if ((unsigned int)base_cksum_size + orig_length <
3208 (unsigned int)base_cksum_size) {
3209 return EINVAL;
3212 gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
3213 if (gss_cksum == NULL) {
3214 return ENOMEM;
3217 memset(gss_cksum, '\0', base_cksum_size + orig_length);
3218 SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
3221 * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
3222 * This matches the behavior of heimdal and mit.
3224 * And it is needed to work against some closed source
3225 * SMB servers.
3227 * See bug #7883
3229 memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
3231 SIVAL(gss_cksum, 20, gss_flags);
3233 if (orig_length) {
3234 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
3235 SSVAL(gss_cksum, 26, orig_length);
3236 /* Copy the kerberos KRB_CRED data */
3237 memcpy(gss_cksum + 28, in_data->data, orig_length);
3238 free(in_data->data);
3239 in_data->data = NULL;
3240 in_data->length = 0;
3242 in_data->data = gss_cksum;
3243 in_data->length = base_cksum_size + orig_length;
3244 return 0;
3246 #endif
3249 * We can't use krb5_mk_req because w2k wants the service to be in a particular
3250 * format.
3252 static krb5_error_code ads_krb5_mk_req(krb5_context context,
3253 krb5_auth_context *auth_context,
3254 const krb5_flags ap_req_options,
3255 const char *principal,
3256 krb5_ccache ccache,
3257 krb5_data *outbuf,
3258 time_t *expire_time,
3259 const char *impersonate_princ_s)
3261 krb5_error_code retval;
3262 krb5_principal server;
3263 krb5_principal impersonate_princ = NULL;
3264 krb5_creds *credsp;
3265 krb5_creds creds;
3266 krb5_data in_data;
3267 bool creds_ready = false;
3268 int i = 0, maxtries = 3;
3269 bool ok;
3271 ZERO_STRUCT(in_data);
3273 retval = smb_krb5_parse_name(context, principal, &server);
3274 if (retval != 0) {
3275 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
3276 return retval;
3279 if (impersonate_princ_s) {
3280 retval = smb_krb5_parse_name(context, impersonate_princ_s,
3281 &impersonate_princ);
3282 if (retval) {
3283 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
3284 goto cleanup_princ;
3288 /* obtain ticket & session key */
3289 ZERO_STRUCT(creds);
3290 if ((retval = krb5_copy_principal(context, server, &creds.server))) {
3291 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
3292 error_message(retval)));
3293 goto cleanup_princ;
3296 retval = krb5_cc_get_principal(context, ccache, &creds.client);
3297 if (retval != 0) {
3298 /* This can commonly fail on smbd startup with no ticket in the cache.
3299 * Report at higher level than 1. */
3300 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
3301 error_message(retval)));
3302 goto cleanup_creds;
3305 while (!creds_ready && (i < maxtries)) {
3307 retval = smb_krb5_get_credentials(context,
3308 ccache,
3309 creds.client,
3310 creds.server,
3311 impersonate_princ,
3312 &credsp);
3313 if (retval != 0) {
3314 DBG_WARNING("smb_krb5_get_credentials failed for %s "
3315 "(%s)\n",
3316 principal,
3317 error_message(retval));
3318 goto cleanup_creds;
3321 /* cope with ticket being in the future due to clock skew */
3322 if ((unsigned)credsp->times.starttime > time(NULL)) {
3323 time_t t = time(NULL);
3324 int time_offset =(int)((unsigned)credsp->times.starttime-t);
3325 DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
3326 krb5_set_real_time(context, t + time_offset + 1, 0);
3329 ok = ads_cleanup_expired_creds(context, ccache, credsp);
3330 if (!ok) {
3331 creds_ready = true;
3334 i++;
3337 DBG_DEBUG("Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
3338 principal,
3339 krb5_cc_get_type(context, ccache),
3340 krb5_cc_get_name(context, ccache),
3341 http_timestring(talloc_tos(),
3342 (unsigned)credsp->times.endtime),
3343 (unsigned)credsp->times.endtime);
3345 if (expire_time) {
3346 *expire_time = (time_t)credsp->times.endtime;
3349 /* Allocate the auth_context. */
3350 retval = ads_setup_auth_context(context, auth_context);
3351 if (retval != 0) {
3352 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3353 error_message(retval));
3354 goto cleanup_creds;
3357 #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)
3359 uint32_t gss_flags = 0;
3361 if (credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE) {
3363 * Fetch a forwarded TGT from the KDC so that we can
3364 * hand off a 2nd ticket as part of the kerberos
3365 * exchange.
3368 DBG_INFO("Server marked as OK to delegate to, building "
3369 "forwardable TGT\n");
3371 retval = krb5_auth_con_setuseruserkey(context,
3372 *auth_context,
3373 &credsp->keyblock );
3374 if (retval != 0) {
3375 DBG_WARNING("krb5_auth_con_setuseruserkey "
3376 "failed (%s)\n",
3377 error_message(retval));
3378 goto cleanup_creds;
3381 /* Must use a subkey for forwarded tickets. */
3382 retval = krb5_auth_con_setflags(context,
3383 *auth_context,
3384 KRB5_AUTH_CONTEXT_USE_SUBKEY);
3385 if (retval != 0) {
3386 DBG_WARNING("krb5_auth_con_setflags failed (%s)\n",
3387 error_message(retval));
3388 goto cleanup_creds;
3391 retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
3392 *auth_context, /* Authentication context [in] */
3393 discard_const_p(char, KRB5_TGS_NAME), /* Ticket service name ("krbtgt") [in] */
3394 credsp->client, /* Client principal for the tgt [in] */
3395 credsp->server, /* Server principal for the tgt [in] */
3396 ccache, /* Credential cache to use for storage [in] */
3397 1, /* Turn on for "Forwardable ticket" [in] */
3398 &in_data ); /* Resulting response [out] */
3400 if (retval) {
3401 DBG_INFO("krb5_fwd_tgt_creds failed (%s)\n",
3402 error_message(retval));
3405 * This is not fatal. Delete the *auth_context and continue
3406 * with krb5_mk_req_extended to get a non-forwardable ticket.
3409 if (in_data.data) {
3410 free( in_data.data );
3411 in_data.data = NULL;
3412 in_data.length = 0;
3414 krb5_auth_con_free(context, *auth_context);
3415 *auth_context = NULL;
3416 retval = ads_setup_auth_context(context, auth_context);
3417 if (retval != 0) {
3418 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3419 error_message(retval));
3420 goto cleanup_creds;
3422 } else {
3423 /* We got a delegated ticket. */
3424 gss_flags |= GSS_C_DELEG_FLAG;
3428 /* Frees and reallocates in_data into a GSS checksum blob. */
3429 retval = ads_create_gss_checksum(&in_data, gss_flags);
3430 if (retval != 0) {
3431 goto cleanup_data;
3434 /* We always want GSS-checksum types. */
3435 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
3436 if (retval != 0) {
3437 DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
3438 error_message(retval)));
3439 goto cleanup_data;
3442 #endif
3444 retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
3445 &in_data, credsp, outbuf);
3446 if (retval != 0) {
3447 DBG_WARNING("krb5_mk_req_extended failed (%s)\n",
3448 error_message(retval));
3451 #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)
3452 cleanup_data:
3453 #endif
3455 if (in_data.data) {
3456 free( in_data.data );
3457 in_data.length = 0;
3460 krb5_free_creds(context, credsp);
3462 cleanup_creds:
3463 krb5_free_cred_contents(context, &creds);
3465 cleanup_princ:
3466 krb5_free_principal(context, server);
3467 if (impersonate_princ) {
3468 krb5_free_principal(context, impersonate_princ);
3471 return retval;
3475 get a kerberos5 ticket for the given service
3477 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3478 const char *principal,
3479 time_t time_offset,
3480 DATA_BLOB *ticket,
3481 DATA_BLOB *session_key_krb5,
3482 uint32_t extra_ap_opts, const char *ccname,
3483 time_t *tgs_expire,
3484 const char *impersonate_princ_s)
3486 krb5_error_code retval;
3487 krb5_data packet;
3488 krb5_context context = NULL;
3489 krb5_ccache ccdef = NULL;
3490 krb5_auth_context auth_context = NULL;
3491 krb5_enctype enc_types[] = {
3492 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
3493 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
3494 #endif
3495 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
3496 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
3497 #endif
3498 ENCTYPE_ARCFOUR_HMAC,
3499 ENCTYPE_DES_CBC_MD5,
3500 ENCTYPE_DES_CBC_CRC,
3501 ENCTYPE_NULL};
3502 bool ok;
3504 initialize_krb5_error_table();
3505 retval = krb5_init_context(&context);
3506 if (retval != 0) {
3507 DBG_WARNING("krb5_init_context failed (%s)\n",
3508 error_message(retval));
3509 goto failed;
3512 if (time_offset != 0) {
3513 krb5_set_real_time(context, time(NULL) + time_offset, 0);
3516 retval = krb5_cc_resolve(context,
3517 ccname ? ccname : krb5_cc_default_name(context),
3518 &ccdef);
3519 if (retval != 0) {
3520 DBG_WARNING("krb5_cc_default failed (%s)\n",
3521 error_message(retval));
3522 goto failed;
3525 retval = krb5_set_default_tgs_ktypes(context, enc_types);
3526 if (retval != 0) {
3527 DBG_WARNING("krb5_set_default_tgs_ktypes failed (%s)\n",
3528 error_message(retval));
3529 goto failed;
3532 retval = ads_krb5_mk_req(context,
3533 &auth_context,
3534 AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
3535 principal,
3536 ccdef,
3537 &packet,
3538 tgs_expire,
3539 impersonate_princ_s);
3540 if (retval != 0) {
3541 goto failed;
3544 ok = smb_krb5_get_smb_session_key(mem_ctx,
3545 context,
3546 auth_context,
3547 session_key_krb5,
3548 false);
3549 if (!ok) {
3550 retval = ENOMEM;
3551 goto failed;
3554 *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
3556 smb_krb5_free_data_contents(context, &packet);
3558 failed:
3560 if (context) {
3561 if (ccdef) {
3562 krb5_cc_close(context, ccdef);
3564 if (auth_context) {
3565 krb5_auth_con_free(context, auth_context);
3567 krb5_free_context(context);
3570 return retval;
3573 #else /* HAVE_KRB5 */
3574 /* This saves a few linking headaches */
3575 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3576 const char *principal,
3577 time_t time_offset,
3578 DATA_BLOB *ticket,
3579 DATA_BLOB *session_key_krb5,
3580 uint32_t extra_ap_opts, const char *ccname,
3581 time_t *tgs_expire,
3582 const char *impersonate_princ_s)
3584 DEBUG(0,("NO KERBEROS SUPPORT\n"));
3585 return 1;
3588 #endif /* HAVE_KRB5 */