drsuapi.idl: fix source_dsa spelling
[samba4-gss.git] / source4 / kdc / db-glue.c
blob9fad99340589b77d4da9e205fc1da33472db6943
1 /*
2 Unix SMB/CIFS implementation.
4 Database Glue between Samba and the KDC
6 Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2009
7 Copyright (C) Simo Sorce <idra@samba.org> 2010
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.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "includes.h"
25 #include "libcli/security/security.h"
26 #include "librpc/gen_ndr/ndr_security.h"
27 #include "auth/auth.h"
28 #include "auth/auth_sam.h"
29 #include "dsdb/gmsa/util.h"
30 #include "dsdb/samdb/samdb.h"
31 #include "dsdb/common/proto.h"
32 #include "dsdb/common/util.h"
33 #include "librpc/gen_ndr/ndr_drsblobs.h"
34 #include "param/param.h"
35 #include "param/secrets.h"
36 #include "lib/crypto/gkdi.h"
37 #include "../lib/crypto/md4.h"
38 #include "lib/util/memory.h"
39 #include "system/kerberos.h"
40 #include "auth/kerberos/kerberos.h"
41 #include "kdc/authn_policy_util.h"
42 #include "kdc/sdb.h"
43 #include "kdc/samba_kdc.h"
44 #include "kdc/db-glue.h"
45 #include "kdc/pac-glue.h"
46 #include "librpc/gen_ndr/ndr_irpc_c.h"
47 #include "lib/messaging/irpc.h"
49 #undef DBGC_CLASS
50 #define DBGC_CLASS DBGC_KERBEROS
52 #undef strcasecmp
53 #undef strncasecmp
55 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
56 ((uint16_t)(((uint32_t)kvno) >> 16))
58 #define SAMBA_KVNO_GET_VALUE(kvno) \
59 ((uint16_t)(((uint32_t)kvno) & 0xFFFF))
61 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
62 ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
63 ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
65 enum trust_direction {
66 UNKNOWN = 0,
67 INBOUND = LSA_TRUST_DIRECTION_INBOUND,
68 OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
71 static const char *trust_attrs[] = {
72 "securityIdentifier",
73 "flatName",
74 "trustPartner",
75 "trustAttributes",
76 "trustDirection",
77 "trustType",
78 "msDS-TrustForestTrustInfo",
79 "trustAuthIncoming",
80 "trustAuthOutgoing",
81 "whenCreated",
82 "msDS-SupportedEncryptionTypes",
83 NULL
87 send a message to the drepl server telling it to initiate a
88 REPL_SECRET getncchanges extended op to fetch the users secrets
90 static void auth_sam_trigger_repl_secret(TALLOC_CTX *mem_ctx,
91 struct imessaging_context *msg_ctx,
92 struct tevent_context *event_ctx,
93 struct ldb_dn *user_dn)
95 struct dcerpc_binding_handle *irpc_handle;
96 struct drepl_trigger_repl_secret r;
97 struct tevent_req *req;
98 TALLOC_CTX *tmp_ctx;
100 tmp_ctx = talloc_new(mem_ctx);
101 if (tmp_ctx == NULL) {
102 return;
105 irpc_handle = irpc_binding_handle_by_name(tmp_ctx, msg_ctx,
106 "dreplsrv",
107 &ndr_table_irpc);
108 if (irpc_handle == NULL) {
109 DBG_WARNING("Unable to get binding handle for dreplsrv\n");
110 TALLOC_FREE(tmp_ctx);
111 return;
114 r.in.user_dn = ldb_dn_get_linearized(user_dn);
115 if (r.in.user_dn == NULL) {
116 DBG_WARNING("Unable to get user DN\n");
117 TALLOC_FREE(tmp_ctx);
118 return;
122 * This seem to rely on the current IRPC implementation,
123 * which delivers the message in the _send function.
125 * TODO: we need a ONE_WAY IRPC handle and register
126 * a callback and wait for it to be triggered!
128 req = dcerpc_drepl_trigger_repl_secret_r_send(tmp_ctx,
129 event_ctx,
130 irpc_handle,
131 &r);
133 /* we aren't interested in a reply */
134 talloc_free(req);
135 TALLOC_FREE(tmp_ctx);
138 static time_t ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, time_t default_val)
140 const struct ldb_val *gentime = NULL;
141 time_t t;
142 int ret;
144 gentime = ldb_msg_find_ldb_val(msg, attr);
145 ret = ldb_val_to_time(gentime, &t);
146 if (ret) {
147 return default_val;
150 return t;
153 static struct SDBFlags uf2SDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
155 struct SDBFlags flags = {};
157 /* we don't allow kadmin deletes */
158 flags.immutable = 1;
160 /* mark the principal as invalid to start with */
161 flags.invalid = 1;
163 flags.renewable = 1;
165 /* All accounts are servers, but this may be disabled again in the caller */
166 flags.server = 1;
168 /* Account types - clear the invalid bit if it turns out to be valid */
169 if (userAccountControl & UF_NORMAL_ACCOUNT) {
170 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
171 flags.client = 1;
173 flags.invalid = 0;
176 if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
177 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
178 flags.client = 1;
180 flags.invalid = 0;
182 if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
183 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
184 flags.client = 1;
186 flags.invalid = 0;
188 if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
189 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
190 flags.client = 1;
192 flags.invalid = 0;
195 /* Not permitted to act as a client if disabled */
196 if (userAccountControl & UF_ACCOUNTDISABLE) {
197 flags.client = 0;
199 if (userAccountControl & UF_LOCKOUT) {
200 flags.locked_out = 1;
203 if (userAccountControl & UF_PASSWD_NOTREQD) {
204 flags.invalid = 1;
208 UF_PASSWD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevant
210 if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
211 flags.invalid = 1;
214 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
217 if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
218 flags.invalid = 1;
221 if (userAccountControl & UF_SMARTCARD_REQUIRED) {
222 flags.require_hwauth = 1;
224 if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
225 flags.ok_as_delegate = 1;
227 if (userAccountControl & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
229 * this is confusing...
231 * UF_TRUSTED_FOR_DELEGATION
232 * => ok_as_delegate
234 * and
236 * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
237 * => trusted_for_delegation
239 flags.trusted_for_delegation = 1;
241 if (!(userAccountControl & UF_NOT_DELEGATED)) {
242 flags.forwardable = 1;
243 flags.proxiable = 1;
246 if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
247 flags.require_preauth = 0;
248 } else {
249 flags.require_preauth = 1;
252 if (userAccountControl & UF_NO_AUTH_DATA_REQUIRED) {
253 flags.no_auth_data_reqd = 1;
256 return flags;
259 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
261 if (p->db_entry != NULL) {
263 * A sdb_entry still has a reference
265 return -1;
268 if (p->kdc_entry != NULL) {
270 * hdb_entry or krb5_db_entry still
271 * have a reference...
273 return -1;
276 return 0;
280 * Sort keys in descending order of strength.
282 * Explanation from Greg Hudson:
284 * To encrypt tickets only the first returned key is used by the MIT KDC. The
285 * other keys just communicate support for session key enctypes, and aren't
286 * really used. The encryption key for the ticket enc part doesn't have
287 * to be of a type requested by the client. The session key enctype is chosen
288 * based on the client preference order, limited by the set of enctypes present
289 * in the server keys (unless the string attribute is set on the server
290 * principal overriding that set).
293 static int sdb_key_strength_priority(krb5_enctype etype)
295 static const krb5_enctype etype_list[] = {
296 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
297 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
298 ENCTYPE_DES3_CBC_SHA1,
299 ENCTYPE_ARCFOUR_HMAC,
300 ENCTYPE_DES_CBC_MD5,
301 ENCTYPE_DES_CBC_MD4,
302 ENCTYPE_DES_CBC_CRC,
303 ENCTYPE_NULL
305 int i;
307 for (i = 0; i < ARRAY_SIZE(etype_list); i++) {
308 if (etype == etype_list[i]) {
309 break;
313 return ARRAY_SIZE(etype_list) - i;
316 static int sdb_key_strength_cmp(const struct sdb_key *k1, const struct sdb_key *k2)
318 int p1 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k1->key));
319 int p2 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k2->key));
321 if (p1 == p2) {
322 return 0;
325 if (p1 > p2) {
327 * Higher priority comes first
329 return -1;
330 } else {
331 return 1;
335 static void samba_kdc_sort_keys(struct sdb_keys *keys)
337 if (keys == NULL) {
338 return;
341 TYPESAFE_QSORT(keys->val, keys->len, sdb_key_strength_cmp);
344 int samba_kdc_set_fixed_keys(krb5_context context,
345 const struct ldb_val *secretbuffer,
346 uint32_t supported_enctypes,
347 struct sdb_keys *keys)
349 uint16_t allocated_keys = 0;
350 int ret;
352 allocated_keys = 3;
353 keys->len = 0;
354 keys->val = calloc(allocated_keys, sizeof(struct sdb_key));
355 if (keys->val == NULL) {
356 memset(secretbuffer->data, 0, secretbuffer->length);
357 ret = ENOMEM;
358 goto out;
361 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
362 struct sdb_key key = {};
364 ret = smb_krb5_keyblock_init_contents(context,
365 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
366 secretbuffer->data,
367 MIN(secretbuffer->length, 32),
368 &key.key);
369 if (ret) {
370 memset(secretbuffer->data, 0, secretbuffer->length);
371 goto out;
374 keys->val[keys->len] = key;
375 keys->len++;
378 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
379 struct sdb_key key = {};
381 ret = smb_krb5_keyblock_init_contents(context,
382 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
383 secretbuffer->data,
384 MIN(secretbuffer->length, 16),
385 &key.key);
386 if (ret) {
387 memset(secretbuffer->data, 0, secretbuffer->length);
388 goto out;
391 keys->val[keys->len] = key;
392 keys->len++;
395 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
396 struct sdb_key key = {};
398 ret = smb_krb5_keyblock_init_contents(context,
399 ENCTYPE_ARCFOUR_HMAC,
400 secretbuffer->data,
401 MIN(secretbuffer->length, 16),
402 &key.key);
403 if (ret) {
404 memset(secretbuffer->data, 0, secretbuffer->length);
405 goto out;
408 keys->val[keys->len] = key;
409 keys->len++;
411 ret = 0;
412 out:
413 return ret;
417 static int samba_kdc_set_random_keys(krb5_context context,
418 uint32_t supported_enctypes,
419 struct sdb_keys *keys)
421 struct ldb_val secret_val;
422 uint8_t secretbuffer[32];
425 * Fake keys until we have a better way to reject
426 * non-pkinit requests.
428 * We just need to indicate which encryption types are
429 * supported.
431 generate_secret_buffer(secretbuffer, sizeof(secretbuffer));
433 secret_val = data_blob_const(secretbuffer,
434 sizeof(secretbuffer));
435 return samba_kdc_set_fixed_keys(context,
436 &secret_val,
437 supported_enctypes,
438 keys);
441 struct samba_kdc_user_keys {
442 struct sdb_keys *skeys;
443 uint32_t kvno;
444 uint32_t *returned_kvno;
445 uint32_t supported_enctypes;
446 uint32_t *available_enctypes;
447 const struct samr_Password *nthash;
448 const char *salt_string;
449 uint16_t num_pkeys;
450 const struct package_PrimaryKerberosKey4 *pkeys;
453 static krb5_error_code samba_kdc_fill_user_keys(krb5_context context,
454 struct samba_kdc_user_keys *p)
457 * Make sure we'll never reveal DES keys
459 uint32_t supported_enctypes = p->supported_enctypes &= ~(ENC_CRC32 | ENC_RSA_MD5);
460 uint32_t _available_enctypes = 0;
461 uint32_t *available_enctypes = p->available_enctypes;
462 uint32_t _returned_kvno = 0;
463 uint32_t *returned_kvno = p->returned_kvno;
464 uint32_t num_pkeys = p->num_pkeys;
465 uint32_t allocated_keys = num_pkeys;
466 uint32_t i;
467 int ret;
469 if (available_enctypes == NULL) {
470 available_enctypes = &_available_enctypes;
473 *available_enctypes = 0;
475 if (returned_kvno == NULL) {
476 returned_kvno = &_returned_kvno;
479 *returned_kvno = p->kvno;
481 if (p->nthash != NULL) {
482 allocated_keys += 1;
485 allocated_keys = MAX(1, allocated_keys);
487 /* allocate space to decode into */
488 p->skeys->len = 0;
489 p->skeys->val = calloc(allocated_keys, sizeof(struct sdb_key));
490 if (p->skeys->val == NULL) {
491 return ENOMEM;
494 for (i=0; i < num_pkeys; i++) {
495 struct sdb_key key = {};
496 uint32_t enctype_bit;
498 if (p->pkeys[i].value == NULL) {
499 continue;
502 enctype_bit = kerberos_enctype_to_bitmap(p->pkeys[i].keytype);
503 if (!(enctype_bit & supported_enctypes)) {
504 continue;
507 if (p->salt_string != NULL) {
508 DATA_BLOB salt;
510 salt = data_blob_string_const(p->salt_string);
512 key.salt = calloc(1, sizeof(*key.salt));
513 if (key.salt == NULL) {
514 ret = ENOMEM;
515 goto fail;
518 key.salt->type = KRB5_PW_SALT;
520 ret = smb_krb5_copy_data_contents(&key.salt->salt,
521 salt.data,
522 salt.length);
523 if (ret) {
524 *key.salt = (struct sdb_salt) {};
525 sdb_key_free(&key);
526 goto fail;
530 ret = smb_krb5_keyblock_init_contents(context,
531 p->pkeys[i].keytype,
532 p->pkeys[i].value->data,
533 p->pkeys[i].value->length,
534 &key.key);
535 if (ret == 0) {
536 p->skeys->val[p->skeys->len++] = key;
537 *available_enctypes |= enctype_bit;
538 continue;
540 ZERO_STRUCT(key.key);
541 sdb_key_free(&key);
542 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
543 DEBUG(2,("Unsupported keytype ignored - type %u\n",
544 p->pkeys[i].keytype));
545 ret = 0;
546 continue;
549 goto fail;
552 if (p->nthash != NULL && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
553 struct sdb_key key = {};
555 ret = smb_krb5_keyblock_init_contents(context,
556 ENCTYPE_ARCFOUR_HMAC,
557 p->nthash->hash,
558 sizeof(p->nthash->hash),
559 &key.key);
560 if (ret == 0) {
561 p->skeys->val[p->skeys->len++] = key;
563 *available_enctypes |= ENC_RC4_HMAC_MD5;
564 } else if (ret == KRB5_PROG_ETYPE_NOSUPP) {
565 DEBUG(2,("Unsupported keytype ignored - type %u\n",
566 ENCTYPE_ARCFOUR_HMAC));
567 ret = 0;
569 if (ret != 0) {
570 goto fail;
574 samba_kdc_sort_keys(p->skeys);
576 return 0;
577 fail:
578 sdb_keys_free(p->skeys);
579 return ret;
582 static krb5_error_code samba_kdc_merge_keys(struct sdb_keys *keys,
583 struct sdb_keys *old_keys)
585 unsigned num_keys;
586 unsigned num_old_keys;
587 unsigned total_keys;
588 unsigned j;
589 struct sdb_key *skeys = NULL;
591 if (keys == NULL || old_keys == NULL) {
592 return EINVAL;
595 num_keys = keys->len;
596 num_old_keys = old_keys->len;
597 total_keys = num_keys + num_old_keys;
599 skeys = realloc(keys->val, total_keys * sizeof keys->val[0]);
600 if (skeys == NULL) {
601 return ENOMEM;
603 keys->val = skeys;
605 for (j = 0; j < num_old_keys; ++j) {
606 keys->val[num_keys + j] = old_keys->val[j];
608 keys->len = total_keys;
610 old_keys->len = 0;
611 SAFE_FREE(old_keys->val);
613 return 0;
616 krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
617 TALLOC_CTX *mem_ctx,
618 struct ldb_context *ldb,
619 const struct ldb_message *msg,
620 bool is_krbtgt,
621 bool is_rodc,
622 uint32_t userAccountControl,
623 enum samba_kdc_ent_type ent_type,
624 unsigned flags,
625 krb5_kvno requested_kvno,
626 struct sdb_entry *entry,
627 const uint32_t supported_enctypes_in,
628 uint32_t *supported_enctypes_out)
630 krb5_error_code ret = 0;
631 enum ndr_err_code ndr_err;
632 struct samr_Password *hash;
633 unsigned int num_ntPwdHistory = 0;
634 struct samr_Password *ntPwdHistory = NULL;
635 struct samr_Password *old_hash = NULL;
636 struct samr_Password *older_hash = NULL;
637 const struct ldb_val *sc_val;
638 struct supplementalCredentialsBlob scb;
639 struct supplementalCredentialsPackage *scpk = NULL;
640 struct package_PrimaryKerberosBlob _pkb;
641 struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
642 int krbtgt_number = 0;
643 uint32_t current_kvno;
644 uint32_t old_kvno = 0;
645 uint32_t older_kvno = 0;
646 uint32_t returned_kvno = 0;
647 uint16_t i;
648 struct samba_kdc_user_keys keys = { .num_pkeys = 0, };
649 struct samba_kdc_user_keys old_keys = { .num_pkeys = 0, };
650 struct samba_kdc_user_keys older_keys = { .num_pkeys = 0, };
651 uint32_t available_enctypes = 0;
652 uint32_t supported_enctypes = supported_enctypes_in;
653 const bool exporting_keytab = flags & SDB_F_ADMIN_DATA;
655 *supported_enctypes_out = 0;
657 /* Is this the krbtgt or a RODC krbtgt */
658 if (is_rodc) {
659 krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
661 if (krbtgt_number == -1) {
662 return EINVAL;
664 if (krbtgt_number == 0) {
665 return EINVAL;
669 if (flags & SDB_F_USER2USER_PRINCIPAL) {
671 * User2User uses the session key
672 * from the additional ticket,
673 * so we just provide random keys
674 * here in order to make sure
675 * we never expose the user password
676 * keys.
678 ret = samba_kdc_set_random_keys(context,
679 supported_enctypes,
680 &entry->keys);
682 *supported_enctypes_out = supported_enctypes & ENC_ALL_TYPES;
684 goto out;
687 if ((ent_type == SAMBA_KDC_ENT_TYPE_CLIENT)
688 && (userAccountControl & UF_SMARTCARD_REQUIRED)) {
689 ret = samba_kdc_set_random_keys(context,
690 supported_enctypes,
691 &entry->keys);
693 *supported_enctypes_out = supported_enctypes & ENC_ALL_TYPES;
695 goto out;
698 current_kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
699 if (current_kvno > 1) {
700 old_kvno = current_kvno - 1;
702 if (current_kvno > 2) {
703 older_kvno = current_kvno - 2;
705 if (is_krbtgt) {
707 * Even for the main krbtgt account
708 * we have to strictly split the kvno into
709 * two 16-bit parts and the upper 16-bit
710 * need to be all zero, even if
711 * the msDS-KeyVersionNumber has a value
712 * larger than 65535.
714 * See https://bugzilla.samba.org/show_bug.cgi?id=14951
716 current_kvno = SAMBA_KVNO_GET_VALUE(current_kvno);
717 old_kvno = SAMBA_KVNO_GET_VALUE(old_kvno);
718 older_kvno = SAMBA_KVNO_GET_VALUE(older_kvno);
719 requested_kvno = SAMBA_KVNO_GET_VALUE(requested_kvno);
722 /* Get keys from the db */
724 hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
725 num_ntPwdHistory = samdb_result_hashes(mem_ctx, msg,
726 "ntPwdHistory",
727 &ntPwdHistory);
728 if (num_ntPwdHistory > 1) {
729 old_hash = &ntPwdHistory[1];
731 if (num_ntPwdHistory > 2) {
732 older_hash = &ntPwdHistory[2];
734 sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
736 /* supplementalCredentials if present */
737 if (sc_val) {
738 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
739 (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
740 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
741 ret = EINVAL;
742 goto out;
745 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
746 if (scb.sub.num_packages != 0) {
747 NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
748 ret = EINVAL;
749 goto out;
753 for (i=0; i < scb.sub.num_packages; i++) {
754 if (scb.sub.packages[i].name != NULL &&
755 strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0)
757 scpk = &scb.sub.packages[i];
758 if (!scpk->data || !scpk->data[0]) {
759 scpk = NULL;
760 continue;
762 break;
767 * Primary:Kerberos-Newer-Keys element
768 * of supplementalCredentials
770 * The legacy Primary:Kerberos only contains
771 * single DES keys, which are completely ignored
772 * now.
774 if (scpk) {
775 DATA_BLOB blob;
777 blob = strhex_to_data_blob(mem_ctx, scpk->data);
778 if (!blob.data) {
779 ret = ENOMEM;
780 goto out;
783 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
784 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
785 (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
786 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
787 ret = EINVAL;
788 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
789 krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
790 goto out;
793 if (_pkb.version != 4) {
794 ret = EINVAL;
795 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
796 krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
797 goto out;
800 pkb4 = &_pkb.ctr.ctr4;
803 keys = (struct samba_kdc_user_keys) {
804 .kvno = current_kvno,
805 .supported_enctypes = supported_enctypes,
806 .nthash = hash,
807 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
808 .num_pkeys = pkb4 != NULL ? pkb4->num_keys : 0,
809 .pkeys = pkb4 != NULL ? pkb4->keys : NULL,
812 old_keys = (struct samba_kdc_user_keys) {
813 .kvno = old_kvno,
814 .supported_enctypes = supported_enctypes,
815 .nthash = old_hash,
816 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
817 .num_pkeys = pkb4 != NULL ? pkb4->num_old_keys : 0,
818 .pkeys = pkb4 != NULL ? pkb4->old_keys : NULL,
820 older_keys = (struct samba_kdc_user_keys) {
821 .kvno = older_kvno,
822 .supported_enctypes = supported_enctypes,
823 .nthash = older_hash,
824 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
825 .num_pkeys = pkb4 != NULL ? pkb4->num_older_keys : 0,
826 .pkeys = pkb4 != NULL ? pkb4->older_keys : NULL,
829 if (flags & SDB_F_KVNO_SPECIFIED) {
830 if (requested_kvno == keys.kvno) {
832 * The current kvno was requested,
833 * so we return it.
835 keys.skeys = &entry->keys;
836 keys.available_enctypes = &available_enctypes;
837 keys.returned_kvno = &returned_kvno;
838 } else if (requested_kvno == 0) {
840 * don't return any keys
842 } else if (requested_kvno == old_keys.kvno) {
844 * return the old keys as default keys
845 * with the requested kvno.
847 old_keys.skeys = &entry->keys;
848 old_keys.available_enctypes = &available_enctypes;
849 old_keys.returned_kvno = &returned_kvno;
850 } else if (requested_kvno == older_keys.kvno) {
852 * return the older keys as default keys
853 * with the requested kvno.
855 older_keys.skeys = &entry->keys;
856 older_keys.available_enctypes = &available_enctypes;
857 older_keys.returned_kvno = &returned_kvno;
858 } else {
860 * don't return any keys
863 } else {
864 bool include_history = false;
866 if ((flags & SDB_F_GET_CLIENT) && (flags & SDB_F_FOR_AS_REQ)) {
867 include_history = true;
868 } else if (exporting_keytab) {
869 include_history = true;
872 keys.skeys = &entry->keys;
873 keys.available_enctypes = &available_enctypes;
874 keys.returned_kvno = &returned_kvno;
876 if (include_history && old_keys.kvno != 0) {
877 old_keys.skeys = &entry->old_keys;
879 if (include_history && older_keys.kvno != 0) {
880 older_keys.skeys = &entry->older_keys;
884 if (keys.skeys != NULL) {
885 ret = samba_kdc_fill_user_keys(context, &keys);
886 if (ret != 0) {
887 goto out;
891 if (old_keys.skeys != NULL) {
892 ret = samba_kdc_fill_user_keys(context, &old_keys);
893 if (ret != 0) {
894 goto out;
897 if (keys.skeys != NULL && !exporting_keytab) {
898 bool is_gmsa;
900 is_gmsa = dsdb_account_is_gmsa(ldb, msg);
901 if (is_gmsa) {
902 NTTIME current_time;
903 bool gmsa_key_is_recent;
904 bool ok;
906 ok = dsdb_gmsa_current_time(ldb, &current_time);
907 if (!ok) {
908 ret = EINVAL;
909 goto out;
912 gmsa_key_is_recent = samdb_gmsa_key_is_recent(
913 msg, current_time);
914 if (gmsa_key_is_recent) {
916 * As the current gMSA keys are less
917 * than five minutes old, the previous
918 * set of keys remains valid. The
919 * Heimdal KDC will try each of the
920 * current keys when decrypting a
921 * client’s PA‐DATA, so by merging the
922 * old set into the current set we can
923 * cause both sets to be considered for
924 * decryption.
926 ret = samba_kdc_merge_keys(
927 keys.skeys, old_keys.skeys);
928 if (ret) {
929 goto out;
936 if (older_keys.skeys != NULL) {
937 ret = samba_kdc_fill_user_keys(context, &older_keys);
938 if (ret != 0) {
939 goto out;
943 *supported_enctypes_out |= available_enctypes;
945 if (is_krbtgt) {
947 * Even for the main krbtgt account
948 * we have to strictly split the kvno into
949 * two 16-bit parts and the upper 16-bit
950 * need to be all zero, even if
951 * the msDS-KeyVersionNumber has a value
952 * larger than 65535.
954 * See https://bugzilla.samba.org/show_bug.cgi?id=14951
956 returned_kvno = SAMBA_KVNO_AND_KRBTGT(returned_kvno, krbtgt_number);
958 entry->kvno = returned_kvno;
960 out:
961 return ret;
964 static krb5_error_code is_principal_component_equal_impl(krb5_context context,
965 krb5_const_principal principal,
966 unsigned int component,
967 const char *string,
968 bool do_strcasecmp,
969 bool *eq)
971 const char *p;
973 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
974 if (component >= krb5_princ_size(context, principal)) {
975 /* A non‐existent component compares equal to no string. */
976 *eq = false;
977 return 0;
979 p = krb5_principal_get_comp_string(context, principal, component);
980 if (p == NULL) {
981 return ENOENT;
983 if (do_strcasecmp) {
984 *eq = strcasecmp(p, string) == 0;
985 } else {
986 *eq = strcmp(p, string) == 0;
988 return 0;
989 #else
990 size_t len;
991 krb5_data d;
992 krb5_error_code ret = 0;
994 if (component > INT_MAX) {
995 return EINVAL;
998 if (component >= krb5_princ_size(context, principal)) {
999 /* A non‐existent component compares equal to no string. */
1000 *eq = false;
1001 return 0;
1004 ret = smb_krb5_princ_component(context, principal, component, &d);
1005 if (ret) {
1006 return ret;
1009 p = d.data;
1011 len = strlen(string);
1012 if (d.length != len) {
1013 *eq = false;
1014 return 0;
1017 if (do_strcasecmp) {
1018 *eq = strncasecmp(p, string, len) == 0;
1019 } else {
1020 *eq = memcmp(p, string, len) == 0;
1022 return 0;
1023 #endif
1026 static krb5_error_code is_principal_component_equal_ignoring_case(krb5_context context,
1027 krb5_const_principal principal,
1028 unsigned int component,
1029 const char *string,
1030 bool *eq)
1032 return is_principal_component_equal_impl(context,
1033 principal,
1034 component,
1035 string,
1036 true /* do_strcasecmp */,
1037 eq);
1040 static krb5_error_code is_principal_component_equal(krb5_context context,
1041 krb5_const_principal principal,
1042 unsigned int component,
1043 const char *string,
1044 bool *eq)
1046 return is_principal_component_equal_impl(context,
1047 principal,
1048 component,
1049 string,
1050 false /* do_strcasecmp */,
1051 eq);
1054 static krb5_error_code is_kadmin_changepw(krb5_context context,
1055 krb5_const_principal principal,
1056 bool *is_changepw)
1058 krb5_error_code ret = 0;
1059 bool eq = false;
1061 if (krb5_princ_size(context, principal) != 2) {
1062 *is_changepw = false;
1063 return 0;
1066 ret = is_principal_component_equal(context, principal, 0, "kadmin", &eq);
1067 if (ret) {
1068 return ret;
1071 if (!eq) {
1072 *is_changepw = false;
1073 return 0;
1076 ret = is_principal_component_equal(context, principal, 1, "changepw", &eq);
1077 if (ret) {
1078 return ret;
1081 *is_changepw = eq;
1082 return 0;
1085 static krb5_error_code samba_kdc_get_entry_principal(
1086 krb5_context context,
1087 struct samba_kdc_db_context *kdc_db_ctx,
1088 const char *samAccountName,
1089 enum samba_kdc_ent_type ent_type,
1090 unsigned flags,
1091 bool is_kadmin_changepw,
1092 krb5_const_principal in_princ,
1093 krb5_principal *out_princ)
1095 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1096 krb5_error_code code = 0;
1097 bool canon = flags & (SDB_F_CANON|SDB_F_FORCE_CANON);
1100 * If we are set to canonicalize, we get back the fixed UPPER
1101 * case realm, and the real username (ie matching LDAP
1102 * samAccountName)
1104 * Otherwise, if we are set to enterprise, we
1105 * get back the whole principal as-sent
1107 * Finally, if we are not set to canonicalize, we get back the
1108 * fixed UPPER case realm, but the as-sent username
1112 * We need to ensure that the kadmin/changepw principal isn't able to
1113 * issue krbtgt tickets, even if canonicalization is turned on.
1115 if (!is_kadmin_changepw) {
1116 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT && canon) {
1118 * When requested to do so, ensure that both
1119 * the realm values in the principal are set
1120 * to the upper case, canonical realm
1122 code = smb_krb5_make_principal(context,
1123 out_princ,
1124 lpcfg_realm(lp_ctx),
1125 "krbtgt",
1126 lpcfg_realm(lp_ctx),
1127 NULL);
1128 if (code != 0) {
1129 return code;
1131 smb_krb5_principal_set_type(context,
1132 *out_princ,
1133 KRB5_NT_SRV_INST);
1135 return 0;
1138 if ((canon && flags & (SDB_F_FORCE_CANON|SDB_F_FOR_AS_REQ)) ||
1139 (ent_type == SAMBA_KDC_ENT_TYPE_ANY && in_princ == NULL)) {
1141 * SDB_F_CANON maps from the canonicalize flag in the
1142 * packet, and has a different meaning between AS-REQ
1143 * and TGS-REQ. We only change the principal in the
1144 * AS-REQ case.
1146 * The SDB_F_FORCE_CANON if for new MIT KDC code that
1147 * wants the canonical name in all lookups, and takes
1148 * care to canonicalize only when appropriate.
1150 code = smb_krb5_make_principal(context,
1151 out_princ,
1152 lpcfg_realm(lp_ctx),
1153 samAccountName,
1154 NULL);
1155 return code;
1160 * For a krbtgt entry, this appears to be required regardless of the
1161 * canonicalize flag from the client.
1163 code = krb5_copy_principal(context, in_princ, out_princ);
1164 if (code != 0) {
1165 return code;
1169 * While we have copied the client principal, tests show that Win2k3
1170 * returns the 'corrected' realm, not the client-specified realm. This
1171 * code attempts to replace the client principal's realm with the one
1172 * we determine from our records
1174 code = smb_krb5_principal_set_realm(context,
1175 *out_princ,
1176 lpcfg_realm(lp_ctx));
1178 return code;
1182 * Construct an hdb_entry from a directory entry.
1184 static krb5_error_code samba_kdc_message2entry(krb5_context context,
1185 struct samba_kdc_db_context *kdc_db_ctx,
1186 TALLOC_CTX *mem_ctx,
1187 krb5_const_principal principal,
1188 enum samba_kdc_ent_type ent_type,
1189 unsigned flags,
1190 krb5_kvno kvno,
1191 struct ldb_dn *realm_dn,
1192 struct ldb_message *msg,
1193 struct sdb_entry *entry)
1195 TALLOC_CTX *tmp_ctx = NULL;
1196 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1197 uint32_t userAccountControl;
1198 uint32_t msDS_User_Account_Control_Computed;
1199 krb5_error_code ret = 0;
1200 krb5_boolean is_computer = FALSE;
1201 struct samba_kdc_entry *p;
1202 NTTIME acct_expiry;
1203 NTSTATUS status;
1204 bool protected_user = false;
1205 struct dom_sid sid;
1206 uint32_t rid;
1207 bool is_krbtgt = false;
1208 bool is_rodc = false;
1209 bool force_rc4 = lpcfg_kdc_force_enable_rc4_weak_session_keys(lp_ctx);
1210 struct ldb_message_element *objectclasses;
1211 struct ldb_val computer_val = data_blob_string_const("computer");
1212 struct ldb_val gmsa_oc_val = data_blob_string_const("msDS-GroupManagedServiceAccount");
1213 uint32_t config_default_supported_enctypes = lpcfg_kdc_default_domain_supported_enctypes(lp_ctx);
1214 uint32_t default_supported_enctypes =
1215 config_default_supported_enctypes != 0 ?
1216 config_default_supported_enctypes :
1217 ENC_RC4_HMAC_MD5 | ENC_HMAC_SHA1_96_AES256_SK;
1218 uint32_t supported_enctypes
1219 = ldb_msg_find_attr_as_uint(msg,
1220 "msDS-SupportedEncryptionTypes",
1221 default_supported_enctypes);
1222 uint32_t pa_supported_enctypes;
1223 uint32_t supported_session_etypes;
1224 uint32_t available_enctypes = 0;
1226 * also legacy enctypes are announced,
1227 * but effectively restricted by kdc_enctypes
1229 uint32_t domain_enctypes = ENC_RC4_HMAC_MD5 | ENC_RSA_MD5 | ENC_CRC32;
1230 uint32_t config_kdc_enctypes = lpcfg_kdc_supported_enctypes(lp_ctx);
1231 uint32_t kdc_enctypes =
1232 config_kdc_enctypes != 0 ?
1233 config_kdc_enctypes :
1234 ENC_ALL_TYPES;
1235 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
1237 const struct authn_kerberos_client_policy *authn_client_policy = NULL;
1238 const struct authn_server_policy *authn_server_policy = NULL;
1239 const bool user2user = (flags & SDB_F_USER2USER_PRINCIPAL);
1240 int64_t lifetime_secs;
1241 int effective_lifetime_secs;
1243 *entry = (struct sdb_entry) {};
1245 tmp_ctx = talloc_new(mem_ctx);
1246 if (tmp_ctx == NULL) {
1247 return ENOMEM;
1250 if (supported_enctypes == 0) {
1251 supported_enctypes = default_supported_enctypes;
1254 if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1255 domain_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
1258 if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
1259 is_rodc = true;
1262 if (!samAccountName) {
1263 ret = ENOENT;
1264 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
1265 goto out;
1268 objectclasses = ldb_msg_find_element(msg, "objectClass");
1270 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
1271 is_computer = TRUE;
1274 p = talloc_zero(tmp_ctx, struct samba_kdc_entry);
1275 if (!p) {
1276 ret = ENOMEM;
1277 goto out;
1280 if (objectclasses && ldb_msg_find_val(objectclasses, &gmsa_oc_val)) {
1281 p->group_managed_service_account = true;
1284 p->is_rodc = is_rodc;
1285 p->kdc_db_ctx = kdc_db_ctx;
1286 p->realm_dn = talloc_reference(p, realm_dn);
1287 if (!p->realm_dn) {
1288 ret = ENOMEM;
1289 goto out;
1291 p->current_nttime = *kdc_db_ctx->current_nttime_ull;
1293 talloc_set_destructor(p, samba_kdc_entry_destructor);
1295 entry->skdc_entry = p;
1297 userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
1299 msDS_User_Account_Control_Computed
1300 = ldb_msg_find_attr_as_uint(msg,
1301 "msDS-User-Account-Control-Computed",
1302 UF_ACCOUNTDISABLE);
1305 * This brings in the lockout flag, block the account if not
1306 * found. We need the weird UF_ACCOUNTDISABLE check because
1307 * we do not want to fail open if the value is not returned,
1308 * but 0 is a valid value (all OK)
1310 if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
1311 ret = EINVAL;
1312 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
1313 "no msDS-User-Account-Control-Computed present");
1314 goto out;
1315 } else {
1316 userAccountControl |= msDS_User_Account_Control_Computed;
1319 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
1320 p->is_krbtgt = true;
1323 /* First try and figure out the flags based on the userAccountControl */
1324 entry->flags = uf2SDBFlags(context, userAccountControl, ent_type);
1327 * Take control of the returned principal here, rather than
1328 * allowing the Heimdal code to do it as we have specific
1329 * behaviour around the forced realm to honour
1331 entry->flags.force_canonicalize = true;
1334 * Windows 2008 seems to enforce this (very sensible) rule by
1335 * default - don't allow offline attacks on a user's password
1336 * by asking for a ticket to them as a service (encrypted with
1337 * their probably pathetically insecure password)
1339 * But user2user avoids using the keys based on the password,
1340 * so we can allow it.
1343 if (entry->flags.server && !user2user
1344 && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
1345 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
1346 entry->flags.server = 0;
1351 * We restrict a 3-part SPN ending in my domain/realm to full
1352 * domain controllers.
1354 * This avoids any cases where (eg) a demoted DC still has
1355 * these more restricted SPNs.
1357 if (krb5_princ_size(context, principal) > 2) {
1358 char *third_part = NULL;
1359 bool is_our_realm;
1360 bool is_dc;
1362 ret = smb_krb5_principal_get_comp_string(tmp_ctx,
1363 context,
1364 principal,
1366 &third_part);
1367 if (ret) {
1368 krb5_set_error_message(context, ret, "smb_krb5_principal_get_comp_string: out of memory");
1369 goto out;
1372 is_our_realm = lpcfg_is_my_domain_or_realm(lp_ctx,
1373 third_part);
1374 is_dc = userAccountControl &
1375 (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT);
1376 if (is_our_realm && !is_dc) {
1377 entry->flags.server = 0;
1381 * To give the correct type of error to the client, we must
1382 * not just return the entry without .server set, we must
1383 * pretend the principal does not exist. Otherwise we may
1384 * return ERR_POLICY instead of
1385 * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
1387 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry->flags.server == 0) {
1388 ret = SDB_ERR_NOENTRY;
1389 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
1390 goto out;
1392 if (flags & SDB_F_ADMIN_DATA) {
1393 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
1394 * of the Heimdal KDC. They are stored in the traditional
1395 * DB for audit purposes, and still form part of the structure
1396 * we must return */
1398 /* use 'whenCreated' */
1399 entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1400 /* use 'kadmin' for now (needed by mit_samba) */
1402 ret = smb_krb5_make_principal(context,
1403 &entry->created_by.principal,
1404 lpcfg_realm(lp_ctx), "kadmin", NULL);
1405 if (ret) {
1406 krb5_clear_error_message(context);
1407 goto out;
1410 entry->modified_by = calloc(1, sizeof(struct sdb_event));
1411 if (entry->modified_by == NULL) {
1412 ret = ENOMEM;
1413 krb5_set_error_message(context, ret, "calloc: out of memory");
1414 goto out;
1417 /* use 'whenChanged' */
1418 entry->modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
1419 /* use 'kadmin' for now (needed by mit_samba) */
1420 ret = smb_krb5_make_principal(context,
1421 &entry->modified_by->principal,
1422 lpcfg_realm(lp_ctx), "kadmin", NULL);
1423 if (ret) {
1424 krb5_clear_error_message(context);
1425 goto out;
1430 /* The lack of password controls etc applies to krbtgt by
1431 * virtue of being that particular RID */
1432 ret = samdb_result_dom_sid_buf(msg, "objectSid", &sid);
1433 if (ret) {
1434 goto out;
1436 status = dom_sid_split_rid(NULL, &sid, NULL, &rid);
1437 if (!NT_STATUS_IS_OK(status)) {
1438 ret = EINVAL;
1439 goto out;
1442 if (rid == DOMAIN_RID_KRBTGT) {
1443 char *realm = NULL;
1445 entry->valid_end = NULL;
1446 entry->pw_end = NULL;
1448 entry->flags.invalid = 0;
1449 entry->flags.server = 1;
1451 realm = smb_krb5_principal_get_realm(
1452 tmp_ctx, context, principal);
1453 if (realm == NULL) {
1454 ret = ENOMEM;
1455 goto out;
1458 /* Don't mark all requests for the krbtgt/realm as
1459 * 'change password', as otherwise we could get into
1460 * trouble, and not enforce the password expiry.
1461 * Instead, only do it when request is for the kpasswd service */
1462 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1463 bool is_changepw = false;
1465 ret = is_kadmin_changepw(context, principal, &is_changepw);
1466 if (ret) {
1467 goto out;
1470 if (is_changepw && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
1471 entry->flags.change_pw = 1;
1475 TALLOC_FREE(realm);
1477 entry->flags.client = 0;
1478 entry->flags.forwardable = 1;
1479 entry->flags.ok_as_delegate = 1;
1480 } else if (is_rodc) {
1481 /* The RODC krbtgt account is like the main krbtgt,
1482 * but it does not have a changepw or kadmin
1483 * service */
1485 entry->valid_end = NULL;
1486 entry->pw_end = NULL;
1488 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
1489 entry->flags.client = 0;
1490 entry->flags.invalid = 0;
1491 entry->flags.server = 1;
1493 entry->flags.client = 0;
1494 entry->flags.forwardable = 1;
1495 entry->flags.ok_as_delegate = 0;
1496 } else if (entry->flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1497 /* The account/password expiry only applies when the account is used as a
1498 * client (ie password login), not when used as a server */
1500 /* Make very well sure we don't use this for a client,
1501 * it could bypass the password restrictions */
1502 entry->flags.client = 0;
1504 entry->valid_end = NULL;
1505 entry->pw_end = NULL;
1507 } else {
1508 NTTIME must_change_time
1509 = samdb_result_nttime(msg,
1510 "msDS-UserPasswordExpiryTimeComputed",
1512 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
1513 entry->pw_end = NULL;
1514 } else {
1515 entry->pw_end = malloc(sizeof(*entry->pw_end));
1516 if (entry->pw_end == NULL) {
1517 ret = ENOMEM;
1518 goto out;
1520 *entry->pw_end = nt_time_to_unix(must_change_time);
1523 acct_expiry = samdb_result_account_expires(msg);
1524 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
1525 entry->valid_end = NULL;
1526 } else {
1527 entry->valid_end = malloc(sizeof(*entry->valid_end));
1528 if (entry->valid_end == NULL) {
1529 ret = ENOMEM;
1530 goto out;
1532 *entry->valid_end = nt_time_to_unix(acct_expiry);
1536 ret = samba_kdc_get_entry_principal(context,
1537 kdc_db_ctx,
1538 samAccountName,
1539 ent_type,
1540 flags,
1541 entry->flags.change_pw,
1542 principal,
1543 &entry->principal);
1544 if (ret != 0) {
1545 krb5_clear_error_message(context);
1546 goto out;
1549 entry->valid_start = NULL;
1551 entry->max_life = malloc(sizeof(*entry->max_life));
1552 if (entry->max_life == NULL) {
1553 ret = ENOMEM;
1554 goto out;
1557 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1558 *entry->max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
1559 } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
1560 *entry->max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
1561 } else {
1562 *entry->max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
1563 kdc_db_ctx->policy.usr_tkt_lifetime);
1566 if (entry->flags.change_pw) {
1567 /* Limit lifetime of kpasswd tickets to two minutes or less. */
1568 *entry->max_life = MIN(*entry->max_life, CHANGEPW_LIFETIME);
1571 entry->max_renew = malloc(sizeof(*entry->max_renew));
1572 if (entry->max_renew == NULL) {
1573 ret = ENOMEM;
1574 goto out;
1577 *entry->max_renew = kdc_db_ctx->policy.renewal_lifetime;
1580 * A principal acting as a client that is not being looked up as the
1581 * principal of an armor ticket may have an authentication policy apply
1582 * to it.
1584 * We won’t get an authentication policy for the client of an S4U2Self
1585 * or S4U2Proxy request. Those clients are looked up with
1586 * SDB_F_FOR_TGS_REQ instead of with SDB_F_FOR_AS_REQ.
1588 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT &&
1589 (flags & SDB_F_FOR_AS_REQ) &&
1590 !(flags & SDB_F_ARMOR_PRINCIPAL))
1592 ret = authn_policy_kerberos_client(kdc_db_ctx->samdb, tmp_ctx, msg,
1593 &authn_client_policy);
1594 if (ret) {
1595 goto out;
1600 * A principal acting as a server may have an authentication policy
1601 * apply to it.
1603 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1604 ret = authn_policy_server(kdc_db_ctx->samdb, tmp_ctx, msg,
1605 &authn_server_policy);
1606 if (ret) {
1607 goto out;
1611 entry->skdc_entry->enforced_tgt_lifetime_nt_ticks = authn_policy_enforced_tgt_lifetime_raw(authn_client_policy);
1612 lifetime_secs = entry->skdc_entry->enforced_tgt_lifetime_nt_ticks;
1613 effective_lifetime_secs = *entry->max_life;
1615 if (lifetime_secs != 0) {
1616 lifetime_secs /= INT64_C(1000) * 1000 * 10;
1617 lifetime_secs = MIN(lifetime_secs, INT_MAX);
1618 lifetime_secs = MAX(lifetime_secs, INT_MIN);
1620 effective_lifetime_secs = MIN(effective_lifetime_secs,
1621 lifetime_secs);
1624 * Set both lifetime and renewal time based only on the
1625 * configured maximum lifetime — not on the configured renewal
1626 * time. Yes, this is what Windows does.
1628 *entry->max_life = effective_lifetime_secs;
1629 *entry->max_renew = effective_lifetime_secs;
1632 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT && (flags & SDB_F_FOR_AS_REQ)) {
1633 int result;
1634 const struct auth_user_info_dc *user_info_dc = NULL;
1636 * These protections only apply to clients, so servers in the
1637 * Protected Users group may still have service tickets to them
1638 * encrypted with RC4. For accounts looked up as servers, note
1639 * that 'msg' does not contain the 'memberOf' attribute for
1640 * determining whether the account is a member of Protected
1641 * Users.
1643 * Additionally, Microsoft advises that accounts for services
1644 * and computers should never be members of Protected Users, or
1645 * they may fail to authenticate.
1647 ret = samba_kdc_get_user_info_from_db(tmp_ctx,
1648 kdc_db_ctx->samdb,
1650 msg,
1651 &user_info_dc);
1652 if (ret) {
1653 goto out;
1656 result = dsdb_is_protected_user(kdc_db_ctx->samdb,
1657 user_info_dc->sids,
1658 user_info_dc->num_sids);
1659 if (result == -1) {
1660 ret = EINVAL;
1661 goto out;
1664 protected_user = result;
1666 if (protected_user) {
1667 entry->flags.forwardable = 0;
1668 entry->flags.proxiable = 0;
1670 if (lifetime_secs == 0) {
1672 * If a TGT lifetime hasn’t been set, Protected
1673 * Users enforces a four hour TGT lifetime.
1676 effective_lifetime_secs = 4 * 60 * 60;
1678 *entry->max_life = MIN(*entry->max_life, effective_lifetime_secs);
1679 *entry->max_renew = MIN(*entry->max_renew, effective_lifetime_secs);
1684 if (effective_lifetime_secs != lifetime_secs) {
1686 * Since ‘effective_lifetime_secs’ has changed, update
1687 * ‘enforced_tgt_lifetime_nt_ticks’ to match.
1689 entry->skdc_entry->enforced_tgt_lifetime_nt_ticks =
1690 effective_lifetime_secs * (INT64_C(1000) * 1000 * 10);
1693 if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
1694 bool enable_fast;
1696 is_krbtgt = true;
1699 * KDCs (and KDCs on RODCs)
1700 * ignore msDS-SupportedEncryptionTypes completely
1701 * but support all supported enctypes by the domain.
1703 supported_enctypes = domain_enctypes;
1705 enable_fast = lpcfg_kdc_enable_fast(kdc_db_ctx->lp_ctx);
1706 if (enable_fast) {
1707 supported_enctypes |= ENC_FAST_SUPPORTED;
1710 supported_enctypes |= ENC_CLAIMS_SUPPORTED;
1711 supported_enctypes |= ENC_COMPOUND_IDENTITY_SUPPORTED;
1714 * Resource SID compression is enabled implicitly, unless
1715 * disabled in msDS-SupportedEncryptionTypes.
1718 } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
1720 * DCs and RODCs computer accounts take
1721 * msDS-SupportedEncryptionTypes unmodified, but
1722 * force all enctypes supported by the domain.
1724 supported_enctypes |= domain_enctypes;
1726 } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
1727 (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
1729 * for AS-REQ the client chooses the enc types it
1730 * supports, and this will vary between computers a
1731 * user logs in from. Therefore, so that we accept any
1732 * of the client's keys for decrypting padata,
1733 * supported_enctypes should not restrict etype usage.
1735 * likewise for 'any' return as much as is supported,
1736 * to export into a keytab.
1738 supported_enctypes |= ENC_ALL_TYPES;
1741 /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
1742 if (userAccountControl & UF_USE_DES_KEY_ONLY) {
1743 supported_enctypes &= ~ENC_ALL_TYPES;
1744 DBG_NOTICE("DES-only keys allowed on the account '%s', "
1745 "most likely auth will fail through Kerberos\n",
1746 samAccountName);
1749 if (protected_user) {
1750 supported_enctypes &= ~ENC_RC4_HMAC_MD5;
1753 pa_supported_enctypes = supported_enctypes;
1754 supported_session_etypes = supported_enctypes;
1755 if (supported_session_etypes & ENC_HMAC_SHA1_96_AES256_SK) {
1756 supported_session_etypes |= ENC_HMAC_SHA1_96_AES256;
1757 supported_session_etypes |= ENC_HMAC_SHA1_96_AES128;
1759 if (force_rc4) {
1760 supported_session_etypes |= ENC_RC4_HMAC_MD5;
1763 * now that we remembered what to announce in pa_supported_enctypes
1764 * and normalized ENC_HMAC_SHA1_96_AES256_SK, we restrict the
1765 * rest to the enc types the local kdc supports.
1767 supported_enctypes &= kdc_enctypes;
1768 supported_session_etypes &= kdc_enctypes;
1770 /* Get keys from the db */
1771 ret = samba_kdc_message2entry_keys(context, p,
1772 kdc_db_ctx->samdb, msg,
1773 is_krbtgt, is_rodc,
1774 userAccountControl,
1775 ent_type, flags, kvno, entry,
1776 supported_enctypes,
1777 &available_enctypes);
1778 if (ret) {
1779 /* Could be bogus data in the entry, or out of memory */
1780 goto out;
1784 * If we only have a nthash stored,
1785 * but a better session key would be
1786 * available, we fallback to fetching the
1787 * RC4_HMAC_MD5, which implicitly also
1788 * would allow an RC4_HMAC_MD5 session key.
1789 * But only if the kdc actually supports
1790 * RC4_HMAC_MD5.
1792 if (available_enctypes == 0 &&
1793 (supported_enctypes & ENC_RC4_HMAC_MD5) == 0 &&
1794 (supported_enctypes & ~ENC_RC4_HMAC_MD5) != 0 &&
1795 (kdc_enctypes & ENC_RC4_HMAC_MD5) != 0)
1797 supported_enctypes = ENC_RC4_HMAC_MD5;
1798 ret = samba_kdc_message2entry_keys(context, p,
1799 kdc_db_ctx->samdb, msg,
1800 is_krbtgt, is_rodc,
1801 userAccountControl,
1802 ent_type, flags, kvno, entry,
1803 supported_enctypes,
1804 &available_enctypes);
1805 if (ret) {
1806 /* Could be bogus data in the entry, or out of memory */
1807 goto out;
1812 * We need to support all session keys enctypes for
1813 * all keys we provide
1815 supported_session_etypes |= available_enctypes;
1817 ret = sdb_entry_set_etypes(entry);
1818 if (ret) {
1819 goto out;
1822 if (entry->flags.server) {
1823 bool add_aes256 =
1824 supported_session_etypes & KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96;
1825 bool add_aes128 =
1826 supported_session_etypes & KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96;
1827 bool add_rc4 =
1828 supported_session_etypes & ENC_RC4_HMAC_MD5;
1829 ret = sdb_entry_set_session_etypes(entry,
1830 add_aes256,
1831 add_aes128,
1832 add_rc4);
1833 if (ret) {
1834 goto out;
1838 if (entry->keys.len != 0) {
1840 * FIXME: Currently limited to Heimdal so as not to
1841 * break MIT KDCs, for which no fix is available.
1843 #ifdef SAMBA4_USES_HEIMDAL
1844 if (is_krbtgt) {
1846 * The krbtgt account, having no reason to
1847 * issue tickets encrypted in weaker keys,
1848 * shall only make available its strongest
1849 * key. All weaker keys are stripped out. This
1850 * makes it impossible for an RC4-encrypted
1851 * TGT to be accepted when AES KDC keys exist.
1853 * This controls the ticket key and so the PAC
1854 * signature algorithms indirectly, preventing
1855 * a weak KDC checksum from being accepted
1856 * when we verify the signatures for an
1857 * S4U2Proxy evidence ticket. As such, this is
1858 * indispensable for addressing
1859 * CVE-2022-37966.
1861 * Being strict here also provides protection
1862 * against possible future attacks on weak
1863 * keys.
1867 * The krbtgt account is never a Group Managed Service
1868 * Account, but a similar system might well be
1869 * implemented as a means of having the krbtgt’s keys
1870 * roll over automatically. In that case, thought might
1871 * be given as to how this security measure — of
1872 * stripping out weaker keys — would interact with key
1873 * management.
1876 entry->keys.len = 1;
1877 if (entry->etypes != NULL) {
1878 entry->etypes->len = MIN(entry->etypes->len, 1);
1880 entry->old_keys.len = MIN(entry->old_keys.len, 1);
1881 entry->older_keys.len = MIN(entry->older_keys.len, 1);
1883 #endif
1884 } else if (kdc_db_ctx->rodc) {
1886 * We are on an RODC, but don't have keys for this
1887 * account. Signal this to the caller
1889 auth_sam_trigger_repl_secret(kdc_db_ctx,
1890 kdc_db_ctx->msg_ctx,
1891 kdc_db_ctx->ev_ctx,
1892 msg->dn);
1893 ret = SDB_ERR_NOT_FOUND_HERE;
1894 goto out;
1895 } else {
1897 * oh, no password. Apparently (comment in
1898 * hdb-ldap.c) this violates the ASN.1, but this
1899 * allows an entry with no keys (yet).
1903 p->msg = talloc_steal(p, msg);
1904 p->supported_enctypes = pa_supported_enctypes;
1906 p->client_policy = talloc_steal(p, authn_client_policy);
1907 p->server_policy = talloc_steal(p, authn_server_policy);
1909 talloc_steal(kdc_db_ctx, p);
1911 out:
1912 if (ret != 0) {
1913 /* This doesn't free ent itself, that is for the eventual caller to do */
1914 sdb_entry_free(entry);
1917 talloc_free(tmp_ctx);
1918 return ret;
1921 struct samba_kdc_trust_keys {
1922 struct sdb_keys *skeys;
1923 uint32_t kvno;
1924 uint32_t *returned_kvno;
1925 uint32_t supported_enctypes;
1926 uint32_t *available_enctypes;
1927 krb5_const_principal salt_principal;
1928 const struct AuthenticationInformationArray *auth_array;
1931 static krb5_error_code samba_kdc_fill_trust_keys(krb5_context context,
1932 struct samba_kdc_trust_keys *p)
1935 * Make sure we'll never reveal DES keys
1937 uint32_t supported_enctypes = p->supported_enctypes &= ~(ENC_CRC32 | ENC_RSA_MD5);
1938 uint32_t _available_enctypes = 0;
1939 uint32_t *available_enctypes = p->available_enctypes;
1940 uint32_t _returned_kvno = 0;
1941 uint32_t *returned_kvno = p->returned_kvno;
1942 TALLOC_CTX *frame = talloc_stackframe();
1943 const struct AuthenticationInformationArray *aa = p->auth_array;
1944 DATA_BLOB password_utf16 = { .length = 0, };
1945 DATA_BLOB password_utf8 = { .length = 0, };
1946 struct samr_Password _password_hash = { .hash = { 0,}, };
1947 const struct samr_Password *password_hash = NULL;
1948 uint32_t allocated_keys = 0;
1949 uint32_t i;
1950 int ret;
1952 if (available_enctypes == NULL) {
1953 available_enctypes = &_available_enctypes;
1956 *available_enctypes = 0;
1958 if (returned_kvno == NULL) {
1959 returned_kvno = &_returned_kvno;
1962 *returned_kvno = p->kvno;
1964 for (i=0; i < aa->count; i++) {
1965 if (aa->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1966 const struct AuthInfoClear *clear =
1967 &aa->array[i].AuthInfo.clear;
1968 bool ok;
1970 password_utf16 = data_blob_const(clear->password,
1971 clear->size);
1972 if (password_utf16.length == 0) {
1973 break;
1976 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1977 mdfour(_password_hash.hash,
1978 password_utf16.data,
1979 password_utf16.length);
1980 if (password_hash == NULL) {
1981 allocated_keys += 1;
1983 password_hash = &_password_hash;
1986 if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1987 break;
1990 ok = convert_string_talloc(frame,
1991 CH_UTF16MUNGED, CH_UTF8,
1992 password_utf16.data,
1993 password_utf16.length,
1994 &password_utf8.data,
1995 &password_utf8.length);
1996 if (!ok) {
1997 krb5_clear_error_message(context);
1998 ret = ENOMEM;
1999 goto fail;
2002 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
2003 allocated_keys += 1;
2005 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
2006 allocated_keys += 1;
2008 break;
2009 } else if (aa->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
2010 const struct AuthInfoNT4Owf *nt4owf =
2011 &aa->array[i].AuthInfo.nt4owf;
2013 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
2014 password_hash = &nt4owf->password;
2015 allocated_keys += 1;
2020 allocated_keys = MAX(1, allocated_keys);
2022 /* allocate space to decode into */
2023 p->skeys->len = 0;
2024 p->skeys->val = calloc(allocated_keys, sizeof(struct sdb_key));
2025 if (p->skeys->val == NULL) {
2026 krb5_clear_error_message(context);
2027 ret = ENOMEM;
2028 goto fail;
2031 if (password_utf8.length != 0) {
2032 struct sdb_key key = {};
2033 krb5_data salt;
2034 krb5_data cleartext_data;
2036 cleartext_data.data = discard_const_p(char, password_utf8.data);
2037 cleartext_data.length = password_utf8.length;
2039 ret = smb_krb5_get_pw_salt(context,
2040 p->salt_principal,
2041 &salt);
2042 if (ret != 0) {
2043 goto fail;
2046 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
2047 key.salt = calloc(1, sizeof(*key.salt));
2048 if (key.salt == NULL) {
2049 smb_krb5_free_data_contents(context, &salt);
2050 ret = ENOMEM;
2051 goto fail;
2054 key.salt->type = KRB5_PW_SALT;
2056 ret = smb_krb5_copy_data_contents(&key.salt->salt,
2057 salt.data,
2058 salt.length);
2059 if (ret) {
2060 *key.salt = (struct sdb_salt) {};
2061 sdb_key_free(&key);
2062 smb_krb5_free_data_contents(context, &salt);
2063 goto fail;
2066 ret = smb_krb5_create_key_from_string(context,
2067 p->salt_principal,
2068 &salt,
2069 &cleartext_data,
2070 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
2071 &key.key);
2072 if (ret == 0) {
2073 p->skeys->val[p->skeys->len++] = key;
2074 *available_enctypes |= ENC_HMAC_SHA1_96_AES256;
2075 } else if (ret == KRB5_PROG_ETYPE_NOSUPP) {
2076 DBG_NOTICE("Unsupported keytype ignored - type %u\n",
2077 ENCTYPE_AES256_CTS_HMAC_SHA1_96);
2078 ZERO_STRUCT(key.key);
2079 sdb_key_free(&key);
2080 ret = 0;
2082 if (ret != 0) {
2083 ZERO_STRUCT(key.key);
2084 sdb_key_free(&key);
2085 smb_krb5_free_data_contents(context, &salt);
2086 goto fail;
2090 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
2091 key.salt = calloc(1, sizeof(*key.salt));
2092 if (key.salt == NULL) {
2093 smb_krb5_free_data_contents(context, &salt);
2094 ret = ENOMEM;
2095 goto fail;
2098 key.salt->type = KRB5_PW_SALT;
2100 ret = smb_krb5_copy_data_contents(&key.salt->salt,
2101 salt.data,
2102 salt.length);
2103 if (ret) {
2104 *key.salt = (struct sdb_salt) {};
2105 sdb_key_free(&key);
2106 smb_krb5_free_data_contents(context, &salt);
2107 goto fail;
2110 ret = smb_krb5_create_key_from_string(context,
2111 p->salt_principal,
2112 &salt,
2113 &cleartext_data,
2114 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
2115 &key.key);
2116 if (ret == 0) {
2117 p->skeys->val[p->skeys->len++] = key;
2118 *available_enctypes |= ENC_HMAC_SHA1_96_AES128;
2119 } else if (ret == KRB5_PROG_ETYPE_NOSUPP) {
2120 DBG_NOTICE("Unsupported keytype ignored - type %u\n",
2121 ENCTYPE_AES128_CTS_HMAC_SHA1_96);
2122 ZERO_STRUCT(key.key);
2123 sdb_key_free(&key);
2124 ret = 0;
2126 if (ret != 0) {
2127 ZERO_STRUCT(key.key);
2128 sdb_key_free(&key);
2129 smb_krb5_free_data_contents(context, &salt);
2130 goto fail;
2134 smb_krb5_free_data_contents(context, &salt);
2137 if (password_hash != NULL) {
2138 struct sdb_key key = {};
2140 ret = smb_krb5_keyblock_init_contents(context,
2141 ENCTYPE_ARCFOUR_HMAC,
2142 password_hash->hash,
2143 sizeof(password_hash->hash),
2144 &key.key);
2145 if (ret == 0) {
2146 p->skeys->val[p->skeys->len++] = key;
2148 *available_enctypes |= ENC_RC4_HMAC_MD5;
2149 } else if (ret == KRB5_PROG_ETYPE_NOSUPP) {
2150 DEBUG(2,("Unsupported keytype ignored - type %u\n",
2151 ENCTYPE_ARCFOUR_HMAC));
2152 ZERO_STRUCT(key.key);
2153 sdb_key_free(&key);
2154 ret = 0;
2156 if (ret != 0) {
2157 ZERO_STRUCT(key.key);
2158 sdb_key_free(&key);
2159 goto fail;
2163 samba_kdc_sort_keys(p->skeys);
2165 return 0;
2166 fail:
2167 sdb_keys_free(p->skeys);
2168 TALLOC_FREE(frame);
2169 return ret;
2173 * Construct an hdb_entry from a directory entry.
2174 * The kvno is what the remote client asked for
2176 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
2177 struct samba_kdc_db_context *kdc_db_ctx,
2178 TALLOC_CTX *mem_ctx,
2179 enum trust_direction direction,
2180 struct ldb_dn *realm_dn,
2181 unsigned flags,
2182 uint32_t kvno,
2183 struct ldb_message *msg,
2184 struct sdb_entry *entry)
2186 TALLOC_CTX *tmp_ctx = NULL;
2187 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
2188 const char *our_realm = lpcfg_realm(lp_ctx);
2189 char *partner_realm = NULL;
2190 const char *realm = NULL;
2191 const char *krbtgt_realm = NULL;
2192 const struct ldb_val *password_val;
2193 struct trustAuthInOutBlob password_blob;
2194 struct samba_kdc_entry *p;
2195 bool use_previous = false;
2196 bool include_previous = false;
2197 uint32_t current_kvno;
2198 uint32_t previous_kvno;
2199 struct samba_kdc_trust_keys current_keys = {};
2200 struct samba_kdc_trust_keys previous_keys = {};
2201 enum ndr_err_code ndr_err;
2202 int ret;
2203 unsigned int i;
2204 NTTIME now = *kdc_db_ctx->current_nttime_ull;
2205 NTTIME an_hour_ago, an_hour;
2206 bool prefer_current = false;
2207 bool force_rc4 = lpcfg_kdc_force_enable_rc4_weak_session_keys(lp_ctx);
2208 uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
2209 uint32_t pa_supported_enctypes;
2210 uint32_t supported_session_etypes;
2211 uint32_t config_kdc_enctypes = lpcfg_kdc_supported_enctypes(lp_ctx);
2212 uint32_t kdc_enctypes =
2213 config_kdc_enctypes != 0 ?
2214 config_kdc_enctypes :
2215 ENC_ALL_TYPES;
2216 struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
2217 NTSTATUS status;
2218 uint32_t returned_kvno = 0;
2219 uint32_t available_enctypes = 0;
2221 *entry = (struct sdb_entry) {};
2223 tmp_ctx = talloc_new(mem_ctx);
2224 if (tmp_ctx == NULL) {
2225 return ENOMEM;
2228 if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
2229 /* If not told otherwise, Windows now assumes that trusts support AES. */
2230 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
2231 "msDS-SupportedEncryptionTypes",
2232 ENC_HMAC_SHA1_96_AES256);
2235 pa_supported_enctypes = supported_enctypes;
2236 supported_session_etypes = supported_enctypes;
2237 if (supported_session_etypes & ENC_HMAC_SHA1_96_AES256_SK) {
2238 supported_session_etypes |= ENC_HMAC_SHA1_96_AES256;
2239 supported_session_etypes |= ENC_HMAC_SHA1_96_AES128;
2241 if (force_rc4) {
2242 supported_session_etypes |= ENC_RC4_HMAC_MD5;
2245 * now that we remembered what to announce in pa_supported_enctypes
2246 * and normalized ENC_HMAC_SHA1_96_AES256_SK, we restrict the
2247 * rest to the enc types the local kdc supports.
2249 supported_enctypes &= kdc_enctypes;
2250 supported_session_etypes &= kdc_enctypes;
2252 status = dsdb_trust_parse_tdo_info(tmp_ctx, msg, &tdo);
2253 if (!NT_STATUS_IS_OK(status)) {
2254 krb5_clear_error_message(context);
2255 ret = ENOMEM;
2256 goto out;
2259 if (!(tdo->trust_direction & direction)) {
2260 krb5_clear_error_message(context);
2261 ret = SDB_ERR_NOENTRY;
2262 goto out;
2265 if (tdo->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
2267 * Only UPLEVEL domains support kerberos here,
2268 * as we don't support LSA_TRUST_TYPE_MIT.
2270 krb5_clear_error_message(context);
2271 ret = SDB_ERR_NOENTRY;
2272 goto out;
2275 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
2277 * We don't support WITHIN_FOREST yet
2279 krb5_clear_error_message(context);
2280 ret = SDB_ERR_NOENTRY;
2281 goto out;
2284 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_PIM_TRUST) {
2286 * We don't support PIM_TRUST yet
2288 krb5_clear_error_message(context);
2289 ret = SDB_ERR_NOENTRY;
2290 goto out;
2293 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_CROSS_ORGANIZATION) {
2295 * We don't support selective authentication yet.
2297 krb5_clear_error_message(context);
2298 ret = SDB_ERR_NOENTRY;
2299 goto out;
2302 if (tdo->domain_name.string == NULL) {
2303 krb5_clear_error_message(context);
2304 ret = SDB_ERR_NOENTRY;
2305 goto out;
2307 partner_realm = strupper_talloc(tmp_ctx, tdo->domain_name.string);
2308 if (partner_realm == NULL) {
2309 krb5_clear_error_message(context);
2310 ret = ENOMEM;
2311 goto out;
2314 if (direction == INBOUND) {
2315 realm = our_realm;
2316 krbtgt_realm = partner_realm;
2318 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
2319 } else { /* OUTBOUND */
2320 realm = partner_realm;
2321 krbtgt_realm = our_realm;
2323 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
2326 if (password_val == NULL) {
2327 krb5_clear_error_message(context);
2328 ret = SDB_ERR_NOENTRY;
2329 goto out;
2332 ndr_err = ndr_pull_struct_blob(password_val, tmp_ctx, &password_blob,
2333 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2334 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2335 krb5_clear_error_message(context);
2336 ret = EINVAL;
2337 goto out;
2340 p = talloc_zero(tmp_ctx, struct samba_kdc_entry);
2341 if (!p) {
2342 ret = ENOMEM;
2343 goto out;
2346 p->is_trust = true;
2347 p->kdc_db_ctx = kdc_db_ctx;
2348 p->realm_dn = realm_dn;
2349 p->supported_enctypes = pa_supported_enctypes;
2350 p->current_nttime = *kdc_db_ctx->current_nttime_ull;
2352 talloc_set_destructor(p, samba_kdc_entry_destructor);
2354 entry->skdc_entry = p;
2356 /* use 'whenCreated' */
2357 entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
2358 /* use 'kadmin' for now (needed by mit_samba) */
2359 ret = smb_krb5_make_principal(context,
2360 &entry->created_by.principal,
2361 realm, "kadmin", NULL);
2362 if (ret) {
2363 krb5_clear_error_message(context);
2364 goto out;
2368 * We always need to generate the canonicalized principal
2369 * with the values of our database.
2371 ret = smb_krb5_make_principal(context, &entry->principal, realm,
2372 "krbtgt", krbtgt_realm, NULL);
2373 if (ret) {
2374 krb5_clear_error_message(context);
2375 goto out;
2377 smb_krb5_principal_set_type(context, entry->principal,
2378 KRB5_NT_SRV_INST);
2380 entry->valid_start = NULL;
2382 /* we need to work out if we are going to use the current or
2383 * the previous password hash.
2384 * We base this on the kvno the client passes in. If the kvno
2385 * passed in is equal to the current kvno in our database then
2386 * we use the current structure. If it is the current kvno-1,
2387 * then we use the previous substructure.
2391 * Windows prefers the previous key for one hour.
2394 an_hour = INT64_C(1000) * 1000 * 10 * 3600;
2397 * While a 'now' value of 0 is implausible, avoid this being a
2398 * silly value in that case
2400 if (now > an_hour) {
2401 an_hour_ago = now - an_hour;
2402 } else {
2403 an_hour_ago = now;
2406 /* first work out the current kvno */
2407 current_kvno = 0;
2408 for (i=0; i < password_blob.count; i++) {
2409 struct AuthenticationInformation *a =
2410 &password_blob.current.array[i];
2412 if (a->LastUpdateTime <= an_hour_ago) {
2413 prefer_current = true;
2416 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
2417 current_kvno = a->AuthInfo.version.version;
2420 if (current_kvno == 0) {
2421 previous_kvno = 255;
2422 } else {
2423 previous_kvno = current_kvno - 1;
2425 for (i=0; i < password_blob.count; i++) {
2426 struct AuthenticationInformation *a =
2427 &password_blob.previous.array[i];
2429 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
2430 previous_kvno = a->AuthInfo.version.version;
2434 /* work out whether we will use the previous or current
2435 password */
2436 if (password_blob.previous.count == 0) {
2437 /* there is no previous password */
2438 use_previous = false;
2439 } else if (!(flags & SDB_F_KVNO_SPECIFIED)) {
2441 * If not specified we use the lowest kvno
2442 * for the first hour after an update.
2444 if (prefer_current) {
2445 use_previous = false;
2446 } else if (previous_kvno < current_kvno) {
2447 use_previous = true;
2448 } else {
2449 use_previous = false;
2452 if (flags & SDB_F_ADMIN_DATA) {
2454 * let admin tool
2455 * get to all keys
2457 use_previous = false;
2458 include_previous = true;
2460 } else if (kvno == current_kvno) {
2462 * Exact match ...
2464 use_previous = false;
2465 } else if (kvno == previous_kvno) {
2467 * Exact match ...
2469 use_previous = true;
2470 } else {
2472 * Fallback to the current one for anything else
2474 use_previous = false;
2477 current_keys = (struct samba_kdc_trust_keys) {
2478 .kvno = current_kvno,
2479 .supported_enctypes = supported_enctypes,
2480 .salt_principal = entry->principal,
2481 .auth_array = &password_blob.current,
2484 previous_keys = (struct samba_kdc_trust_keys) {
2485 .kvno = previous_kvno,
2486 .supported_enctypes = supported_enctypes,
2487 .salt_principal = entry->principal,
2488 .auth_array = &password_blob.previous,
2491 if (use_previous) {
2493 * return the old keys as default keys
2494 * with the requested kvno.
2496 previous_keys.skeys = &entry->keys;
2497 previous_keys.available_enctypes = &available_enctypes;
2498 previous_keys.returned_kvno = &returned_kvno;
2499 } else {
2501 * return the current keys as default keys
2502 * with the requested kvno.
2504 current_keys.skeys = &entry->keys;
2505 current_keys.available_enctypes = &available_enctypes;
2506 current_keys.returned_kvno = &returned_kvno;
2508 if (include_previous) {
2510 * return the old keys in addition.
2512 previous_keys.skeys = &entry->old_keys;
2516 if (current_keys.skeys != NULL) {
2517 ret = samba_kdc_fill_trust_keys(context, &current_keys);
2518 if (ret != 0) {
2519 goto out;
2523 if (previous_keys.skeys != NULL) {
2524 ret = samba_kdc_fill_trust_keys(context, &previous_keys);
2525 if (ret != 0) {
2526 goto out;
2530 /* use the kvno the client specified, if available */
2531 if (flags & SDB_F_KVNO_SPECIFIED) {
2532 returned_kvno = kvno;
2535 /* Must have found a cleartext or MD4 password */
2536 if (entry->keys.len == 0) {
2537 DBG_WARNING("no usable key found\n");
2538 krb5_clear_error_message(context);
2539 ret = SDB_ERR_NOENTRY;
2540 goto out;
2543 entry->flags = (struct SDBFlags) {};
2544 entry->flags.immutable = 1;
2545 entry->flags.invalid = 0;
2546 entry->flags.server = 1;
2547 entry->flags.require_preauth = 1;
2549 entry->pw_end = NULL;
2551 entry->max_life = NULL;
2553 entry->max_renew = NULL;
2555 /* Match Windows behavior and allow forwardable flag in cross-realm. */
2556 entry->flags.forwardable = 1;
2558 entry->kvno = returned_kvno;
2561 * We need to support all session keys enctypes for
2562 * all keys we provide
2564 supported_session_etypes |= available_enctypes;
2566 ret = sdb_entry_set_etypes(entry);
2567 if (ret) {
2568 goto out;
2572 bool add_aes256 =
2573 supported_session_etypes & KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96;
2574 bool add_aes128 =
2575 supported_session_etypes & KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96;
2576 bool add_rc4 =
2577 supported_session_etypes & ENC_RC4_HMAC_MD5;
2578 ret = sdb_entry_set_session_etypes(entry,
2579 add_aes256,
2580 add_aes128,
2581 add_rc4);
2582 if (ret) {
2583 goto out;
2587 p->msg = talloc_steal(p, msg);
2589 talloc_steal(kdc_db_ctx, p);
2591 out:
2592 TALLOC_FREE(partner_realm);
2594 if (ret != 0) {
2595 /* This doesn't free ent itself, that is for the eventual caller to do */
2596 sdb_entry_free(entry);
2599 talloc_free(tmp_ctx);
2600 return ret;
2604 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
2605 TALLOC_CTX *mem_ctx,
2606 const char *realm,
2607 struct ldb_dn *realm_dn,
2608 struct ldb_message **pmsg)
2610 NTSTATUS status;
2611 const char * const *attrs = trust_attrs;
2613 status = dsdb_trust_search_tdo(ldb_ctx, realm, realm,
2614 attrs, mem_ctx, pmsg);
2615 if (NT_STATUS_IS_OK(status)) {
2616 return 0;
2617 } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2618 return SDB_ERR_NOENTRY;
2619 } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
2620 int ret = ENOMEM;
2621 krb5_set_error_message(context, ret, "samba_kdc_lookup_trust: out of memory");
2622 return ret;
2623 } else {
2624 int ret = EINVAL;
2625 krb5_set_error_message(context, ret, "samba_kdc_lookup_trust: %s", nt_errstr(status));
2626 return ret;
2630 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
2631 struct samba_kdc_db_context *kdc_db_ctx,
2632 TALLOC_CTX *mem_ctx,
2633 krb5_const_principal principal,
2634 const char **attrs,
2635 const uint32_t dsdb_flags,
2636 struct ldb_dn **realm_dn,
2637 struct ldb_message **msg)
2639 NTSTATUS nt_status;
2640 char *principal_string = NULL;
2642 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2643 krb5_error_code ret = 0;
2645 ret = smb_krb5_principal_get_comp_string(mem_ctx, context,
2646 principal, 0, &principal_string);
2647 if (ret) {
2648 return ret;
2650 } else {
2651 char *principal_string_m = NULL;
2652 krb5_error_code ret;
2654 ret = krb5_unparse_name(context, principal, &principal_string_m);
2655 if (ret != 0) {
2656 return ret;
2659 principal_string = talloc_strdup(mem_ctx, principal_string_m);
2660 SAFE_FREE(principal_string_m);
2661 if (principal_string == NULL) {
2662 return ENOMEM;
2666 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
2667 mem_ctx, principal_string, attrs, dsdb_flags,
2668 realm_dn, msg);
2669 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
2670 krb5_principal fallback_principal = NULL;
2671 unsigned int num_comp;
2672 char *fallback_realm = NULL;
2673 char *fallback_account = NULL;
2674 krb5_error_code ret;
2676 ret = krb5_parse_name(context, principal_string,
2677 &fallback_principal);
2678 TALLOC_FREE(principal_string);
2679 if (ret != 0) {
2680 return ret;
2683 num_comp = krb5_princ_size(context, fallback_principal);
2684 fallback_realm = smb_krb5_principal_get_realm(
2685 mem_ctx, context, fallback_principal);
2686 if (fallback_realm == NULL) {
2687 krb5_free_principal(context, fallback_principal);
2688 return ENOMEM;
2691 if (num_comp == 1) {
2692 size_t len;
2694 ret = smb_krb5_principal_get_comp_string(mem_ctx,
2695 context, fallback_principal, 0, &fallback_account);
2696 if (ret) {
2697 krb5_free_principal(context, fallback_principal);
2698 TALLOC_FREE(fallback_realm);
2699 return ret;
2702 len = strlen(fallback_account);
2703 if (len >= 2 && fallback_account[len - 1] == '$') {
2704 TALLOC_FREE(fallback_account);
2707 krb5_free_principal(context, fallback_principal);
2708 fallback_principal = NULL;
2710 if (fallback_account != NULL) {
2711 char *with_dollar;
2713 with_dollar = talloc_asprintf(mem_ctx, "%s$",
2714 fallback_account);
2715 if (with_dollar == NULL) {
2716 TALLOC_FREE(fallback_realm);
2717 return ENOMEM;
2719 TALLOC_FREE(fallback_account);
2721 ret = smb_krb5_make_principal(context,
2722 &fallback_principal,
2723 fallback_realm,
2724 with_dollar, NULL);
2725 TALLOC_FREE(with_dollar);
2726 if (ret != 0) {
2727 TALLOC_FREE(fallback_realm);
2728 return ret;
2731 TALLOC_FREE(fallback_realm);
2733 if (fallback_principal != NULL) {
2734 char *fallback_string = NULL;
2736 ret = krb5_unparse_name(context,
2737 fallback_principal,
2738 &fallback_string);
2739 if (ret != 0) {
2740 krb5_free_principal(context, fallback_principal);
2741 return ret;
2744 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
2745 mem_ctx,
2746 fallback_string,
2747 attrs, dsdb_flags,
2748 realm_dn, msg);
2749 SAFE_FREE(fallback_string);
2751 krb5_free_principal(context, fallback_principal);
2752 fallback_principal = NULL;
2754 TALLOC_FREE(principal_string);
2756 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
2757 return SDB_ERR_NOENTRY;
2758 } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
2759 return ENOMEM;
2760 } else if (!NT_STATUS_IS_OK(nt_status)) {
2761 return EINVAL;
2764 return 0;
2767 /* This is for the reset UF_SMARTCARD_REQUIRED password, but only in the expired case */
2768 static void smartcard_random_pw_update(TALLOC_CTX *mem_ctx,
2769 struct ldb_context *ldb,
2770 struct ldb_dn *dn)
2772 int ret;
2773 NTSTATUS status = NT_STATUS_OK;
2775 * The password_hash module expects these passwords to be
2776 * null‐terminated, so we zero-initialise with {}
2778 uint8_t new_password[128] = {};
2779 DATA_BLOB password_blob = {.data = new_password,
2780 .length = sizeof(new_password)};
2783 * This will be re-randomised in password_hash, but want this
2784 * to be random in a failure case
2786 generate_random_buffer(new_password, sizeof(new_password)-2);
2788 ret = ldb_transaction_start(ldb);
2789 if (ret != LDB_SUCCESS) {
2790 DBG_ERR("Transaction start for automated "
2791 "password rotation "
2792 "of soon-to-expire "
2793 "underlying password on account %s with "
2794 "UF_SMARTCARD_REQUIRED failed: %s\n",
2795 ldb_dn_get_linearized(dn),
2796 ldb_errstring(ldb));
2797 return;
2800 status = samdb_set_password(ldb,
2801 mem_ctx,
2803 &password_blob,
2804 NULL,
2805 DSDB_PASSWORD_KDC_RESET_SMARTCARD_ACCOUNT_PASSWORD,
2806 NULL, NULL);
2807 if (!NT_STATUS_IS_OK(status)) {
2808 ldb_transaction_cancel(ldb);
2809 DBG_ERR("Automated password rotation "
2810 "of soon-to-expire "
2811 "underlying password on account %s with "
2812 "UF_SMARTCARD_REQUIRED failed: %s\n",
2813 ldb_dn_get_linearized(dn),
2814 nt_errstr(status));
2815 return;
2818 ret = ldb_transaction_commit(ldb);
2819 if (ret != LDB_SUCCESS) {
2820 DBG_ERR("Transaction commit for automated "
2821 "password rotation "
2822 "of soon-to-expire "
2823 "underlying password on account %s with "
2824 "UF_SMARTCARD_REQUIRED failed: %s\n",
2825 ldb_dn_get_linearized(dn),
2826 ldb_errstring(ldb));
2830 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
2831 struct samba_kdc_db_context *kdc_db_ctx,
2832 TALLOC_CTX *mem_ctx,
2833 krb5_const_principal principal,
2834 unsigned flags,
2835 krb5_kvno kvno,
2836 struct sdb_entry *entry)
2838 struct ldb_dn *realm_dn;
2839 krb5_error_code ret;
2840 struct ldb_message *msg = NULL;
2841 int tries = 0;
2842 NTTIME pwd_last_set_last_loop = INT64_MAX;
2843 bool pwd_last_set_last_loop_set = false;
2846 * We will try up to 3 times to rotate the expired or soon to
2847 * expire password of a UF_SMARTCARD_REQUIRED account,
2848 * re-starting the search if we attempted a password change
2849 * (allowing the new secrets and expiry to be used).
2851 * A failure to change the password is not fatal, as password
2852 * changes are attempted before the ultimate expiry. This way
2853 * the server will still process an AS-REQ with PKINIT until
2854 * it (later, in the KDC code) finds the password has actually
2855 * expired.
2857 while (tries++ <= 2) {
2858 NTTIME pwd_last_set_this_loop;
2859 uint32_t attr_flags_computed;
2862 * When we look up the client, we also pre-rotate any expired
2863 * passwords in the UF_SMARTCARD_REQUIRED case
2865 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2866 mem_ctx, principal, user_attrs, DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
2867 &realm_dn, &msg);
2868 if (ret != 0) {
2869 return ret;
2872 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2873 principal, SAMBA_KDC_ENT_TYPE_CLIENT,
2874 flags, kvno,
2875 realm_dn, msg, entry);
2876 if (ret != 0) {
2877 return ret;
2880 if (!(flags & SDB_F_FOR_AS_REQ)) {
2881 break;
2884 /* This is the check on UF_SMARTCARD_REQUIRED */
2885 if (!(entry->flags.require_hwauth)) {
2886 break;
2890 * This check is also the configuration gate: the
2891 * operational module will set a
2892 * msDS-UserPasswordExpiryTimeComputed that in turn is
2893 * represented here as NULL unless the
2894 * expiry/auto-rotation of UF_SMARTCARD_REQUIRED
2895 * accounts is enabled
2897 if (entry->pw_end == NULL) {
2898 break;
2902 * Find if the pwdLastSet has changed on an account
2903 * that we are about to change the password for. If
2904 * we have both seen it and it has changed already, go
2905 * with that, even if it would fail the tests. As
2906 * well as dealing with races, this will avoid a
2907 * double-reset every loop if the TGT lifetime is
2908 * longer than the expiry.
2910 pwd_last_set_this_loop =
2911 ldb_msg_find_attr_as_int64(msg, "pwdLastSet", INT64_MAX);
2912 if (pwd_last_set_last_loop_set &&
2913 pwd_last_set_last_loop != pwd_last_set_this_loop) {
2914 break;
2916 pwd_last_set_last_loop = pwd_last_set_this_loop;
2917 pwd_last_set_last_loop_set = true;
2919 attr_flags_computed
2920 = ldb_msg_find_attr_as_uint(msg,
2921 "msDS-User-Account-Control-Computed",
2922 UF_PASSWORD_EXPIRED /* A safe if chaotic default */);
2923 if (attr_flags_computed & UF_PASSWORD_EXPIRED) {
2924 /* Already expired, keep processing */
2925 } else {
2927 * Will expire soon, but not already expired.
2929 * However we must first
2930 * check if this is before the TGT is due to
2931 * expire.
2933 * Then we check if we are half-way
2934 * though the password lifetime before we make
2935 * a password rotation.
2937 NTTIME must_change_time
2938 = samdb_result_nttime(msg,
2939 "msDS-UserPasswordExpiryTimeComputed",
2941 NTTIME pw_lifetime = must_change_time - pwd_last_set_this_loop;
2942 NTTIME pw_halflife = pw_lifetime / 2;
2943 if (must_change_time
2944 > entry->skdc_entry->enforced_tgt_lifetime_nt_ticks + entry->skdc_entry->current_nttime) {
2945 /* Password will not expire before TGT will */
2946 break;
2949 if (pwd_last_set_this_loop != 0
2950 && pwd_last_set_this_loop + pw_halflife > entry->skdc_entry->current_nttime) {
2952 * Still in first half of password
2953 * lifetime, no change per
2954 * https://lists.samba.org/archive/cifs-protocol/2024-May/004316.html
2956 break;
2958 /* Keep processing */
2961 if (kdc_db_ctx->rodc) {
2963 * Nothing we can do locally on an RODC. So
2964 * we trigger pushing the user back to the
2965 * full DC to ensure the PW is rotated.
2967 ret = SDB_ERR_NOT_FOUND_HERE;
2968 break;
2972 * Reset PW to random value. All we can do is loop
2973 * and hope we succeed again on failure, if we succeed
2974 * then we will pass the tests above and break out of the loop
2976 * We don't want to fail on error here as we might
2977 * still be able to provide service to the client if
2978 * the password is not yet actually expired. They may get
2979 * better luck at another KDC or at a later AS-REQ.
2981 smartcard_random_pw_update(mem_ctx, kdc_db_ctx->samdb, entry->skdc_entry->msg->dn);
2984 return ret;
2988 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
2989 struct samba_kdc_db_context *kdc_db_ctx,
2990 TALLOC_CTX *mem_ctx,
2991 krb5_const_principal principal,
2992 unsigned flags,
2993 uint32_t kvno,
2994 struct sdb_entry *entry)
2996 TALLOC_CTX *tmp_ctx = NULL;
2997 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
2998 krb5_error_code ret = 0;
2999 int is_krbtgt;
3000 struct ldb_message *msg = NULL;
3001 struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
3002 char *realm_from_princ;
3003 char *realm_princ_comp = NULL;
3005 tmp_ctx = talloc_new(mem_ctx);
3006 if (tmp_ctx == NULL) {
3007 ret = ENOMEM;
3008 goto out;
3011 realm_from_princ = smb_krb5_principal_get_realm(
3012 tmp_ctx, context, principal);
3013 if (realm_from_princ == NULL) {
3014 /* can't happen */
3015 ret = SDB_ERR_NOENTRY;
3016 goto out;
3019 is_krbtgt = smb_krb5_principal_is_tgs(context, principal);
3020 if (is_krbtgt == -1) {
3021 ret = ENOMEM;
3022 goto out;
3023 } else if (!is_krbtgt) {
3024 /* Not a krbtgt */
3025 ret = SDB_ERR_NOENTRY;
3026 goto out;
3029 /* krbtgt case. Either us or a trusted realm */
3031 ret = smb_krb5_principal_get_comp_string(tmp_ctx, context, principal, 1, &realm_princ_comp);
3032 if (ret == ENOENT) {
3033 /* OK. */
3034 } else if (ret) {
3035 goto out;
3038 if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
3039 && (realm_princ_comp == NULL || lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp))) {
3040 /* us, or someone quite like us */
3041 /* Kludge, kludge, kludge. If the realm part of krbtgt/realm,
3042 * is in our db, then direct the caller at our primary
3043 * krbtgt */
3045 int lret;
3046 unsigned int krbtgt_number;
3047 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
3048 trust tickets. We don't yet know what this means, but we do
3049 seem to need to treat it as unspecified */
3050 if (flags & (SDB_F_KVNO_SPECIFIED|SDB_F_RODC_NUMBER_SPECIFIED)) {
3051 krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
3052 if (kdc_db_ctx->rodc) {
3053 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
3054 ret = SDB_ERR_NOT_FOUND_HERE;
3055 goto out;
3058 } else {
3059 krbtgt_number = kdc_db_ctx->my_krbtgt_number;
3062 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
3063 lret = dsdb_search_one(kdc_db_ctx->samdb, tmp_ctx,
3064 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
3065 krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
3066 "(objectClass=user)");
3067 } else {
3068 /* We need to look up an RODC krbtgt (perhaps
3069 * ours, if we are an RODC, perhaps another
3070 * RODC if we are a read-write DC */
3071 lret = dsdb_search_one(kdc_db_ctx->samdb, tmp_ctx,
3072 &msg, realm_dn, LDB_SCOPE_SUBTREE,
3073 krbtgt_attrs,
3074 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
3075 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
3078 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
3079 krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
3080 (unsigned)(krbtgt_number));
3081 krb5_set_error_message(context, SDB_ERR_NOENTRY,
3082 "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
3083 (unsigned)(krbtgt_number));
3084 ret = SDB_ERR_NOENTRY;
3085 goto out;
3086 } else if (lret != LDB_SUCCESS) {
3087 krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
3088 (unsigned)(krbtgt_number));
3089 krb5_set_error_message(context, SDB_ERR_NOENTRY,
3090 "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
3091 (unsigned)(krbtgt_number));
3092 ret = SDB_ERR_NOENTRY;
3093 goto out;
3096 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
3097 principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
3098 flags, kvno, realm_dn, msg, entry);
3099 if (ret != 0) {
3100 krb5_warnx(context, "samba_kdc_fetch_krbtgt: self krbtgt message2entry failed");
3102 } else {
3103 enum trust_direction direction = UNKNOWN;
3104 const char *realm = NULL;
3106 /* Either an inbound or outbound trust */
3108 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
3109 /* look for inbound trust */
3110 direction = INBOUND;
3111 realm = realm_princ_comp;
3112 } else {
3113 bool eq = false;
3115 ret = is_principal_component_equal_ignoring_case(context, principal, 1, lpcfg_realm(lp_ctx), &eq);
3116 if (ret) {
3117 goto out;
3120 if (eq) {
3121 /* look for outbound trust */
3122 direction = OUTBOUND;
3123 realm = realm_from_princ;
3124 } else {
3125 krb5_warnx(context, "samba_kdc_fetch_krbtgt: not our realm for trusts ('%s', '%s')",
3126 realm_from_princ,
3127 realm_princ_comp);
3128 krb5_set_error_message(context, SDB_ERR_NOENTRY, "samba_kdc_fetch_krbtgt: not our realm for trusts ('%s', '%s')",
3129 realm_from_princ,
3130 realm_princ_comp);
3131 ret = SDB_ERR_NOENTRY;
3132 goto out;
3136 /* Trusted domains are under CN=system */
3138 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
3139 tmp_ctx,
3140 realm, realm_dn, &msg);
3142 if (ret != 0) {
3143 krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find principal in DB");
3144 krb5_set_error_message(context, ret, "samba_kdc_fetch_krbtgt: could not find principal in DB");
3145 goto out;
3148 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
3149 direction,
3150 realm_dn, flags, kvno, msg, entry);
3151 if (ret != 0) {
3152 krb5_warnx(context, "samba_kdc_fetch_krbtgt: trust_message2entry failed for %s",
3153 ldb_dn_get_linearized(msg->dn));
3154 krb5_set_error_message(context, ret, "samba_kdc_fetch_krbtgt: "
3155 "trust_message2entry failed for %s",
3156 ldb_dn_get_linearized(msg->dn));
3160 out:
3161 talloc_free(tmp_ctx);
3162 return ret;
3165 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
3166 struct samba_kdc_db_context *kdc_db_ctx,
3167 TALLOC_CTX *mem_ctx,
3168 krb5_const_principal principal,
3169 unsigned flags,
3170 struct ldb_dn **realm_dn,
3171 struct ldb_message **msg)
3173 krb5_error_code ret;
3174 if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
3175 && krb5_princ_size(context, principal) >= 2) {
3176 /* 'normal server' case */
3177 int ldb_ret;
3178 NTSTATUS nt_status;
3179 struct ldb_dn *user_dn;
3180 char *principal_string;
3182 ret = krb5_unparse_name_flags(context, principal,
3183 KRB5_PRINCIPAL_UNPARSE_NO_REALM,
3184 &principal_string);
3185 if (ret != 0) {
3186 return ret;
3189 /* At this point we may find the host is known to be
3190 * in a different realm, so we should generate a
3191 * referral instead */
3192 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
3193 mem_ctx, principal_string,
3194 &user_dn, realm_dn);
3195 free(principal_string);
3197 if (!NT_STATUS_IS_OK(nt_status)) {
3198 return SDB_ERR_NOENTRY;
3201 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
3202 mem_ctx,
3203 msg, user_dn, LDB_SCOPE_BASE,
3204 server_attrs,
3205 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
3206 "(objectClass=*)");
3207 if (ldb_ret != LDB_SUCCESS) {
3208 return SDB_ERR_NOENTRY;
3210 return 0;
3211 } else if (!(flags & SDB_F_FOR_AS_REQ)
3212 && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
3214 * The behaviour of accepting an
3215 * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
3216 * containing a UPN only applies to TGS-REQ packets,
3217 * not AS-REQ packets.
3219 return samba_kdc_lookup_client(context, kdc_db_ctx,
3220 mem_ctx, principal, server_attrs, DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
3221 realm_dn, msg);
3222 } else {
3224 * This case is for:
3225 * - the AS-REQ, where we only accept
3226 * samAccountName based lookups for the server, no
3227 * matter if the name is an
3228 * KRB5_NT_ENTERPRISE_PRINCIPAL or not
3229 * - for the TGS-REQ when we are not given an
3230 * KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
3231 * only lookup samAccountName based names.
3233 int lret;
3234 char *short_princ;
3235 krb5_principal enterprise_principal = NULL;
3236 krb5_const_principal used_principal = NULL;
3237 char *name1 = NULL;
3238 size_t len1 = 0;
3239 char *filter = NULL;
3241 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
3242 char *str = NULL;
3243 /* Need to reparse the enterprise principal to find the real target */
3244 if (krb5_princ_size(context, principal) != 1) {
3245 ret = KRB5_PARSE_MALFORMED;
3246 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
3247 "enterprise principal with wrong (%d) number of components",
3248 krb5_princ_size(context, principal));
3249 return ret;
3251 ret = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0, &str);
3252 if (ret) {
3253 return KRB5_PARSE_MALFORMED;
3255 ret = krb5_parse_name(context, str,
3256 &enterprise_principal);
3257 talloc_free(str);
3258 if (ret) {
3259 return ret;
3261 used_principal = enterprise_principal;
3262 } else {
3263 used_principal = principal;
3266 /* server as client principal case, but we must not lookup userPrincipalNames */
3267 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
3269 /* TODO: Check if it is our realm, otherwise give referral */
3271 ret = krb5_unparse_name_flags(context, used_principal,
3272 KRB5_PRINCIPAL_UNPARSE_NO_REALM |
3273 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
3274 &short_princ);
3275 used_principal = NULL;
3276 krb5_free_principal(context, enterprise_principal);
3277 enterprise_principal = NULL;
3279 if (ret != 0) {
3280 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: could not parse principal");
3281 krb5_warnx(context, "samba_kdc_lookup_server: could not parse principal");
3282 return ret;
3285 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
3286 SAFE_FREE(short_princ);
3287 if (name1 == NULL) {
3288 return ENOMEM;
3290 len1 = strlen(name1);
3291 if (len1 >= 1 && name1[len1 - 1] != '$') {
3292 filter = talloc_asprintf(mem_ctx,
3293 "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
3294 name1, name1);
3295 if (filter == NULL) {
3296 return ENOMEM;
3298 } else {
3299 filter = talloc_asprintf(mem_ctx,
3300 "(&(objectClass=user)(samAccountName=%s))",
3301 name1);
3302 if (filter == NULL) {
3303 return ENOMEM;
3307 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
3308 *realm_dn, LDB_SCOPE_SUBTREE,
3309 server_attrs,
3310 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
3311 "%s", filter);
3312 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
3313 DBG_DEBUG("Failed to find an entry for %s filter:%s\n",
3314 name1, filter);
3315 return SDB_ERR_NOENTRY;
3317 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
3318 DBG_DEBUG("Failed to find unique entry for %s filter:%s\n",
3319 name1, filter);
3320 return SDB_ERR_NOENTRY;
3322 if (lret != LDB_SUCCESS) {
3323 DBG_ERR("Failed single search for %s - %s\n",
3324 name1, ldb_errstring(kdc_db_ctx->samdb));
3325 return SDB_ERR_NOENTRY;
3327 return 0;
3329 return SDB_ERR_NOENTRY;
3334 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
3335 struct samba_kdc_db_context *kdc_db_ctx,
3336 TALLOC_CTX *mem_ctx,
3337 krb5_const_principal principal,
3338 unsigned flags,
3339 krb5_kvno kvno,
3340 struct sdb_entry *entry)
3342 krb5_error_code ret;
3343 struct ldb_dn *realm_dn;
3344 struct ldb_message *msg;
3346 ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
3347 flags, &realm_dn, &msg);
3348 if (ret != 0) {
3349 return ret;
3352 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
3353 principal, SAMBA_KDC_ENT_TYPE_SERVER,
3354 flags, kvno,
3355 realm_dn, msg, entry);
3356 if (ret != 0) {
3357 char *client_name = NULL;
3358 krb5_error_code code;
3360 code = krb5_unparse_name(context, principal, &client_name);
3361 if (code == 0) {
3362 krb5_warnx(context,
3363 "samba_kdc_fetch_server: message2entry failed for "
3364 "%s",
3365 client_name);
3366 } else {
3367 krb5_warnx(context,
3368 "samba_kdc_fetch_server: message2entry and "
3369 "krb5_unparse_name failed");
3371 SAFE_FREE(client_name);
3374 return ret;
3377 static krb5_error_code samba_kdc_lookup_realm(krb5_context context,
3378 struct samba_kdc_db_context *kdc_db_ctx,
3379 krb5_const_principal principal,
3380 unsigned flags,
3381 struct sdb_entry *entry)
3383 TALLOC_CTX *frame = talloc_stackframe();
3384 NTSTATUS status;
3385 krb5_error_code ret;
3386 bool check_realm = false;
3387 const char *realm = NULL;
3388 struct dsdb_trust_routing_table *trt = NULL;
3389 const struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
3390 unsigned int num_comp;
3391 bool ok;
3392 char *upper = NULL;
3394 *entry = (struct sdb_entry) {};
3396 num_comp = krb5_princ_size(context, principal);
3398 if (flags & SDB_F_GET_CLIENT) {
3399 if (flags & SDB_F_FOR_AS_REQ) {
3400 check_realm = true;
3403 if (flags & SDB_F_GET_SERVER) {
3404 if (flags & SDB_F_FOR_TGS_REQ) {
3405 check_realm = true;
3409 if (!check_realm) {
3410 TALLOC_FREE(frame);
3411 return 0;
3414 realm = smb_krb5_principal_get_realm(frame, context, principal);
3415 if (realm == NULL) {
3416 TALLOC_FREE(frame);
3417 return ENOMEM;
3421 * The requested realm needs to be our own
3423 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
3424 if (!ok) {
3426 * The request is not for us...
3428 TALLOC_FREE(frame);
3429 return SDB_ERR_NOENTRY;
3432 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
3433 char *principal_string = NULL;
3434 krb5_principal enterprise_principal = NULL;
3435 char *enterprise_realm = NULL;
3437 if (num_comp != 1) {
3438 TALLOC_FREE(frame);
3439 return SDB_ERR_NOENTRY;
3442 ret = smb_krb5_principal_get_comp_string(frame, context,
3443 principal, 0, &principal_string);
3444 if (ret) {
3445 TALLOC_FREE(frame);
3446 return ret;
3449 ret = krb5_parse_name(context, principal_string,
3450 &enterprise_principal);
3451 TALLOC_FREE(principal_string);
3452 if (ret) {
3453 TALLOC_FREE(frame);
3454 return ret;
3457 enterprise_realm = smb_krb5_principal_get_realm(
3458 frame, context, enterprise_principal);
3459 krb5_free_principal(context, enterprise_principal);
3460 if (enterprise_realm != NULL) {
3461 realm = enterprise_realm;
3465 if (flags & SDB_F_GET_SERVER) {
3466 bool is_krbtgt = false;
3468 ret = is_principal_component_equal(context, principal, 0, KRB5_TGS_NAME, &is_krbtgt);
3469 if (ret) {
3470 TALLOC_FREE(frame);
3471 return ret;
3474 if (is_krbtgt) {
3476 * we need to search krbtgt/ locally
3478 TALLOC_FREE(frame);
3479 return 0;
3483 * We need to check the last component against the routing table.
3485 * Note this works only with 2 or 3 component principals, e.g:
3487 * servicePrincipalName: ldap/W2K8R2-219.bla.base
3488 * servicePrincipalName: ldap/W2K8R2-219.bla.base/bla.base
3489 * servicePrincipalName: ldap/W2K8R2-219.bla.base/ForestDnsZones.bla.base
3490 * servicePrincipalName: ldap/W2K8R2-219.bla.base/DomainDnsZones.bla.base
3493 if (num_comp == 2 || num_comp == 3) {
3494 char *service_realm = NULL;
3496 ret = smb_krb5_principal_get_comp_string(frame,
3497 context,
3498 principal,
3499 num_comp - 1,
3500 &service_realm);
3501 if (ret) {
3502 TALLOC_FREE(frame);
3503 return ret;
3504 } else {
3505 realm = service_realm;
3510 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
3511 if (ok) {
3513 * skip the expensive routing lookup
3515 TALLOC_FREE(frame);
3516 return 0;
3519 status = dsdb_trust_routing_table_load(kdc_db_ctx->samdb,
3520 frame, &trt);
3521 if (!NT_STATUS_IS_OK(status)) {
3522 TALLOC_FREE(frame);
3523 return EINVAL;
3526 tdo = dsdb_trust_routing_by_name(trt, realm);
3527 if (tdo == NULL) {
3529 * This principal has to be local
3531 TALLOC_FREE(frame);
3532 return 0;
3535 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
3537 * TODO: handle the routing within the forest
3539 * This should likely be handled in
3540 * samba_kdc_message2entry() in case we're
3541 * a global catalog. We'd need to check
3542 * if realm_dn is our own domain and derive
3543 * the dns domain name from realm_dn and check that
3544 * against the routing table or fallback to
3545 * the tdo we found here.
3547 * But for now we don't support multiple domains
3548 * in our forest correctly anyway.
3550 * Just search in our local database.
3552 TALLOC_FREE(frame);
3553 return 0;
3556 ret = krb5_copy_principal(context, principal,
3557 &entry->principal);
3558 if (ret) {
3559 TALLOC_FREE(frame);
3560 return ret;
3563 upper = strupper_talloc(frame, tdo->domain_name.string);
3564 if (upper == NULL) {
3565 TALLOC_FREE(frame);
3566 return ENOMEM;
3569 ret = smb_krb5_principal_set_realm(context,
3570 entry->principal,
3571 upper);
3572 if (ret) {
3573 TALLOC_FREE(frame);
3574 return ret;
3577 TALLOC_FREE(frame);
3578 return SDB_ERR_WRONG_REALM;
3581 krb5_error_code samba_kdc_fetch(krb5_context context,
3582 struct samba_kdc_db_context *kdc_db_ctx,
3583 krb5_const_principal principal,
3584 unsigned flags,
3585 krb5_kvno kvno,
3586 struct sdb_entry *entry)
3588 krb5_error_code ret = SDB_ERR_NOENTRY;
3589 TALLOC_CTX *mem_ctx;
3591 mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
3592 if (!mem_ctx) {
3593 ret = ENOMEM;
3594 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
3595 return ret;
3598 ret = samba_kdc_lookup_realm(context, kdc_db_ctx,
3599 principal, flags, entry);
3600 if (ret != 0) {
3601 goto done;
3604 ret = SDB_ERR_NOENTRY;
3606 if (flags & SDB_F_GET_CLIENT) {
3607 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
3608 if (ret != SDB_ERR_NOENTRY) goto done;
3610 if (flags & SDB_F_GET_SERVER) {
3611 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
3612 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
3613 if (ret != SDB_ERR_NOENTRY) goto done;
3615 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
3616 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
3617 if (ret != SDB_ERR_NOENTRY) goto done;
3619 if (flags & SDB_F_GET_KRBTGT) {
3620 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
3621 if (ret != SDB_ERR_NOENTRY) goto done;
3624 done:
3625 talloc_free(mem_ctx);
3626 return ret;
3629 struct samba_kdc_seq {
3630 unsigned int index;
3631 unsigned int count;
3632 struct ldb_message **msgs;
3633 enum trust_direction trust_direction;
3634 unsigned int trust_index;
3635 unsigned int trust_count;
3636 struct ldb_message **trust_msgs;
3637 struct ldb_dn *realm_dn;
3640 static krb5_error_code samba_kdc_seq(krb5_context context,
3641 struct samba_kdc_db_context *kdc_db_ctx,
3642 const unsigned sdb_flags,
3643 struct sdb_entry *entry)
3645 krb5_error_code ret;
3646 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
3647 const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
3648 struct ldb_message *msg = NULL;
3649 const char *sAMAccountName = NULL;
3650 krb5_principal principal = NULL;
3651 TALLOC_CTX *mem_ctx;
3653 if (!priv) {
3654 return SDB_ERR_NOENTRY;
3657 mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
3659 if (!mem_ctx) {
3660 ret = ENOMEM;
3661 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
3662 goto out;
3665 if (priv->index == priv->count) {
3666 goto trusts;
3669 while (priv->index < priv->count) {
3670 msg = priv->msgs[priv->index++];
3672 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
3673 if (sAMAccountName != NULL) {
3674 break;
3678 if (sAMAccountName == NULL) {
3680 * This is not really possible,
3681 * but instead returning
3682 * SDB_ERR_NOENTRY, we
3683 * go on with trusts
3685 goto trusts;
3688 ret = smb_krb5_make_principal(context, &principal,
3689 realm, sAMAccountName, NULL);
3690 if (ret != 0) {
3691 goto out;
3694 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
3695 principal, SAMBA_KDC_ENT_TYPE_ANY,
3696 sdb_flags|SDB_F_GET_ANY,
3697 0 /* kvno */,
3698 priv->realm_dn, msg, entry);
3699 krb5_free_principal(context, principal);
3701 out:
3702 if (ret != 0) {
3703 TALLOC_FREE(priv);
3704 kdc_db_ctx->seq_ctx = NULL;
3705 } else {
3706 talloc_free(mem_ctx);
3709 return ret;
3711 trusts:
3712 while (priv->trust_index < priv->trust_count) {
3713 enum trust_direction trust_direction = priv->trust_direction;
3715 msg = priv->trust_msgs[priv->trust_index];
3717 if (trust_direction == INBOUND) {
3719 * This time we try INBOUND keys,
3720 * next time we'll do OUTBOUND
3721 * for the same trust.
3723 priv->trust_direction = OUTBOUND;
3726 * samba_kdc_trust_message2entry()
3727 * will likely steal msg from us,
3728 * so we need to make a copy for
3729 * the first run with INBOUND,
3730 * and let it steal without
3731 * a copy in the OUTBOUND run.
3733 msg = ldb_msg_copy(priv->trust_msgs, msg);
3734 if (msg == NULL) {
3735 return ENOMEM;
3737 } else {
3739 * This time we try OUTBOUND keys,
3740 * next time we'll do INBOUND for
3741 * the next trust.
3743 priv->trust_direction = INBOUND;
3744 priv->trust_index++;
3747 ret = samba_kdc_trust_message2entry(context,
3748 kdc_db_ctx,
3749 mem_ctx,
3750 trust_direction,
3751 priv->realm_dn,
3752 sdb_flags|SDB_F_GET_ANY,
3753 0, /* kvno */
3754 msg,
3755 entry);
3756 if (ret == SDB_ERR_NOENTRY) {
3757 continue;
3759 goto out;
3762 ret = SDB_ERR_NOENTRY;
3763 goto out;
3766 krb5_error_code samba_kdc_firstkey(krb5_context context,
3767 struct samba_kdc_db_context *kdc_db_ctx,
3768 const unsigned sdb_flags,
3769 struct sdb_entry *entry)
3771 struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
3772 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
3773 char *realm;
3774 struct ldb_result *res = NULL;
3775 krb5_error_code ret;
3776 int lret;
3777 NTSTATUS status;
3779 if (priv) {
3780 TALLOC_FREE(priv);
3781 kdc_db_ctx->seq_ctx = NULL;
3784 priv = talloc_zero(kdc_db_ctx, struct samba_kdc_seq);
3785 if (!priv) {
3786 ret = ENOMEM;
3787 krb5_set_error_message(context, ret, "talloc: out of memory");
3788 return ret;
3791 priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
3793 ret = krb5_get_default_realm(context, &realm);
3794 if (ret != 0) {
3795 TALLOC_FREE(priv);
3796 return ret;
3798 krb5_free_default_realm(context, realm);
3800 lret = dsdb_search(ldb_ctx, priv, &res,
3801 priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
3802 DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
3803 "(objectClass=user)");
3805 if (lret != LDB_SUCCESS) {
3806 TALLOC_FREE(priv);
3807 return SDB_ERR_NOENTRY;
3810 priv->count = res->count;
3811 priv->msgs = talloc_move(priv, &res->msgs);
3812 TALLOC_FREE(res);
3814 status = dsdb_trust_search_tdos(ldb_ctx,
3815 NULL, /* exclude */
3816 trust_attrs,
3817 priv,
3818 &res);
3819 if (!NT_STATUS_IS_OK(status)) {
3820 DBG_ERR("dsdb_trust_search_tdos() - %s\n",
3821 nt_errstr(status));
3822 TALLOC_FREE(priv);
3823 return SDB_ERR_NOENTRY;
3826 priv->trust_direction = INBOUND;
3827 priv->trust_count = res->count;
3828 priv->trust_msgs = talloc_move(priv, &res->msgs);
3829 TALLOC_FREE(res);
3831 kdc_db_ctx->seq_ctx = priv;
3833 ret = samba_kdc_seq(context, kdc_db_ctx, sdb_flags, entry);
3835 if (ret != 0) {
3836 TALLOC_FREE(priv);
3837 kdc_db_ctx->seq_ctx = NULL;
3839 return ret;
3842 krb5_error_code samba_kdc_nextkey(krb5_context context,
3843 struct samba_kdc_db_context *kdc_db_ctx,
3844 const unsigned sdb_flags,
3845 struct sdb_entry *entry)
3847 return samba_kdc_seq(context, kdc_db_ctx, sdb_flags, entry);
3850 /* Check if a given entry may delegate or do s4u2self to this target principal
3852 * The safest way to determine 'self' is to check the DB record made at
3853 * the time the principal was presented to the KDC.
3855 krb5_error_code
3856 samba_kdc_check_client_matches_target_service(krb5_context context,
3857 struct samba_kdc_entry *skdc_entry_client,
3858 struct samba_kdc_entry *skdc_entry_server_target)
3860 struct dom_sid *orig_sid;
3861 struct dom_sid *target_sid;
3862 TALLOC_CTX *frame = talloc_stackframe();
3864 orig_sid = samdb_result_dom_sid(frame,
3865 skdc_entry_client->msg,
3866 "objectSid");
3867 target_sid = samdb_result_dom_sid(frame,
3868 skdc_entry_server_target->msg,
3869 "objectSid");
3872 * Allow delegation to the same record (representing a
3873 * principal), even if by a different name. The easy and safe
3874 * way to prove this is by SID comparison
3876 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
3877 talloc_free(frame);
3878 return KRB5KRB_AP_ERR_BADMATCH;
3881 talloc_free(frame);
3882 return 0;
3885 /* Certificates printed by the Certificate Authority might have a
3886 * slightly different form of the user principal name to that in the
3887 * database. Allow a mismatch where they both refer to the same
3888 * SID */
3890 krb5_error_code
3891 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
3892 struct samba_kdc_db_context *kdc_db_ctx,
3893 struct samba_kdc_entry *skdc_entry,
3894 krb5_const_principal certificate_principal)
3896 krb5_error_code ret;
3897 struct ldb_dn *realm_dn;
3898 struct ldb_message *msg;
3899 struct dom_sid *orig_sid;
3900 struct dom_sid *target_sid;
3901 const char *ms_upn_check_attrs[] = {
3902 "objectSid", NULL
3905 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
3907 if (!mem_ctx) {
3908 ret = ENOMEM;
3909 krb5_set_error_message(context, ret, "samba_kdc_check_pkinit_ms_upn_match: talloc_named() failed!");
3910 return ret;
3913 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
3914 mem_ctx, certificate_principal,
3915 ms_upn_check_attrs, 0, &realm_dn, &msg);
3917 if (ret != 0) {
3918 talloc_free(mem_ctx);
3919 return ret;
3922 orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
3923 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
3925 /* Consider these to be the same principal, even if by a different
3926 * name. The easy and safe way to prove this is by SID
3927 * comparison */
3928 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
3929 talloc_free(mem_ctx);
3930 #if defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
3931 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
3932 #else /* Heimdal (where this is an enum) */
3933 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
3934 #endif
3937 talloc_free(mem_ctx);
3938 return ret;
3942 * Check if a given entry may delegate to this target principal
3943 * with S4U2Proxy.
3945 krb5_error_code
3946 samba_kdc_check_s4u2proxy(krb5_context context,
3947 struct samba_kdc_db_context *kdc_db_ctx,
3948 struct samba_kdc_entry *skdc_entry,
3949 krb5_const_principal target_principal)
3951 krb5_error_code ret;
3952 char *tmp = NULL;
3953 const char *client_dn = NULL;
3954 const char *target_principal_name = NULL;
3955 struct ldb_message_element *el;
3956 struct ldb_val val;
3957 unsigned int i;
3958 bool found = false;
3960 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
3962 if (!mem_ctx) {
3963 ret = ENOMEM;
3964 krb5_set_error_message(context, ret,
3965 "samba_kdc_check_s4u2proxy:"
3966 " talloc_named() failed!");
3967 return ret;
3970 client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
3971 if (!client_dn) {
3972 if (errno == 0) {
3973 errno = ENOMEM;
3975 ret = errno;
3976 krb5_set_error_message(context, ret,
3977 "samba_kdc_check_s4u2proxy:"
3978 " ldb_dn_get_linearized() failed!");
3979 talloc_free(mem_ctx);
3980 return ret;
3983 el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
3984 if (el == NULL) {
3985 ret = ENOENT;
3986 goto bad_option;
3988 SMB_ASSERT(el->num_values != 0);
3991 * This is the Microsoft forwardable flag behavior.
3993 * If the proxy (target) principal is NULL, and we have any authorized
3994 * delegation target, allow to forward.
3996 if (target_principal == NULL) {
3997 talloc_free(mem_ctx);
3998 return 0;
4003 * The main heimdal code already checked that the target_principal
4004 * belongs to the same realm as the client.
4006 * So we just need the principal without the realm,
4007 * as that is what is configured in the "msDS-AllowedToDelegateTo"
4008 * attribute.
4010 ret = krb5_unparse_name_flags(context, target_principal,
4011 KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
4012 if (ret) {
4013 talloc_free(mem_ctx);
4014 krb5_set_error_message(context, ret,
4015 "samba_kdc_check_s4u2proxy:"
4016 " krb5_unparse_name_flags() failed!");
4017 return ret;
4019 DBG_DEBUG("client[%s] for target[%s]\n",
4020 client_dn, tmp);
4022 target_principal_name = talloc_strdup(mem_ctx, tmp);
4023 SAFE_FREE(tmp);
4024 if (target_principal_name == NULL) {
4025 ret = ENOMEM;
4026 krb5_set_error_message(context, ret,
4027 "samba_kdc_check_s4u2proxy:"
4028 " talloc_strdup() failed!");
4029 talloc_free(mem_ctx);
4030 return ret;
4033 val = data_blob_string_const(target_principal_name);
4035 for (i=0; i<el->num_values; i++) {
4036 struct ldb_val *val1 = &val;
4037 struct ldb_val *val2 = &el->values[i];
4038 int cmp;
4040 if (val1->length != val2->length) {
4041 continue;
4044 cmp = strncasecmp((const char *)val1->data,
4045 (const char *)val2->data,
4046 val1->length);
4047 if (cmp != 0) {
4048 continue;
4051 found = true;
4052 break;
4055 if (!found) {
4056 ret = ENOENT;
4057 goto bad_option;
4060 DBG_DEBUG("client[%s] allowed target[%s]\n",
4061 client_dn, target_principal_name);
4062 talloc_free(mem_ctx);
4063 return 0;
4065 bad_option:
4066 krb5_set_error_message(context, ret,
4067 "samba_kdc_check_s4u2proxy: client[%s] "
4068 "not allowed for delegation to target[%s]",
4069 client_dn,
4070 target_principal_name);
4071 talloc_free(mem_ctx);
4072 return KRB5KDC_ERR_BADOPTION;
4076 * This method is called for S4U2Proxy requests and implements the
4077 * resource-based constrained delegation variant, which can support
4078 * cross-realm delegation.
4080 krb5_error_code samba_kdc_check_s4u2proxy_rbcd(
4081 krb5_context context,
4082 struct samba_kdc_db_context *kdc_db_ctx,
4083 krb5_const_principal client_principal,
4084 krb5_const_principal server_principal,
4085 const struct auth_user_info_dc *user_info_dc,
4086 const struct auth_user_info_dc *device_info_dc,
4087 const struct auth_claims auth_claims,
4088 struct samba_kdc_entry *proxy_skdc_entry)
4090 krb5_error_code code;
4091 enum ndr_err_code ndr_err;
4092 char *client_name = NULL;
4093 char *server_name = NULL;
4094 const char *proxy_dn = NULL;
4095 const DATA_BLOB *data = NULL;
4096 struct security_descriptor *rbcd_security_descriptor = NULL;
4097 struct security_token *security_token = NULL;
4098 uint32_t session_info_flags =
4099 AUTH_SESSION_INFO_DEFAULT_GROUPS |
4100 AUTH_SESSION_INFO_DEVICE_DEFAULT_GROUPS |
4101 AUTH_SESSION_INFO_SIMPLE_PRIVILEGES |
4102 AUTH_SESSION_INFO_FORCE_COMPOUNDED_AUTHENTICATION;
4104 * Testing shows that although Windows grants SEC_ADS_GENERIC_ALL access
4105 * in security descriptors it creates for RBCD, its KDC only requires
4106 * SEC_ADS_CONTROL_ACCESS for the access check to succeed.
4108 uint32_t access_desired = SEC_ADS_CONTROL_ACCESS;
4109 uint32_t access_granted = 0;
4110 NTSTATUS nt_status;
4111 TALLOC_CTX *mem_ctx = NULL;
4113 mem_ctx = talloc_named(kdc_db_ctx,
4115 "samba_kdc_check_s4u2proxy_rbcd");
4116 if (mem_ctx == NULL) {
4117 errno = ENOMEM;
4118 code = errno;
4120 return code;
4123 proxy_dn = ldb_dn_get_linearized(proxy_skdc_entry->msg->dn);
4124 if (proxy_dn == NULL) {
4125 DBG_ERR("ldb_dn_get_linearized failed for proxy_dn!\n");
4126 if (errno == 0) {
4127 errno = ENOMEM;
4129 code = errno;
4131 goto out;
4134 rbcd_security_descriptor = talloc_zero(mem_ctx,
4135 struct security_descriptor);
4136 if (rbcd_security_descriptor == NULL) {
4137 errno = ENOMEM;
4138 code = errno;
4140 goto out;
4143 code = krb5_unparse_name_flags(context,
4144 client_principal,
4145 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
4146 &client_name);
4147 if (code != 0) {
4148 DBG_ERR("Unable to parse client_principal!\n");
4149 goto out;
4152 code = krb5_unparse_name_flags(context,
4153 server_principal,
4154 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
4155 &server_name);
4156 if (code != 0) {
4157 DBG_ERR("Unable to parse server_principal!\n");
4158 goto out;
4161 DBG_INFO("Check delegation from client[%s] to server[%s] via "
4162 "proxy[%s]\n",
4163 client_name,
4164 server_name,
4165 proxy_dn);
4167 if (!(user_info_dc->info->user_flags & NETLOGON_GUEST)) {
4168 session_info_flags |= AUTH_SESSION_INFO_AUTHENTICATED;
4171 if (device_info_dc != NULL && !(device_info_dc->info->user_flags & NETLOGON_GUEST)) {
4172 session_info_flags |= AUTH_SESSION_INFO_DEVICE_AUTHENTICATED;
4175 nt_status = auth_generate_security_token(mem_ctx,
4176 kdc_db_ctx->lp_ctx,
4177 kdc_db_ctx->samdb,
4178 user_info_dc,
4179 device_info_dc,
4180 auth_claims,
4181 session_info_flags,
4182 &security_token);
4183 if (!NT_STATUS_IS_OK(nt_status)) {
4184 code = map_errno_from_nt_status(nt_status);
4185 goto out;
4188 data = ldb_msg_find_ldb_val(proxy_skdc_entry->msg,
4189 "msDS-AllowedToActOnBehalfOfOtherIdentity");
4190 if (data == NULL) {
4191 DBG_WARNING("Could not find security descriptor "
4192 "msDS-AllowedToActOnBehalfOfOtherIdentity in "
4193 "proxy[%s]\n",
4194 proxy_dn);
4195 code = KRB5KDC_ERR_BADOPTION;
4196 goto out;
4199 ndr_err = ndr_pull_struct_blob(
4200 data,
4201 mem_ctx,
4202 rbcd_security_descriptor,
4203 (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
4204 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4205 errno = ndr_map_error2errno(ndr_err);
4206 DBG_ERR("Failed to unmarshall "
4207 "msDS-AllowedToActOnBehalfOfOtherIdentity "
4208 "security descriptor of proxy[%s]\n",
4209 proxy_dn);
4210 code = KRB5KDC_ERR_BADOPTION;
4211 goto out;
4214 if (DEBUGLEVEL >= 10) {
4215 NDR_PRINT_DEBUG(security_token, security_token);
4216 NDR_PRINT_DEBUG(security_descriptor, rbcd_security_descriptor);
4219 nt_status = sec_access_check_ds(rbcd_security_descriptor,
4220 security_token,
4221 access_desired,
4222 &access_granted,
4223 NULL,
4224 NULL);
4226 if (!NT_STATUS_IS_OK(nt_status)) {
4227 DBG_WARNING("RBCD: sec_access_check_ds(access_desired=%#08x, "
4228 "access_granted:%#08x) failed with: %s\n",
4229 access_desired,
4230 access_granted,
4231 nt_errstr(nt_status));
4233 code = KRB5KDC_ERR_BADOPTION;
4234 goto out;
4237 DBG_NOTICE("RBCD: Access granted for client[%s]\n", client_name);
4239 code = 0;
4240 out:
4241 SAFE_FREE(client_name);
4242 SAFE_FREE(server_name);
4244 TALLOC_FREE(mem_ctx);
4245 return code;
4248 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
4249 struct samba_kdc_db_context **kdc_db_ctx_out)
4251 int ldb_ret;
4252 struct ldb_message *msg = NULL;
4253 struct samba_kdc_db_context *kdc_db_ctx = NULL;
4254 bool time_ok;
4256 /* The idea here is very simple. Using Kerberos to
4257 * authenticate the KDC to the LDAP server is highly likely to
4258 * be circular.
4260 * In future we may set this up to use EXTERNAL and SSL
4261 * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
4264 kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
4265 if (kdc_db_ctx == NULL) {
4266 return NT_STATUS_NO_MEMORY;
4268 kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
4269 kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
4270 kdc_db_ctx->msg_ctx = base_ctx->msg_ctx;
4272 /* Copy over the pointer that will be updated with the time */
4273 kdc_db_ctx->current_nttime_ull = base_ctx->current_nttime_ull;
4275 /* get default kdc policy */
4276 lpcfg_default_kdc_policy(mem_ctx,
4277 base_ctx->lp_ctx,
4278 &kdc_db_ctx->policy.svc_tkt_lifetime,
4279 &kdc_db_ctx->policy.usr_tkt_lifetime,
4280 &kdc_db_ctx->policy.renewal_lifetime);
4282 /* This is to allow "samba-tool domain exportkeytab to take a -H */
4283 if (base_ctx->samdb != NULL) {
4285 * Caller is responsible for lifetimes. In reality
4286 * the whole thing is destroyed before leaving the
4287 * function the samdb was passed into.
4289 * We assume this DB is created from python and so
4290 * can't be in the ldb_wrap cache.
4292 kdc_db_ctx->samdb = base_ctx->samdb;
4293 } else {
4294 struct auth_session_info *session_info = NULL;
4295 session_info = system_session(kdc_db_ctx->lp_ctx);
4296 if (session_info == NULL) {
4297 talloc_free(kdc_db_ctx);
4298 return NT_STATUS_INTERNAL_ERROR;
4301 /* Setup the link to LDB */
4302 kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx,
4303 base_ctx->ev_ctx,
4304 base_ctx->lp_ctx,
4305 session_info,
4306 NULL,
4307 SAMBA_LDB_WRAP_CONNECT_FLAG_NO_SHARE_CONTEXT);
4308 if (kdc_db_ctx->samdb == NULL) {
4309 DBG_WARNING("Cannot open samdb for KDC backend!\n");
4310 talloc_free(kdc_db_ctx);
4311 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
4316 * Set the current time pointer, which will be updated before
4317 * each packet (Heimdal) or fetch call (MIT)
4319 time_ok = dsdb_gmsa_set_current_time(kdc_db_ctx->samdb, kdc_db_ctx->current_nttime_ull);
4320 if (!time_ok) {
4321 talloc_free(kdc_db_ctx);
4322 return NT_STATUS_INTERNAL_ERROR;
4325 /* Find out our own krbtgt kvno */
4326 ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
4327 if (ldb_ret != LDB_SUCCESS) {
4328 DBG_WARNING("Cannot determine if we are an RODC in KDC backend: %s\n",
4329 ldb_errstring(kdc_db_ctx->samdb));
4330 talloc_free(kdc_db_ctx);
4331 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
4333 if (kdc_db_ctx->rodc) {
4334 int my_krbtgt_number;
4335 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
4336 struct ldb_dn *account_dn = NULL;
4337 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
4338 if (!server_dn) {
4339 DBG_WARNING("Cannot determine server DN in KDC backend: %s\n",
4340 ldb_errstring(kdc_db_ctx->samdb));
4341 talloc_free(kdc_db_ctx);
4342 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
4345 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
4346 "serverReference", &account_dn);
4347 if (ldb_ret != LDB_SUCCESS) {
4348 DBG_WARNING("Cannot determine server account in KDC backend: %s\n",
4349 ldb_errstring(kdc_db_ctx->samdb));
4350 talloc_free(kdc_db_ctx);
4351 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
4354 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
4355 "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
4356 talloc_free(account_dn);
4357 if (ldb_ret != LDB_SUCCESS) {
4358 DBG_WARNING("Cannot determine RODC krbtgt account in KDC backend: %s\n",
4359 ldb_errstring(kdc_db_ctx->samdb));
4360 talloc_free(kdc_db_ctx);
4361 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
4364 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
4365 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
4366 secondary_keytab,
4367 DSDB_SEARCH_NO_GLOBAL_CATALOG,
4368 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
4369 if (ldb_ret != LDB_SUCCESS) {
4370 DBG_WARNING("Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
4371 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
4372 ldb_errstring(kdc_db_ctx->samdb),
4373 ldb_strerror(ldb_ret));
4374 talloc_free(kdc_db_ctx);
4375 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
4377 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
4378 if (my_krbtgt_number == -1) {
4379 DBG_WARNING("Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
4380 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
4381 my_krbtgt_number);
4382 talloc_free(kdc_db_ctx);
4383 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
4385 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
4387 } else {
4388 kdc_db_ctx->my_krbtgt_number = 0;
4389 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
4390 &msg,
4391 ldb_get_default_basedn(kdc_db_ctx->samdb),
4392 LDB_SCOPE_SUBTREE,
4393 krbtgt_attrs,
4394 DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
4395 "(&(objectClass=user)(samAccountName=krbtgt))");
4397 if (ldb_ret != LDB_SUCCESS) {
4398 DBG_WARNING("could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb));
4399 talloc_free(kdc_db_ctx);
4400 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
4402 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
4403 kdc_db_ctx->my_krbtgt_number = 0;
4404 talloc_free(msg);
4406 *kdc_db_ctx_out = kdc_db_ctx;
4407 return NT_STATUS_OK;
4410 krb5_error_code dsdb_extract_aes_256_key(krb5_context context,
4411 TALLOC_CTX *mem_ctx,
4412 struct ldb_context *ldb,
4413 const struct ldb_message *msg,
4414 uint32_t user_account_control,
4415 const uint32_t *kvno,
4416 uint32_t *kvno_out,
4417 DATA_BLOB *aes_256_key,
4418 DATA_BLOB *salt)
4420 krb5_error_code krb5_ret;
4421 uint32_t supported_enctypes;
4422 unsigned flags = SDB_F_GET_CLIENT;
4423 struct sdb_entry sentry = {};
4425 if (kvno != NULL) {
4426 flags |= SDB_F_KVNO_SPECIFIED;
4429 krb5_ret = samba_kdc_message2entry_keys(context,
4430 mem_ctx,
4431 ldb,
4432 msg,
4433 false, /* is_krbtgt */
4434 false, /* is_rodc */
4435 user_account_control,
4436 SAMBA_KDC_ENT_TYPE_CLIENT,
4437 flags,
4438 (kvno != NULL) ? *kvno : 0,
4439 &sentry,
4440 ENC_HMAC_SHA1_96_AES256,
4441 &supported_enctypes);
4442 if (krb5_ret != 0) {
4443 const char *krb5_err = krb5_get_error_message(context, krb5_ret);
4445 DBG_ERR("Failed to parse supplementalCredentials "
4446 "of %s with %s kvno using "
4447 "ENCTYPE_HMAC_SHA1_96_AES256 "
4448 "Kerberos Key: %s\n",
4449 ldb_dn_get_linearized(msg->dn),
4450 (kvno != NULL) ? "previous" : "current",
4451 krb5_err != NULL ? krb5_err : "<unknown>");
4453 krb5_free_error_message(context, krb5_err);
4455 return krb5_ret;
4458 if ((supported_enctypes & ENC_HMAC_SHA1_96_AES256) == 0 ||
4459 sentry.keys.len != 1) {
4460 DBG_INFO("Failed to find a ENCTYPE_HMAC_SHA1_96_AES256 "
4461 "key in supplementalCredentials "
4462 "of %s at KVNO %u (got %u keys, expected 1)\n",
4463 ldb_dn_get_linearized(msg->dn),
4464 sentry.kvno,
4465 sentry.keys.len);
4466 sdb_entry_free(&sentry);
4467 return ENOENT;
4470 if (sentry.keys.val[0].salt == NULL) {
4471 DBG_INFO("Failed to find a salt in "
4472 "supplementalCredentials "
4473 "of %s at KVNO %u\n",
4474 ldb_dn_get_linearized(msg->dn),
4475 sentry.kvno);
4476 sdb_entry_free(&sentry);
4477 return ENOENT;
4480 if (aes_256_key != NULL) {
4481 *aes_256_key = data_blob_talloc(mem_ctx,
4482 KRB5_KEY_DATA(&sentry.keys.val[0].key),
4483 KRB5_KEY_LENGTH(&sentry.keys.val[0].key));
4484 if (aes_256_key->data == NULL) {
4485 sdb_entry_free(&sentry);
4486 return ENOMEM;
4488 talloc_keep_secret(aes_256_key->data);
4491 if (salt != NULL) {
4492 *salt = data_blob_talloc(mem_ctx,
4493 sentry.keys.val[0].salt->salt.data,
4494 sentry.keys.val[0].salt->salt.length);
4495 if (salt->data == NULL) {
4496 sdb_entry_free(&sentry);
4497 return ENOMEM;
4501 if (kvno_out != NULL) {
4502 *kvno_out = sentry.kvno;
4505 sdb_entry_free(&sentry);
4507 return 0;