ldb:attrib_handlers: use NUMERIC_CMP in ldb_comparison_fold
[Samba.git] / source4 / kdc / db-glue.c
blob1c00527d4818bed41d73720b147bd49cfef8223f
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/samdb/samdb.h"
30 #include "dsdb/common/util.h"
31 #include "librpc/gen_ndr/ndr_drsblobs.h"
32 #include "param/param.h"
33 #include "param/secrets.h"
34 #include "../lib/crypto/md4.h"
35 #include "system/kerberos.h"
36 #include "auth/kerberos/kerberos.h"
37 #include "kdc/authn_policy_util.h"
38 #include "kdc/sdb.h"
39 #include "kdc/samba_kdc.h"
40 #include "kdc/db-glue.h"
41 #include "kdc/pac-glue.h"
42 #include "librpc/gen_ndr/ndr_irpc_c.h"
43 #include "lib/messaging/irpc.h"
45 #undef DBGC_CLASS
46 #define DBGC_CLASS DBGC_KERBEROS
48 #undef strcasecmp
49 #undef strncasecmp
51 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
52 ((uint16_t)(((uint32_t)kvno) >> 16))
54 #define SAMBA_KVNO_GET_VALUE(kvno) \
55 ((uint16_t)(((uint32_t)kvno) & 0xFFFF))
57 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
58 ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
59 ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
61 enum trust_direction {
62 UNKNOWN = 0,
63 INBOUND = LSA_TRUST_DIRECTION_INBOUND,
64 OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
67 static const char *trust_attrs[] = {
68 "securityIdentifier",
69 "flatName",
70 "trustPartner",
71 "trustAttributes",
72 "trustDirection",
73 "trustType",
74 "msDS-TrustForestTrustInfo",
75 "trustAuthIncoming",
76 "trustAuthOutgoing",
77 "whenCreated",
78 "msDS-SupportedEncryptionTypes",
79 NULL
83 send a message to the drepl server telling it to initiate a
84 REPL_SECRET getncchanges extended op to fetch the users secrets
86 static void auth_sam_trigger_repl_secret(TALLOC_CTX *mem_ctx,
87 struct imessaging_context *msg_ctx,
88 struct tevent_context *event_ctx,
89 struct ldb_dn *user_dn)
91 struct dcerpc_binding_handle *irpc_handle;
92 struct drepl_trigger_repl_secret r;
93 struct tevent_req *req;
94 TALLOC_CTX *tmp_ctx;
96 tmp_ctx = talloc_new(mem_ctx);
97 if (tmp_ctx == NULL) {
98 return;
101 irpc_handle = irpc_binding_handle_by_name(tmp_ctx, msg_ctx,
102 "dreplsrv",
103 &ndr_table_irpc);
104 if (irpc_handle == NULL) {
105 DBG_WARNING("Unable to get binding handle for dreplsrv\n");
106 TALLOC_FREE(tmp_ctx);
107 return;
110 r.in.user_dn = ldb_dn_get_linearized(user_dn);
111 if (r.in.user_dn == NULL) {
112 DBG_WARNING("Unable to get user DN\n");
113 TALLOC_FREE(tmp_ctx);
114 return;
118 * This seem to rely on the current IRPC implementation,
119 * which delivers the message in the _send function.
121 * TODO: we need a ONE_WAY IRPC handle and register
122 * a callback and wait for it to be triggered!
124 req = dcerpc_drepl_trigger_repl_secret_r_send(tmp_ctx,
125 event_ctx,
126 irpc_handle,
127 &r);
129 /* we aren't interested in a reply */
130 talloc_free(req);
131 TALLOC_FREE(tmp_ctx);
134 static time_t ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, time_t default_val)
136 const struct ldb_val *gentime = NULL;
137 time_t t;
138 int ret;
140 gentime = ldb_msg_find_ldb_val(msg, attr);
141 ret = ldb_val_to_time(gentime, &t);
142 if (ret) {
143 return default_val;
146 return t;
149 static struct SDBFlags uf2SDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
151 struct SDBFlags flags = {};
153 /* we don't allow kadmin deletes */
154 flags.immutable = 1;
156 /* mark the principal as invalid to start with */
157 flags.invalid = 1;
159 flags.renewable = 1;
161 /* All accounts are servers, but this may be disabled again in the caller */
162 flags.server = 1;
164 /* Account types - clear the invalid bit if it turns out to be valid */
165 if (userAccountControl & UF_NORMAL_ACCOUNT) {
166 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
167 flags.client = 1;
169 flags.invalid = 0;
172 if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
173 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
174 flags.client = 1;
176 flags.invalid = 0;
178 if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
179 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
180 flags.client = 1;
182 flags.invalid = 0;
184 if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
185 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
186 flags.client = 1;
188 flags.invalid = 0;
191 /* Not permitted to act as a client if disabled */
192 if (userAccountControl & UF_ACCOUNTDISABLE) {
193 flags.client = 0;
195 if (userAccountControl & UF_LOCKOUT) {
196 flags.locked_out = 1;
199 if (userAccountControl & UF_PASSWD_NOTREQD) {
200 flags.invalid = 1;
204 UF_PASSWD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevant
206 if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
207 flags.invalid = 1;
210 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
213 if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
214 flags.invalid = 1;
217 if (userAccountControl & UF_SMARTCARD_REQUIRED) {
218 flags.require_hwauth = 1;
220 if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
221 flags.ok_as_delegate = 1;
223 if (userAccountControl & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
225 * this is confusing...
227 * UF_TRUSTED_FOR_DELEGATION
228 * => ok_as_delegate
230 * and
232 * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
233 * => trusted_for_delegation
235 flags.trusted_for_delegation = 1;
237 if (!(userAccountControl & UF_NOT_DELEGATED)) {
238 flags.forwardable = 1;
239 flags.proxiable = 1;
242 if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
243 flags.require_preauth = 0;
244 } else {
245 flags.require_preauth = 1;
248 if (userAccountControl & UF_NO_AUTH_DATA_REQUIRED) {
249 flags.no_auth_data_reqd = 1;
252 return flags;
255 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
257 if (p->db_entry != NULL) {
259 * A sdb_entry still has a reference
261 return -1;
264 if (p->kdc_entry != NULL) {
266 * hdb_entry or krb5_db_entry still
267 * have a reference...
269 return -1;
272 return 0;
276 * Sort keys in descending order of strength.
278 * Explanation from Greg Hudson:
280 * To encrypt tickets only the first returned key is used by the MIT KDC. The
281 * other keys just communicate support for session key enctypes, and aren't
282 * really used. The encryption key for the ticket enc part doesn't have
283 * to be of a type requested by the client. The session key enctype is chosen
284 * based on the client preference order, limited by the set of enctypes present
285 * in the server keys (unless the string attribute is set on the server
286 * principal overriding that set).
289 static int sdb_key_strength_priority(krb5_enctype etype)
291 static const krb5_enctype etype_list[] = {
292 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
293 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
294 ENCTYPE_DES3_CBC_SHA1,
295 ENCTYPE_ARCFOUR_HMAC,
296 ENCTYPE_DES_CBC_MD5,
297 ENCTYPE_DES_CBC_MD4,
298 ENCTYPE_DES_CBC_CRC,
299 ENCTYPE_NULL
301 int i;
303 for (i = 0; i < ARRAY_SIZE(etype_list); i++) {
304 if (etype == etype_list[i]) {
305 break;
309 return ARRAY_SIZE(etype_list) - i;
312 static int sdb_key_strength_cmp(const struct sdb_key *k1, const struct sdb_key *k2)
314 int p1 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k1->key));
315 int p2 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k2->key));
317 if (p1 == p2) {
318 return 0;
321 if (p1 > p2) {
323 * Higher priority comes first
325 return -1;
326 } else {
327 return 1;
331 static void samba_kdc_sort_keys(struct sdb_keys *keys)
333 if (keys == NULL) {
334 return;
337 TYPESAFE_QSORT(keys->val, keys->len, sdb_key_strength_cmp);
340 int samba_kdc_set_fixed_keys(krb5_context context,
341 const struct ldb_val *secretbuffer,
342 uint32_t supported_enctypes,
343 struct sdb_keys *keys)
345 uint16_t allocated_keys = 0;
346 int ret;
348 allocated_keys = 3;
349 keys->len = 0;
350 keys->val = calloc(allocated_keys, sizeof(struct sdb_key));
351 if (keys->val == NULL) {
352 memset(secretbuffer->data, 0, secretbuffer->length);
353 ret = ENOMEM;
354 goto out;
357 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
358 struct sdb_key key = {};
360 ret = smb_krb5_keyblock_init_contents(context,
361 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
362 secretbuffer->data,
363 MIN(secretbuffer->length, 32),
364 &key.key);
365 if (ret) {
366 memset(secretbuffer->data, 0, secretbuffer->length);
367 goto out;
370 keys->val[keys->len] = key;
371 keys->len++;
374 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
375 struct sdb_key key = {};
377 ret = smb_krb5_keyblock_init_contents(context,
378 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
379 secretbuffer->data,
380 MIN(secretbuffer->length, 16),
381 &key.key);
382 if (ret) {
383 memset(secretbuffer->data, 0, secretbuffer->length);
384 goto out;
387 keys->val[keys->len] = key;
388 keys->len++;
391 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
392 struct sdb_key key = {};
394 ret = smb_krb5_keyblock_init_contents(context,
395 ENCTYPE_ARCFOUR_HMAC,
396 secretbuffer->data,
397 MIN(secretbuffer->length, 16),
398 &key.key);
399 if (ret) {
400 memset(secretbuffer->data, 0, secretbuffer->length);
401 goto out;
404 keys->val[keys->len] = key;
405 keys->len++;
407 ret = 0;
408 out:
409 return ret;
413 static int samba_kdc_set_random_keys(krb5_context context,
414 uint32_t supported_enctypes,
415 struct sdb_keys *keys)
417 struct ldb_val secret_val;
418 uint8_t secretbuffer[32];
421 * Fake keys until we have a better way to reject
422 * non-pkinit requests.
424 * We just need to indicate which encryption types are
425 * supported.
427 generate_secret_buffer(secretbuffer, sizeof(secretbuffer));
429 secret_val = data_blob_const(secretbuffer,
430 sizeof(secretbuffer));
431 return samba_kdc_set_fixed_keys(context,
432 &secret_val,
433 supported_enctypes,
434 keys);
437 struct samba_kdc_user_keys {
438 struct sdb_keys *skeys;
439 uint32_t kvno;
440 uint32_t *returned_kvno;
441 uint32_t supported_enctypes;
442 uint32_t *available_enctypes;
443 const struct samr_Password *nthash;
444 const char *salt_string;
445 uint16_t num_pkeys;
446 const struct package_PrimaryKerberosKey4 *pkeys;
449 static krb5_error_code samba_kdc_fill_user_keys(krb5_context context,
450 struct samba_kdc_user_keys *p)
453 * Make sure we'll never reveal DES keys
455 uint32_t supported_enctypes = p->supported_enctypes &= ~(ENC_CRC32 | ENC_RSA_MD5);
456 uint32_t _available_enctypes = 0;
457 uint32_t *available_enctypes = p->available_enctypes;
458 uint32_t _returned_kvno = 0;
459 uint32_t *returned_kvno = p->returned_kvno;
460 uint32_t num_pkeys = p->num_pkeys;
461 uint32_t allocated_keys = num_pkeys;
462 uint32_t i;
463 int ret;
465 if (available_enctypes == NULL) {
466 available_enctypes = &_available_enctypes;
469 *available_enctypes = 0;
471 if (returned_kvno == NULL) {
472 returned_kvno = &_returned_kvno;
475 *returned_kvno = p->kvno;
477 if (p->nthash != NULL) {
478 allocated_keys += 1;
481 allocated_keys = MAX(1, allocated_keys);
483 /* allocate space to decode into */
484 p->skeys->len = 0;
485 p->skeys->val = calloc(allocated_keys, sizeof(struct sdb_key));
486 if (p->skeys->val == NULL) {
487 return ENOMEM;
490 for (i=0; i < num_pkeys; i++) {
491 struct sdb_key key = {};
492 uint32_t enctype_bit;
494 if (p->pkeys[i].value == NULL) {
495 continue;
498 enctype_bit = kerberos_enctype_to_bitmap(p->pkeys[i].keytype);
499 if (!(enctype_bit & supported_enctypes)) {
500 continue;
503 if (p->salt_string != NULL) {
504 DATA_BLOB salt;
506 salt = data_blob_string_const(p->salt_string);
508 key.salt = calloc(1, sizeof(*key.salt));
509 if (key.salt == NULL) {
510 ret = ENOMEM;
511 goto fail;
514 key.salt->type = KRB5_PW_SALT;
516 ret = smb_krb5_copy_data_contents(&key.salt->salt,
517 salt.data,
518 salt.length);
519 if (ret) {
520 *key.salt = (struct sdb_salt) {};
521 sdb_key_free(&key);
522 goto fail;
526 ret = smb_krb5_keyblock_init_contents(context,
527 p->pkeys[i].keytype,
528 p->pkeys[i].value->data,
529 p->pkeys[i].value->length,
530 &key.key);
531 if (ret == 0) {
532 p->skeys->val[p->skeys->len++] = key;
533 *available_enctypes |= enctype_bit;
534 continue;
536 ZERO_STRUCT(key.key);
537 sdb_key_free(&key);
538 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
539 DEBUG(2,("Unsupported keytype ignored - type %u\n",
540 p->pkeys[i].keytype));
541 ret = 0;
542 continue;
545 goto fail;
548 if (p->nthash != NULL && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
549 struct sdb_key key = {};
551 ret = smb_krb5_keyblock_init_contents(context,
552 ENCTYPE_ARCFOUR_HMAC,
553 p->nthash->hash,
554 sizeof(p->nthash->hash),
555 &key.key);
556 if (ret == 0) {
557 p->skeys->val[p->skeys->len++] = key;
559 *available_enctypes |= ENC_RC4_HMAC_MD5;
560 } else if (ret == KRB5_PROG_ETYPE_NOSUPP) {
561 DEBUG(2,("Unsupported keytype ignored - type %u\n",
562 ENCTYPE_ARCFOUR_HMAC));
563 ret = 0;
565 if (ret != 0) {
566 goto fail;
570 samba_kdc_sort_keys(p->skeys);
572 return 0;
573 fail:
574 sdb_keys_free(p->skeys);
575 return ret;
578 krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
579 TALLOC_CTX *mem_ctx,
580 struct ldb_context *ldb,
581 const struct ldb_message *msg,
582 bool is_krbtgt,
583 bool is_rodc,
584 uint32_t userAccountControl,
585 enum samba_kdc_ent_type ent_type,
586 unsigned flags,
587 krb5_kvno requested_kvno,
588 struct sdb_entry *entry,
589 const uint32_t supported_enctypes_in,
590 uint32_t *supported_enctypes_out)
592 krb5_error_code ret = 0;
593 enum ndr_err_code ndr_err;
594 struct samr_Password *hash;
595 unsigned int num_ntPwdHistory = 0;
596 struct samr_Password *ntPwdHistory = NULL;
597 struct samr_Password *old_hash = NULL;
598 struct samr_Password *older_hash = NULL;
599 const struct ldb_val *sc_val;
600 struct supplementalCredentialsBlob scb;
601 struct supplementalCredentialsPackage *scpk = NULL;
602 struct package_PrimaryKerberosBlob _pkb;
603 struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
604 int krbtgt_number = 0;
605 uint32_t current_kvno;
606 uint32_t old_kvno = 0;
607 uint32_t older_kvno = 0;
608 uint32_t returned_kvno = 0;
609 uint16_t i;
610 struct samba_kdc_user_keys keys = { .num_pkeys = 0, };
611 struct samba_kdc_user_keys old_keys = { .num_pkeys = 0, };
612 struct samba_kdc_user_keys older_keys = { .num_pkeys = 0, };
613 uint32_t available_enctypes = 0;
614 uint32_t supported_enctypes = supported_enctypes_in;
615 const bool exporting_keytab = flags & SDB_F_ADMIN_DATA;
617 *supported_enctypes_out = 0;
619 /* Is this the krbtgt or a RODC krbtgt */
620 if (is_rodc) {
621 krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
623 if (krbtgt_number == -1) {
624 return EINVAL;
626 if (krbtgt_number == 0) {
627 return EINVAL;
631 if (flags & SDB_F_USER2USER_PRINCIPAL) {
633 * User2User uses the session key
634 * from the additional ticket,
635 * so we just provide random keys
636 * here in order to make sure
637 * we never expose the user password
638 * keys.
640 ret = samba_kdc_set_random_keys(context,
641 supported_enctypes,
642 &entry->keys);
644 *supported_enctypes_out = supported_enctypes & ENC_ALL_TYPES;
646 goto out;
649 if ((ent_type == SAMBA_KDC_ENT_TYPE_CLIENT)
650 && (userAccountControl & UF_SMARTCARD_REQUIRED)) {
651 ret = samba_kdc_set_random_keys(context,
652 supported_enctypes,
653 &entry->keys);
655 *supported_enctypes_out = supported_enctypes & ENC_ALL_TYPES;
657 goto out;
660 current_kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
661 if (current_kvno > 1) {
662 old_kvno = current_kvno - 1;
664 if (current_kvno > 2) {
665 older_kvno = current_kvno - 2;
667 if (is_krbtgt) {
669 * Even for the main krbtgt account
670 * we have to strictly split the kvno into
671 * two 16-bit parts and the upper 16-bit
672 * need to be all zero, even if
673 * the msDS-KeyVersionNumber has a value
674 * larger than 65535.
676 * See https://bugzilla.samba.org/show_bug.cgi?id=14951
678 current_kvno = SAMBA_KVNO_GET_VALUE(current_kvno);
679 old_kvno = SAMBA_KVNO_GET_VALUE(old_kvno);
680 older_kvno = SAMBA_KVNO_GET_VALUE(older_kvno);
681 requested_kvno = SAMBA_KVNO_GET_VALUE(requested_kvno);
684 /* Get keys from the db */
686 hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
687 num_ntPwdHistory = samdb_result_hashes(mem_ctx, msg,
688 "ntPwdHistory",
689 &ntPwdHistory);
690 if (num_ntPwdHistory > 1) {
691 old_hash = &ntPwdHistory[1];
693 if (num_ntPwdHistory > 2) {
694 older_hash = &ntPwdHistory[2];
696 sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
698 /* supplementalCredentials if present */
699 if (sc_val) {
700 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
701 (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
702 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
703 ret = EINVAL;
704 goto out;
707 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
708 if (scb.sub.num_packages != 0) {
709 NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
710 ret = EINVAL;
711 goto out;
715 for (i=0; i < scb.sub.num_packages; i++) {
716 if (scb.sub.packages[i].name != NULL &&
717 strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0)
719 scpk = &scb.sub.packages[i];
720 if (!scpk->data || !scpk->data[0]) {
721 scpk = NULL;
722 continue;
724 break;
729 * Primary:Kerberos-Newer-Keys element
730 * of supplementalCredentials
732 * The legacy Primary:Kerberos only contains
733 * single DES keys, which are completely ignored
734 * now.
736 if (scpk) {
737 DATA_BLOB blob;
739 blob = strhex_to_data_blob(mem_ctx, scpk->data);
740 if (!blob.data) {
741 ret = ENOMEM;
742 goto out;
745 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
746 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
747 (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
748 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
749 ret = EINVAL;
750 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
751 krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
752 goto out;
755 if (_pkb.version != 4) {
756 ret = EINVAL;
757 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
758 krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
759 goto out;
762 pkb4 = &_pkb.ctr.ctr4;
765 keys = (struct samba_kdc_user_keys) {
766 .kvno = current_kvno,
767 .supported_enctypes = supported_enctypes,
768 .nthash = hash,
769 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
770 .num_pkeys = pkb4 != NULL ? pkb4->num_keys : 0,
771 .pkeys = pkb4 != NULL ? pkb4->keys : NULL,
774 old_keys = (struct samba_kdc_user_keys) {
775 .kvno = old_kvno,
776 .supported_enctypes = supported_enctypes,
777 .nthash = old_hash,
778 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
779 .num_pkeys = pkb4 != NULL ? pkb4->num_old_keys : 0,
780 .pkeys = pkb4 != NULL ? pkb4->old_keys : NULL,
782 older_keys = (struct samba_kdc_user_keys) {
783 .kvno = older_kvno,
784 .supported_enctypes = supported_enctypes,
785 .nthash = older_hash,
786 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
787 .num_pkeys = pkb4 != NULL ? pkb4->num_older_keys : 0,
788 .pkeys = pkb4 != NULL ? pkb4->older_keys : NULL,
791 if (flags & SDB_F_KVNO_SPECIFIED) {
792 if (requested_kvno == keys.kvno) {
794 * The current kvno was requested,
795 * so we return it.
797 keys.skeys = &entry->keys;
798 keys.available_enctypes = &available_enctypes;
799 keys.returned_kvno = &returned_kvno;
800 } else if (requested_kvno == 0) {
802 * don't return any keys
804 } else if (requested_kvno == old_keys.kvno) {
806 * return the old keys as default keys
807 * with the requested kvno.
809 old_keys.skeys = &entry->keys;
810 old_keys.available_enctypes = &available_enctypes;
811 old_keys.returned_kvno = &returned_kvno;
812 } else if (requested_kvno == older_keys.kvno) {
814 * return the older keys as default keys
815 * with the requested kvno.
817 older_keys.skeys = &entry->keys;
818 older_keys.available_enctypes = &available_enctypes;
819 older_keys.returned_kvno = &returned_kvno;
820 } else {
822 * don't return any keys
825 } else {
826 bool include_history = false;
828 if ((flags & SDB_F_GET_CLIENT) && (flags & SDB_F_FOR_AS_REQ)) {
829 include_history = true;
830 } else if (exporting_keytab) {
831 include_history = true;
834 keys.skeys = &entry->keys;
835 keys.available_enctypes = &available_enctypes;
836 keys.returned_kvno = &returned_kvno;
838 if (include_history && old_keys.kvno != 0) {
839 old_keys.skeys = &entry->old_keys;
841 if (include_history && older_keys.kvno != 0) {
842 older_keys.skeys = &entry->older_keys;
846 if (keys.skeys != NULL) {
847 ret = samba_kdc_fill_user_keys(context, &keys);
848 if (ret != 0) {
849 goto out;
853 if (old_keys.skeys != NULL) {
854 ret = samba_kdc_fill_user_keys(context, &old_keys);
855 if (ret != 0) {
856 goto out;
860 if (older_keys.skeys != NULL) {
861 ret = samba_kdc_fill_user_keys(context, &older_keys);
862 if (ret != 0) {
863 goto out;
867 *supported_enctypes_out |= available_enctypes;
869 if (is_krbtgt) {
871 * Even for the main krbtgt account
872 * we have to strictly split the kvno into
873 * two 16-bit parts and the upper 16-bit
874 * need to be all zero, even if
875 * the msDS-KeyVersionNumber has a value
876 * larger than 65535.
878 * See https://bugzilla.samba.org/show_bug.cgi?id=14951
880 returned_kvno = SAMBA_KVNO_AND_KRBTGT(returned_kvno, krbtgt_number);
882 entry->kvno = returned_kvno;
884 out:
885 return ret;
888 static krb5_error_code is_principal_component_equal_impl(krb5_context context,
889 krb5_const_principal principal,
890 unsigned int component,
891 const char *string,
892 bool do_strcasecmp,
893 bool *eq)
895 const char *p;
897 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
898 if (component >= krb5_princ_size(context, principal)) {
899 /* A non‐existent component compares equal to no string. */
900 *eq = false;
901 return 0;
903 p = krb5_principal_get_comp_string(context, principal, component);
904 if (p == NULL) {
905 return ENOENT;
907 if (do_strcasecmp) {
908 *eq = strcasecmp(p, string) == 0;
909 } else {
910 *eq = strcmp(p, string) == 0;
912 return 0;
913 #else
914 size_t len;
915 krb5_data d;
916 krb5_error_code ret = 0;
918 if (component > INT_MAX) {
919 return EINVAL;
922 if (component >= krb5_princ_size(context, principal)) {
923 /* A non‐existent component compares equal to no string. */
924 *eq = false;
925 return 0;
928 ret = smb_krb5_princ_component(context, principal, component, &d);
929 if (ret) {
930 return ret;
933 p = d.data;
935 len = strlen(string);
936 if (d.length != len) {
937 *eq = false;
938 return 0;
941 if (do_strcasecmp) {
942 *eq = strncasecmp(p, string, len) == 0;
943 } else {
944 *eq = memcmp(p, string, len) == 0;
946 return 0;
947 #endif
950 static krb5_error_code is_principal_component_equal_ignoring_case(krb5_context context,
951 krb5_const_principal principal,
952 unsigned int component,
953 const char *string,
954 bool *eq)
956 return is_principal_component_equal_impl(context,
957 principal,
958 component,
959 string,
960 true /* do_strcasecmp */,
961 eq);
964 static krb5_error_code is_principal_component_equal(krb5_context context,
965 krb5_const_principal principal,
966 unsigned int component,
967 const char *string,
968 bool *eq)
970 return is_principal_component_equal_impl(context,
971 principal,
972 component,
973 string,
974 false /* do_strcasecmp */,
975 eq);
978 static krb5_error_code is_kadmin_changepw(krb5_context context,
979 krb5_const_principal principal,
980 bool *is_changepw)
982 krb5_error_code ret = 0;
983 bool eq = false;
985 if (krb5_princ_size(context, principal) != 2) {
986 *is_changepw = false;
987 return 0;
990 ret = is_principal_component_equal(context, principal, 0, "kadmin", &eq);
991 if (ret) {
992 return ret;
995 if (!eq) {
996 *is_changepw = false;
997 return 0;
1000 ret = is_principal_component_equal(context, principal, 1, "changepw", &eq);
1001 if (ret) {
1002 return ret;
1005 *is_changepw = eq;
1006 return 0;
1009 static krb5_error_code samba_kdc_get_entry_principal(
1010 krb5_context context,
1011 struct samba_kdc_db_context *kdc_db_ctx,
1012 const char *samAccountName,
1013 enum samba_kdc_ent_type ent_type,
1014 unsigned flags,
1015 bool is_kadmin_changepw,
1016 krb5_const_principal in_princ,
1017 krb5_principal *out_princ)
1019 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1020 krb5_error_code code = 0;
1021 bool canon = flags & (SDB_F_CANON|SDB_F_FORCE_CANON);
1024 * If we are set to canonicalize, we get back the fixed UPPER
1025 * case realm, and the real username (ie matching LDAP
1026 * samAccountName)
1028 * Otherwise, if we are set to enterprise, we
1029 * get back the whole principal as-sent
1031 * Finally, if we are not set to canonicalize, we get back the
1032 * fixed UPPER case realm, but the as-sent username
1036 * We need to ensure that the kadmin/changepw principal isn't able to
1037 * issue krbtgt tickets, even if canonicalization is turned on.
1039 if (!is_kadmin_changepw) {
1040 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT && canon) {
1042 * When requested to do so, ensure that both
1043 * the realm values in the principal are set
1044 * to the upper case, canonical realm
1046 code = smb_krb5_make_principal(context,
1047 out_princ,
1048 lpcfg_realm(lp_ctx),
1049 "krbtgt",
1050 lpcfg_realm(lp_ctx),
1051 NULL);
1052 if (code != 0) {
1053 return code;
1055 smb_krb5_principal_set_type(context,
1056 *out_princ,
1057 KRB5_NT_SRV_INST);
1059 return 0;
1062 if ((canon && flags & (SDB_F_FORCE_CANON|SDB_F_FOR_AS_REQ)) ||
1063 (ent_type == SAMBA_KDC_ENT_TYPE_ANY && in_princ == NULL)) {
1065 * SDB_F_CANON maps from the canonicalize flag in the
1066 * packet, and has a different meaning between AS-REQ
1067 * and TGS-REQ. We only change the principal in the
1068 * AS-REQ case.
1070 * The SDB_F_FORCE_CANON if for new MIT KDC code that
1071 * wants the canonical name in all lookups, and takes
1072 * care to canonicalize only when appropriate.
1074 code = smb_krb5_make_principal(context,
1075 out_princ,
1076 lpcfg_realm(lp_ctx),
1077 samAccountName,
1078 NULL);
1079 return code;
1084 * For a krbtgt entry, this appears to be required regardless of the
1085 * canonicalize flag from the client.
1087 code = krb5_copy_principal(context, in_princ, out_princ);
1088 if (code != 0) {
1089 return code;
1093 * While we have copied the client principal, tests show that Win2k3
1094 * returns the 'corrected' realm, not the client-specified realm. This
1095 * code attempts to replace the client principal's realm with the one
1096 * we determine from our records
1098 code = smb_krb5_principal_set_realm(context,
1099 *out_princ,
1100 lpcfg_realm(lp_ctx));
1102 return code;
1106 * Construct an hdb_entry from a directory entry.
1108 static krb5_error_code samba_kdc_message2entry(krb5_context context,
1109 struct samba_kdc_db_context *kdc_db_ctx,
1110 TALLOC_CTX *mem_ctx,
1111 krb5_const_principal principal,
1112 enum samba_kdc_ent_type ent_type,
1113 unsigned flags,
1114 krb5_kvno kvno,
1115 struct ldb_dn *realm_dn,
1116 struct ldb_message *msg,
1117 struct sdb_entry *entry)
1119 TALLOC_CTX *tmp_ctx = NULL;
1120 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1121 uint32_t userAccountControl;
1122 uint32_t msDS_User_Account_Control_Computed;
1123 krb5_error_code ret = 0;
1124 krb5_boolean is_computer = FALSE;
1125 struct samba_kdc_entry *p;
1126 NTTIME acct_expiry;
1127 NTSTATUS status;
1128 bool protected_user = false;
1129 struct dom_sid sid;
1130 uint32_t rid;
1131 bool is_krbtgt = false;
1132 bool is_rodc = false;
1133 bool force_rc4 = lpcfg_kdc_force_enable_rc4_weak_session_keys(lp_ctx);
1134 struct ldb_message_element *objectclasses;
1135 struct ldb_val computer_val = data_blob_string_const("computer");
1136 struct ldb_val gmsa_oc_val = data_blob_string_const("msDS-GroupManagedServiceAccount");
1137 uint32_t config_default_supported_enctypes = lpcfg_kdc_default_domain_supported_enctypes(lp_ctx);
1138 uint32_t default_supported_enctypes =
1139 config_default_supported_enctypes != 0 ?
1140 config_default_supported_enctypes :
1141 ENC_RC4_HMAC_MD5 | ENC_HMAC_SHA1_96_AES256_SK;
1142 uint32_t supported_enctypes
1143 = ldb_msg_find_attr_as_uint(msg,
1144 "msDS-SupportedEncryptionTypes",
1145 default_supported_enctypes);
1146 uint32_t pa_supported_enctypes;
1147 uint32_t supported_session_etypes;
1148 uint32_t available_enctypes = 0;
1150 * also legacy enctypes are announced,
1151 * but effectively restricted by kdc_enctypes
1153 uint32_t domain_enctypes = ENC_RC4_HMAC_MD5 | ENC_RSA_MD5 | ENC_CRC32;
1154 uint32_t config_kdc_enctypes = lpcfg_kdc_supported_enctypes(lp_ctx);
1155 uint32_t kdc_enctypes =
1156 config_kdc_enctypes != 0 ?
1157 config_kdc_enctypes :
1158 ENC_ALL_TYPES;
1159 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
1161 const struct authn_kerberos_client_policy *authn_client_policy = NULL;
1162 const struct authn_server_policy *authn_server_policy = NULL;
1163 int64_t enforced_tgt_lifetime_raw;
1164 const bool user2user = (flags & SDB_F_USER2USER_PRINCIPAL);
1166 *entry = (struct sdb_entry) {};
1168 tmp_ctx = talloc_new(mem_ctx);
1169 if (tmp_ctx == NULL) {
1170 return ENOMEM;
1173 if (supported_enctypes == 0) {
1174 supported_enctypes = default_supported_enctypes;
1177 if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1178 domain_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
1181 if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
1182 is_rodc = true;
1185 if (!samAccountName) {
1186 ret = ENOENT;
1187 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
1188 goto out;
1191 objectclasses = ldb_msg_find_element(msg, "objectClass");
1193 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
1194 is_computer = TRUE;
1197 p = talloc_zero(tmp_ctx, struct samba_kdc_entry);
1198 if (!p) {
1199 ret = ENOMEM;
1200 goto out;
1203 if (objectclasses && ldb_msg_find_val(objectclasses, &gmsa_oc_val)) {
1204 p->group_managed_service_account = true;
1207 p->is_rodc = is_rodc;
1208 p->kdc_db_ctx = kdc_db_ctx;
1209 p->realm_dn = talloc_reference(p, realm_dn);
1210 if (!p->realm_dn) {
1211 ret = ENOMEM;
1212 goto out;
1215 talloc_set_destructor(p, samba_kdc_entry_destructor);
1217 entry->skdc_entry = p;
1219 userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
1221 msDS_User_Account_Control_Computed
1222 = ldb_msg_find_attr_as_uint(msg,
1223 "msDS-User-Account-Control-Computed",
1224 UF_ACCOUNTDISABLE);
1227 * This brings in the lockout flag, block the account if not
1228 * found. We need the weird UF_ACCOUNTDISABLE check because
1229 * we do not want to fail open if the value is not returned,
1230 * but 0 is a valid value (all OK)
1232 if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
1233 ret = EINVAL;
1234 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
1235 "no msDS-User-Account-Control-Computed present");
1236 goto out;
1237 } else {
1238 userAccountControl |= msDS_User_Account_Control_Computed;
1241 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
1242 p->is_krbtgt = true;
1245 /* First try and figure out the flags based on the userAccountControl */
1246 entry->flags = uf2SDBFlags(context, userAccountControl, ent_type);
1249 * Take control of the returned principal here, rather than
1250 * allowing the Heimdal code to do it as we have specific
1251 * behaviour around the forced realm to honour
1253 entry->flags.force_canonicalize = true;
1256 * Windows 2008 seems to enforce this (very sensible) rule by
1257 * default - don't allow offline attacks on a user's password
1258 * by asking for a ticket to them as a service (encrypted with
1259 * their probably pathetically insecure password)
1261 * But user2user avoids using the keys based on the password,
1262 * so we can allow it.
1265 if (entry->flags.server && !user2user
1266 && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
1267 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
1268 entry->flags.server = 0;
1273 * We restrict a 3-part SPN ending in my domain/realm to full
1274 * domain controllers.
1276 * This avoids any cases where (eg) a demoted DC still has
1277 * these more restricted SPNs.
1279 if (krb5_princ_size(context, principal) > 2) {
1280 char *third_part = NULL;
1281 bool is_our_realm;
1282 bool is_dc;
1284 ret = smb_krb5_principal_get_comp_string(tmp_ctx,
1285 context,
1286 principal,
1288 &third_part);
1289 if (ret) {
1290 krb5_set_error_message(context, ret, "smb_krb5_principal_get_comp_string: out of memory");
1291 goto out;
1294 is_our_realm = lpcfg_is_my_domain_or_realm(lp_ctx,
1295 third_part);
1296 is_dc = userAccountControl &
1297 (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT);
1298 if (is_our_realm && !is_dc) {
1299 entry->flags.server = 0;
1303 * To give the correct type of error to the client, we must
1304 * not just return the entry without .server set, we must
1305 * pretend the principal does not exist. Otherwise we may
1306 * return ERR_POLICY instead of
1307 * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
1309 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry->flags.server == 0) {
1310 ret = SDB_ERR_NOENTRY;
1311 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
1312 goto out;
1314 if (flags & SDB_F_ADMIN_DATA) {
1315 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
1316 * of the Heimdal KDC. They are stored in the traditional
1317 * DB for audit purposes, and still form part of the structure
1318 * we must return */
1320 /* use 'whenCreated' */
1321 entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1322 /* use 'kadmin' for now (needed by mit_samba) */
1324 ret = smb_krb5_make_principal(context,
1325 &entry->created_by.principal,
1326 lpcfg_realm(lp_ctx), "kadmin", NULL);
1327 if (ret) {
1328 krb5_clear_error_message(context);
1329 goto out;
1332 entry->modified_by = calloc(1, sizeof(struct sdb_event));
1333 if (entry->modified_by == NULL) {
1334 ret = ENOMEM;
1335 krb5_set_error_message(context, ret, "calloc: out of memory");
1336 goto out;
1339 /* use 'whenChanged' */
1340 entry->modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
1341 /* use 'kadmin' for now (needed by mit_samba) */
1342 ret = smb_krb5_make_principal(context,
1343 &entry->modified_by->principal,
1344 lpcfg_realm(lp_ctx), "kadmin", NULL);
1345 if (ret) {
1346 krb5_clear_error_message(context);
1347 goto out;
1352 /* The lack of password controls etc applies to krbtgt by
1353 * virtue of being that particular RID */
1354 ret = samdb_result_dom_sid_buf(msg, "objectSid", &sid);
1355 if (ret) {
1356 goto out;
1358 status = dom_sid_split_rid(NULL, &sid, NULL, &rid);
1359 if (!NT_STATUS_IS_OK(status)) {
1360 ret = EINVAL;
1361 goto out;
1364 if (rid == DOMAIN_RID_KRBTGT) {
1365 char *realm = NULL;
1367 entry->valid_end = NULL;
1368 entry->pw_end = NULL;
1370 entry->flags.invalid = 0;
1371 entry->flags.server = 1;
1373 realm = smb_krb5_principal_get_realm(
1374 tmp_ctx, context, principal);
1375 if (realm == NULL) {
1376 ret = ENOMEM;
1377 goto out;
1380 /* Don't mark all requests for the krbtgt/realm as
1381 * 'change password', as otherwise we could get into
1382 * trouble, and not enforce the password expiry.
1383 * Instead, only do it when request is for the kpasswd service */
1384 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1385 bool is_changepw = false;
1387 ret = is_kadmin_changepw(context, principal, &is_changepw);
1388 if (ret) {
1389 goto out;
1392 if (is_changepw && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
1393 entry->flags.change_pw = 1;
1397 TALLOC_FREE(realm);
1399 entry->flags.client = 0;
1400 entry->flags.forwardable = 1;
1401 entry->flags.ok_as_delegate = 1;
1402 } else if (is_rodc) {
1403 /* The RODC krbtgt account is like the main krbtgt,
1404 * but it does not have a changepw or kadmin
1405 * service */
1407 entry->valid_end = NULL;
1408 entry->pw_end = NULL;
1410 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
1411 entry->flags.client = 0;
1412 entry->flags.invalid = 0;
1413 entry->flags.server = 1;
1415 entry->flags.client = 0;
1416 entry->flags.forwardable = 1;
1417 entry->flags.ok_as_delegate = 0;
1418 } else if (entry->flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1419 /* The account/password expiry only applies when the account is used as a
1420 * client (ie password login), not when used as a server */
1422 /* Make very well sure we don't use this for a client,
1423 * it could bypass the password restrictions */
1424 entry->flags.client = 0;
1426 entry->valid_end = NULL;
1427 entry->pw_end = NULL;
1429 } else {
1430 NTTIME must_change_time
1431 = samdb_result_nttime(msg,
1432 "msDS-UserPasswordExpiryTimeComputed",
1434 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
1435 entry->pw_end = NULL;
1436 } else {
1437 entry->pw_end = malloc(sizeof(*entry->pw_end));
1438 if (entry->pw_end == NULL) {
1439 ret = ENOMEM;
1440 goto out;
1442 *entry->pw_end = nt_time_to_unix(must_change_time);
1445 acct_expiry = samdb_result_account_expires(msg);
1446 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
1447 entry->valid_end = NULL;
1448 } else {
1449 entry->valid_end = malloc(sizeof(*entry->valid_end));
1450 if (entry->valid_end == NULL) {
1451 ret = ENOMEM;
1452 goto out;
1454 *entry->valid_end = nt_time_to_unix(acct_expiry);
1458 ret = samba_kdc_get_entry_principal(context,
1459 kdc_db_ctx,
1460 samAccountName,
1461 ent_type,
1462 flags,
1463 entry->flags.change_pw,
1464 principal,
1465 &entry->principal);
1466 if (ret != 0) {
1467 krb5_clear_error_message(context);
1468 goto out;
1471 entry->valid_start = NULL;
1473 entry->max_life = malloc(sizeof(*entry->max_life));
1474 if (entry->max_life == NULL) {
1475 ret = ENOMEM;
1476 goto out;
1479 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1480 *entry->max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
1481 } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
1482 *entry->max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
1483 } else {
1484 *entry->max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
1485 kdc_db_ctx->policy.usr_tkt_lifetime);
1488 if (entry->flags.change_pw) {
1489 /* Limit lifetime of kpasswd tickets to two minutes or less. */
1490 *entry->max_life = MIN(*entry->max_life, CHANGEPW_LIFETIME);
1493 entry->max_renew = malloc(sizeof(*entry->max_renew));
1494 if (entry->max_renew == NULL) {
1495 ret = ENOMEM;
1496 goto out;
1499 *entry->max_renew = kdc_db_ctx->policy.renewal_lifetime;
1502 * A principal acting as a client that is not being looked up as the
1503 * principal of an armor ticket may have an authentication policy apply
1504 * to it.
1506 * We won’t get an authentication policy for the client of an S4U2Self
1507 * or S4U2Proxy request. Those clients are looked up with
1508 * SDB_F_FOR_TGS_REQ instead of with SDB_F_FOR_AS_REQ.
1510 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT &&
1511 (flags & SDB_F_FOR_AS_REQ) &&
1512 !(flags & SDB_F_ARMOR_PRINCIPAL))
1514 ret = authn_policy_kerberos_client(kdc_db_ctx->samdb, tmp_ctx, msg,
1515 &authn_client_policy);
1516 if (ret) {
1517 goto out;
1522 * A principal acting as a server may have an authentication policy
1523 * apply to it.
1525 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1526 ret = authn_policy_server(kdc_db_ctx->samdb, tmp_ctx, msg,
1527 &authn_server_policy);
1528 if (ret) {
1529 goto out;
1533 enforced_tgt_lifetime_raw = authn_policy_enforced_tgt_lifetime_raw(authn_client_policy);
1534 if (enforced_tgt_lifetime_raw != 0) {
1535 int64_t lifetime_secs = enforced_tgt_lifetime_raw;
1537 lifetime_secs /= INT64_C(1000) * 1000 * 10;
1538 lifetime_secs = MIN(lifetime_secs, INT_MAX);
1539 lifetime_secs = MAX(lifetime_secs, INT_MIN);
1542 * Set both lifetime and renewal time based only on the
1543 * configured maximum lifetime — not on the configured renewal
1544 * time. Yes, this is what Windows does.
1546 lifetime_secs = MIN(*entry->max_life, lifetime_secs);
1547 *entry->max_life = lifetime_secs;
1548 *entry->max_renew = lifetime_secs;
1551 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT && (flags & SDB_F_FOR_AS_REQ)) {
1552 int result;
1553 const struct auth_user_info_dc *user_info_dc = NULL;
1555 * These protections only apply to clients, so servers in the
1556 * Protected Users group may still have service tickets to them
1557 * encrypted with RC4. For accounts looked up as servers, note
1558 * that 'msg' does not contain the 'memberOf' attribute for
1559 * determining whether the account is a member of Protected
1560 * Users.
1562 * Additionally, Microsoft advises that accounts for services
1563 * and computers should never be members of Protected Users, or
1564 * they may fail to authenticate.
1566 ret = samba_kdc_get_user_info_from_db(tmp_ctx,
1567 kdc_db_ctx->samdb,
1569 msg,
1570 &user_info_dc);
1571 if (ret) {
1572 goto out;
1575 result = dsdb_is_protected_user(kdc_db_ctx->samdb,
1576 user_info_dc->sids,
1577 user_info_dc->num_sids);
1578 if (result == -1) {
1579 ret = EINVAL;
1580 goto out;
1583 protected_user = result;
1585 if (protected_user) {
1586 entry->flags.forwardable = 0;
1587 entry->flags.proxiable = 0;
1589 if (enforced_tgt_lifetime_raw == 0) {
1591 * If a TGT lifetime hasn’t been set, Protected
1592 * Users enforces a four hour TGT lifetime.
1594 *entry->max_life = MIN(*entry->max_life, 4 * 60 * 60);
1595 *entry->max_renew = MIN(*entry->max_renew, 4 * 60 * 60);
1600 if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
1601 bool enable_fast;
1603 is_krbtgt = true;
1606 * KDCs (and KDCs on RODCs)
1607 * ignore msDS-SupportedEncryptionTypes completely
1608 * but support all supported enctypes by the domain.
1610 supported_enctypes = domain_enctypes;
1612 enable_fast = lpcfg_kdc_enable_fast(kdc_db_ctx->lp_ctx);
1613 if (enable_fast) {
1614 supported_enctypes |= ENC_FAST_SUPPORTED;
1617 supported_enctypes |= ENC_CLAIMS_SUPPORTED;
1618 supported_enctypes |= ENC_COMPOUND_IDENTITY_SUPPORTED;
1621 * Resource SID compression is enabled implicitly, unless
1622 * disabled in msDS-SupportedEncryptionTypes.
1625 } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
1627 * DCs and RODCs computer accounts take
1628 * msDS-SupportedEncryptionTypes unmodified, but
1629 * force all enctypes supported by the domain.
1631 supported_enctypes |= domain_enctypes;
1633 } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
1634 (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
1636 * for AS-REQ the client chooses the enc types it
1637 * supports, and this will vary between computers a
1638 * user logs in from. Therefore, so that we accept any
1639 * of the client's keys for decrypting padata,
1640 * supported_enctypes should not restrict etype usage.
1642 * likewise for 'any' return as much as is supported,
1643 * to export into a keytab.
1645 supported_enctypes |= ENC_ALL_TYPES;
1648 /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
1649 if (userAccountControl & UF_USE_DES_KEY_ONLY) {
1650 supported_enctypes &= ~ENC_ALL_TYPES;
1653 if (protected_user) {
1654 supported_enctypes &= ~ENC_RC4_HMAC_MD5;
1657 pa_supported_enctypes = supported_enctypes;
1658 supported_session_etypes = supported_enctypes;
1659 if (supported_session_etypes & ENC_HMAC_SHA1_96_AES256_SK) {
1660 supported_session_etypes |= ENC_HMAC_SHA1_96_AES256;
1661 supported_session_etypes |= ENC_HMAC_SHA1_96_AES128;
1663 if (force_rc4) {
1664 supported_session_etypes |= ENC_RC4_HMAC_MD5;
1667 * now that we remembered what to announce in pa_supported_enctypes
1668 * and normalized ENC_HMAC_SHA1_96_AES256_SK, we restrict the
1669 * rest to the enc types the local kdc supports.
1671 supported_enctypes &= kdc_enctypes;
1672 supported_session_etypes &= kdc_enctypes;
1674 /* Get keys from the db */
1675 ret = samba_kdc_message2entry_keys(context, p,
1676 kdc_db_ctx->samdb, msg,
1677 is_krbtgt, is_rodc,
1678 userAccountControl,
1679 ent_type, flags, kvno, entry,
1680 supported_enctypes,
1681 &available_enctypes);
1682 if (ret) {
1683 /* Could be bogus data in the entry, or out of memory */
1684 goto out;
1688 * If we only have a nthash stored,
1689 * but a better session key would be
1690 * available, we fallback to fetching the
1691 * RC4_HMAC_MD5, which implicitly also
1692 * would allow an RC4_HMAC_MD5 session key.
1693 * But only if the kdc actually supports
1694 * RC4_HMAC_MD5.
1696 if (available_enctypes == 0 &&
1697 (supported_enctypes & ENC_RC4_HMAC_MD5) == 0 &&
1698 (supported_enctypes & ~ENC_RC4_HMAC_MD5) != 0 &&
1699 (kdc_enctypes & ENC_RC4_HMAC_MD5) != 0)
1701 supported_enctypes = ENC_RC4_HMAC_MD5;
1702 ret = samba_kdc_message2entry_keys(context, p,
1703 kdc_db_ctx->samdb, msg,
1704 is_krbtgt, is_rodc,
1705 userAccountControl,
1706 ent_type, flags, kvno, entry,
1707 supported_enctypes,
1708 &available_enctypes);
1709 if (ret) {
1710 /* Could be bogus data in the entry, or out of memory */
1711 goto out;
1716 * We need to support all session keys enctypes for
1717 * all keys we provide
1719 supported_session_etypes |= available_enctypes;
1721 ret = sdb_entry_set_etypes(entry);
1722 if (ret) {
1723 goto out;
1726 if (entry->flags.server) {
1727 bool add_aes256 =
1728 supported_session_etypes & KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96;
1729 bool add_aes128 =
1730 supported_session_etypes & KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96;
1731 bool add_rc4 =
1732 supported_session_etypes & ENC_RC4_HMAC_MD5;
1733 ret = sdb_entry_set_session_etypes(entry,
1734 add_aes256,
1735 add_aes128,
1736 add_rc4);
1737 if (ret) {
1738 goto out;
1742 if (entry->keys.len != 0) {
1744 * FIXME: Currently limited to Heimdal so as not to
1745 * break MIT KDCs, for which no fix is available.
1747 #ifdef SAMBA4_USES_HEIMDAL
1748 if (is_krbtgt) {
1750 * The krbtgt account, having no reason to
1751 * issue tickets encrypted in weaker keys,
1752 * shall only make available its strongest
1753 * key. All weaker keys are stripped out. This
1754 * makes it impossible for an RC4-encrypted
1755 * TGT to be accepted when AES KDC keys exist.
1757 * This controls the ticket key and so the PAC
1758 * signature algorithms indirectly, preventing
1759 * a weak KDC checksum from being accepted
1760 * when we verify the signatures for an
1761 * S4U2Proxy evidence ticket. As such, this is
1762 * indispensable for addressing
1763 * CVE-2022-37966.
1765 * Being strict here also provides protection
1766 * against possible future attacks on weak
1767 * keys.
1769 entry->keys.len = 1;
1770 if (entry->etypes != NULL) {
1771 entry->etypes->len = MIN(entry->etypes->len, 1);
1773 entry->old_keys.len = MIN(entry->old_keys.len, 1);
1774 entry->older_keys.len = MIN(entry->older_keys.len, 1);
1776 #endif
1777 } else if (kdc_db_ctx->rodc) {
1779 * We are on an RODC, but don't have keys for this
1780 * account. Signal this to the caller
1782 auth_sam_trigger_repl_secret(kdc_db_ctx,
1783 kdc_db_ctx->msg_ctx,
1784 kdc_db_ctx->ev_ctx,
1785 msg->dn);
1786 ret = SDB_ERR_NOT_FOUND_HERE;
1787 goto out;
1788 } else {
1790 * oh, no password. Apparently (comment in
1791 * hdb-ldap.c) this violates the ASN.1, but this
1792 * allows an entry with no keys (yet).
1796 p->msg = talloc_steal(p, msg);
1797 p->supported_enctypes = pa_supported_enctypes;
1799 p->client_policy = talloc_steal(p, authn_client_policy);
1800 p->server_policy = talloc_steal(p, authn_server_policy);
1802 talloc_steal(kdc_db_ctx, p);
1804 out:
1805 if (ret != 0) {
1806 /* This doesn't free ent itself, that is for the eventual caller to do */
1807 sdb_entry_free(entry);
1810 talloc_free(tmp_ctx);
1811 return ret;
1815 * Construct an hdb_entry from a directory entry.
1816 * The kvno is what the remote client asked for
1818 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
1819 struct samba_kdc_db_context *kdc_db_ctx,
1820 TALLOC_CTX *mem_ctx,
1821 enum trust_direction direction,
1822 struct ldb_dn *realm_dn,
1823 unsigned flags,
1824 uint32_t kvno,
1825 struct ldb_message *msg,
1826 struct sdb_entry *entry)
1828 TALLOC_CTX *tmp_ctx = NULL;
1829 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1830 const char *our_realm = lpcfg_realm(lp_ctx);
1831 char *partner_realm = NULL;
1832 const char *realm = NULL;
1833 const char *krbtgt_realm = NULL;
1834 DATA_BLOB password_utf16 = data_blob_null;
1835 DATA_BLOB password_utf8 = data_blob_null;
1836 struct samr_Password _password_hash;
1837 const struct samr_Password *password_hash = NULL;
1838 const struct ldb_val *password_val;
1839 struct trustAuthInOutBlob password_blob;
1840 struct samba_kdc_entry *p;
1841 bool use_previous = false;
1842 uint32_t current_kvno;
1843 uint32_t previous_kvno;
1844 uint32_t num_keys = 0;
1845 enum ndr_err_code ndr_err;
1846 int ret;
1847 unsigned int i;
1848 struct AuthenticationInformationArray *auth_array;
1849 struct timeval tv;
1850 NTTIME an_hour_ago;
1851 uint32_t *auth_kvno;
1852 bool prefer_current = false;
1853 bool force_rc4 = lpcfg_kdc_force_enable_rc4_weak_session_keys(lp_ctx);
1854 uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
1855 uint32_t pa_supported_enctypes;
1856 uint32_t supported_session_etypes;
1857 uint32_t config_kdc_enctypes = lpcfg_kdc_supported_enctypes(lp_ctx);
1858 uint32_t kdc_enctypes =
1859 config_kdc_enctypes != 0 ?
1860 config_kdc_enctypes :
1861 ENC_ALL_TYPES;
1862 struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
1863 NTSTATUS status;
1865 *entry = (struct sdb_entry) {};
1867 tmp_ctx = talloc_new(mem_ctx);
1868 if (tmp_ctx == NULL) {
1869 return ENOMEM;
1872 if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1873 /* If not told otherwise, Windows now assumes that trusts support AES. */
1874 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
1875 "msDS-SupportedEncryptionTypes",
1876 ENC_HMAC_SHA1_96_AES256);
1879 pa_supported_enctypes = supported_enctypes;
1880 supported_session_etypes = supported_enctypes;
1881 if (supported_session_etypes & ENC_HMAC_SHA1_96_AES256_SK) {
1882 supported_session_etypes |= ENC_HMAC_SHA1_96_AES256;
1883 supported_session_etypes |= ENC_HMAC_SHA1_96_AES128;
1885 if (force_rc4) {
1886 supported_session_etypes |= ENC_RC4_HMAC_MD5;
1889 * now that we remembered what to announce in pa_supported_enctypes
1890 * and normalized ENC_HMAC_SHA1_96_AES256_SK, we restrict the
1891 * rest to the enc types the local kdc supports.
1893 supported_enctypes &= kdc_enctypes;
1894 supported_session_etypes &= kdc_enctypes;
1896 status = dsdb_trust_parse_tdo_info(tmp_ctx, msg, &tdo);
1897 if (!NT_STATUS_IS_OK(status)) {
1898 krb5_clear_error_message(context);
1899 ret = ENOMEM;
1900 goto out;
1903 if (!(tdo->trust_direction & direction)) {
1904 krb5_clear_error_message(context);
1905 ret = SDB_ERR_NOENTRY;
1906 goto out;
1909 if (tdo->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
1911 * Only UPLEVEL domains support kerberos here,
1912 * as we don't support LSA_TRUST_TYPE_MIT.
1914 krb5_clear_error_message(context);
1915 ret = SDB_ERR_NOENTRY;
1916 goto out;
1919 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_CROSS_ORGANIZATION) {
1921 * We don't support selective authentication yet.
1923 krb5_clear_error_message(context);
1924 ret = SDB_ERR_NOENTRY;
1925 goto out;
1928 if (tdo->domain_name.string == NULL) {
1929 krb5_clear_error_message(context);
1930 ret = SDB_ERR_NOENTRY;
1931 goto out;
1933 partner_realm = strupper_talloc(tmp_ctx, tdo->domain_name.string);
1934 if (partner_realm == NULL) {
1935 krb5_clear_error_message(context);
1936 ret = ENOMEM;
1937 goto out;
1940 if (direction == INBOUND) {
1941 realm = our_realm;
1942 krbtgt_realm = partner_realm;
1944 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
1945 } else { /* OUTBOUND */
1946 realm = partner_realm;
1947 krbtgt_realm = our_realm;
1949 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
1952 if (password_val == NULL) {
1953 krb5_clear_error_message(context);
1954 ret = SDB_ERR_NOENTRY;
1955 goto out;
1958 ndr_err = ndr_pull_struct_blob(password_val, tmp_ctx, &password_blob,
1959 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1960 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1961 krb5_clear_error_message(context);
1962 ret = EINVAL;
1963 goto out;
1966 p = talloc_zero(tmp_ctx, struct samba_kdc_entry);
1967 if (!p) {
1968 ret = ENOMEM;
1969 goto out;
1972 p->is_trust = true;
1973 p->kdc_db_ctx = kdc_db_ctx;
1974 p->realm_dn = realm_dn;
1975 p->supported_enctypes = pa_supported_enctypes;
1977 talloc_set_destructor(p, samba_kdc_entry_destructor);
1979 entry->skdc_entry = p;
1981 /* use 'whenCreated' */
1982 entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1983 /* use 'kadmin' for now (needed by mit_samba) */
1984 ret = smb_krb5_make_principal(context,
1985 &entry->created_by.principal,
1986 realm, "kadmin", NULL);
1987 if (ret) {
1988 krb5_clear_error_message(context);
1989 goto out;
1993 * We always need to generate the canonicalized principal
1994 * with the values of our database.
1996 ret = smb_krb5_make_principal(context, &entry->principal, realm,
1997 "krbtgt", krbtgt_realm, NULL);
1998 if (ret) {
1999 krb5_clear_error_message(context);
2000 goto out;
2002 smb_krb5_principal_set_type(context, entry->principal,
2003 KRB5_NT_SRV_INST);
2005 entry->valid_start = NULL;
2007 /* we need to work out if we are going to use the current or
2008 * the previous password hash.
2009 * We base this on the kvno the client passes in. If the kvno
2010 * passed in is equal to the current kvno in our database then
2011 * we use the current structure. If it is the current kvno-1,
2012 * then we use the previous substructure.
2016 * Windows prefers the previous key for one hour.
2018 tv = timeval_current();
2019 if (tv.tv_sec > 3600) {
2020 tv.tv_sec -= 3600;
2022 an_hour_ago = timeval_to_nttime(&tv);
2024 /* first work out the current kvno */
2025 current_kvno = 0;
2026 for (i=0; i < password_blob.count; i++) {
2027 struct AuthenticationInformation *a =
2028 &password_blob.current.array[i];
2030 if (a->LastUpdateTime <= an_hour_ago) {
2031 prefer_current = true;
2034 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
2035 current_kvno = a->AuthInfo.version.version;
2038 if (current_kvno == 0) {
2039 previous_kvno = 255;
2040 } else {
2041 previous_kvno = current_kvno - 1;
2043 for (i=0; i < password_blob.count; i++) {
2044 struct AuthenticationInformation *a =
2045 &password_blob.previous.array[i];
2047 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
2048 previous_kvno = a->AuthInfo.version.version;
2052 /* work out whether we will use the previous or current
2053 password */
2054 if (password_blob.previous.count == 0) {
2055 /* there is no previous password */
2056 use_previous = false;
2057 } else if (!(flags & SDB_F_KVNO_SPECIFIED)) {
2059 * If not specified we use the lowest kvno
2060 * for the first hour after an update.
2062 if (prefer_current) {
2063 use_previous = false;
2064 } else if (previous_kvno < current_kvno) {
2065 use_previous = true;
2066 } else {
2067 use_previous = false;
2069 } else if (kvno == current_kvno) {
2071 * Exact match ...
2073 use_previous = false;
2074 } else if (kvno == previous_kvno) {
2076 * Exact match ...
2078 use_previous = true;
2079 } else {
2081 * Fallback to the current one for anything else
2083 use_previous = false;
2086 if (use_previous) {
2087 auth_array = &password_blob.previous;
2088 auth_kvno = &previous_kvno;
2089 } else {
2090 auth_array = &password_blob.current;
2091 auth_kvno = &current_kvno;
2094 /* use the kvno the client specified, if available */
2095 if (flags & SDB_F_KVNO_SPECIFIED) {
2096 entry->kvno = kvno;
2097 } else {
2098 entry->kvno = *auth_kvno;
2101 for (i=0; i < auth_array->count; i++) {
2102 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2103 bool ok;
2105 password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
2106 auth_array->array[i].AuthInfo.clear.size);
2107 if (password_utf16.length == 0) {
2108 break;
2111 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
2112 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
2113 if (password_hash == NULL) {
2114 num_keys += 1;
2116 password_hash = &_password_hash;
2119 if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
2120 break;
2123 ok = convert_string_talloc(tmp_ctx,
2124 CH_UTF16MUNGED, CH_UTF8,
2125 password_utf16.data,
2126 password_utf16.length,
2127 &password_utf8.data,
2128 &password_utf8.length);
2129 if (!ok) {
2130 krb5_clear_error_message(context);
2131 ret = ENOMEM;
2132 goto out;
2135 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
2136 num_keys += 1;
2138 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
2139 num_keys += 1;
2141 break;
2142 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
2143 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
2144 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
2145 num_keys += 1;
2150 /* Must have found a cleartext or MD4 password */
2151 if (num_keys == 0) {
2152 DBG_WARNING("no usable key found\n");
2153 krb5_clear_error_message(context);
2154 ret = SDB_ERR_NOENTRY;
2155 goto out;
2158 entry->keys.val = calloc(num_keys, sizeof(struct sdb_key));
2159 if (entry->keys.val == NULL) {
2160 krb5_clear_error_message(context);
2161 ret = ENOMEM;
2162 goto out;
2165 if (password_utf8.length != 0) {
2166 struct sdb_key key = {};
2167 krb5_const_principal salt_principal = entry->principal;
2168 krb5_data salt;
2169 krb5_data cleartext_data;
2171 cleartext_data.data = discard_const_p(char, password_utf8.data);
2172 cleartext_data.length = password_utf8.length;
2174 ret = smb_krb5_get_pw_salt(context,
2175 salt_principal,
2176 &salt);
2177 if (ret != 0) {
2178 goto out;
2181 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
2182 ret = smb_krb5_create_key_from_string(context,
2183 salt_principal,
2184 &salt,
2185 &cleartext_data,
2186 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
2187 &key.key);
2188 if (ret != 0) {
2189 smb_krb5_free_data_contents(context, &salt);
2190 goto out;
2193 entry->keys.val[entry->keys.len] = key;
2194 entry->keys.len++;
2197 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
2198 ret = smb_krb5_create_key_from_string(context,
2199 salt_principal,
2200 &salt,
2201 &cleartext_data,
2202 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
2203 &key.key);
2204 if (ret != 0) {
2205 smb_krb5_free_data_contents(context, &salt);
2206 goto out;
2209 entry->keys.val[entry->keys.len] = key;
2210 entry->keys.len++;
2213 smb_krb5_free_data_contents(context, &salt);
2216 if (password_hash != NULL) {
2217 struct sdb_key key = {};
2219 ret = smb_krb5_keyblock_init_contents(context,
2220 ENCTYPE_ARCFOUR_HMAC,
2221 password_hash->hash,
2222 sizeof(password_hash->hash),
2223 &key.key);
2224 if (ret != 0) {
2225 goto out;
2228 entry->keys.val[entry->keys.len] = key;
2229 entry->keys.len++;
2232 entry->flags = (struct SDBFlags) {};
2233 entry->flags.immutable = 1;
2234 entry->flags.invalid = 0;
2235 entry->flags.server = 1;
2236 entry->flags.require_preauth = 1;
2238 entry->pw_end = NULL;
2240 entry->max_life = NULL;
2242 entry->max_renew = NULL;
2244 /* Match Windows behavior and allow forwardable flag in cross-realm. */
2245 entry->flags.forwardable = 1;
2247 samba_kdc_sort_keys(&entry->keys);
2249 ret = sdb_entry_set_etypes(entry);
2250 if (ret) {
2251 goto out;
2255 bool add_aes256 =
2256 supported_session_etypes & KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96;
2257 bool add_aes128 =
2258 supported_session_etypes & KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96;
2259 bool add_rc4 =
2260 supported_session_etypes & ENC_RC4_HMAC_MD5;
2261 ret = sdb_entry_set_session_etypes(entry,
2262 add_aes256,
2263 add_aes128,
2264 add_rc4);
2265 if (ret) {
2266 goto out;
2270 p->msg = talloc_steal(p, msg);
2272 talloc_steal(kdc_db_ctx, p);
2274 out:
2275 TALLOC_FREE(partner_realm);
2277 if (ret != 0) {
2278 /* This doesn't free ent itself, that is for the eventual caller to do */
2279 sdb_entry_free(entry);
2282 talloc_free(tmp_ctx);
2283 return ret;
2287 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
2288 TALLOC_CTX *mem_ctx,
2289 const char *realm,
2290 struct ldb_dn *realm_dn,
2291 struct ldb_message **pmsg)
2293 NTSTATUS status;
2294 const char * const *attrs = trust_attrs;
2296 status = dsdb_trust_search_tdo(ldb_ctx, realm, realm,
2297 attrs, mem_ctx, pmsg);
2298 if (NT_STATUS_IS_OK(status)) {
2299 return 0;
2300 } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2301 return SDB_ERR_NOENTRY;
2302 } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
2303 int ret = ENOMEM;
2304 krb5_set_error_message(context, ret, "samba_kdc_lookup_trust: out of memory");
2305 return ret;
2306 } else {
2307 int ret = EINVAL;
2308 krb5_set_error_message(context, ret, "samba_kdc_lookup_trust: %s", nt_errstr(status));
2309 return ret;
2313 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
2314 struct samba_kdc_db_context *kdc_db_ctx,
2315 TALLOC_CTX *mem_ctx,
2316 krb5_const_principal principal,
2317 const char **attrs,
2318 const uint32_t dsdb_flags,
2319 struct ldb_dn **realm_dn,
2320 struct ldb_message **msg)
2322 NTSTATUS nt_status;
2323 char *principal_string = NULL;
2325 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2326 krb5_error_code ret = 0;
2328 ret = smb_krb5_principal_get_comp_string(mem_ctx, context,
2329 principal, 0, &principal_string);
2330 if (ret) {
2331 return ret;
2333 } else {
2334 char *principal_string_m = NULL;
2335 krb5_error_code ret;
2337 ret = krb5_unparse_name(context, principal, &principal_string_m);
2338 if (ret != 0) {
2339 return ret;
2342 principal_string = talloc_strdup(mem_ctx, principal_string_m);
2343 SAFE_FREE(principal_string_m);
2344 if (principal_string == NULL) {
2345 return ENOMEM;
2349 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
2350 mem_ctx, principal_string, attrs, dsdb_flags,
2351 realm_dn, msg);
2352 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
2353 krb5_principal fallback_principal = NULL;
2354 unsigned int num_comp;
2355 char *fallback_realm = NULL;
2356 char *fallback_account = NULL;
2357 krb5_error_code ret;
2359 ret = krb5_parse_name(context, principal_string,
2360 &fallback_principal);
2361 TALLOC_FREE(principal_string);
2362 if (ret != 0) {
2363 return ret;
2366 num_comp = krb5_princ_size(context, fallback_principal);
2367 fallback_realm = smb_krb5_principal_get_realm(
2368 mem_ctx, context, fallback_principal);
2369 if (fallback_realm == NULL) {
2370 krb5_free_principal(context, fallback_principal);
2371 return ENOMEM;
2374 if (num_comp == 1) {
2375 size_t len;
2377 ret = smb_krb5_principal_get_comp_string(mem_ctx,
2378 context, fallback_principal, 0, &fallback_account);
2379 if (ret) {
2380 krb5_free_principal(context, fallback_principal);
2381 TALLOC_FREE(fallback_realm);
2382 return ret;
2385 len = strlen(fallback_account);
2386 if (len >= 2 && fallback_account[len - 1] == '$') {
2387 TALLOC_FREE(fallback_account);
2390 krb5_free_principal(context, fallback_principal);
2391 fallback_principal = NULL;
2393 if (fallback_account != NULL) {
2394 char *with_dollar;
2396 with_dollar = talloc_asprintf(mem_ctx, "%s$",
2397 fallback_account);
2398 if (with_dollar == NULL) {
2399 TALLOC_FREE(fallback_realm);
2400 return ENOMEM;
2402 TALLOC_FREE(fallback_account);
2404 ret = smb_krb5_make_principal(context,
2405 &fallback_principal,
2406 fallback_realm,
2407 with_dollar, NULL);
2408 TALLOC_FREE(with_dollar);
2409 if (ret != 0) {
2410 TALLOC_FREE(fallback_realm);
2411 return ret;
2414 TALLOC_FREE(fallback_realm);
2416 if (fallback_principal != NULL) {
2417 char *fallback_string = NULL;
2419 ret = krb5_unparse_name(context,
2420 fallback_principal,
2421 &fallback_string);
2422 if (ret != 0) {
2423 krb5_free_principal(context, fallback_principal);
2424 return ret;
2427 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
2428 mem_ctx,
2429 fallback_string,
2430 attrs, dsdb_flags,
2431 realm_dn, msg);
2432 SAFE_FREE(fallback_string);
2434 krb5_free_principal(context, fallback_principal);
2435 fallback_principal = NULL;
2437 TALLOC_FREE(principal_string);
2439 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
2440 return SDB_ERR_NOENTRY;
2441 } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
2442 return ENOMEM;
2443 } else if (!NT_STATUS_IS_OK(nt_status)) {
2444 return EINVAL;
2447 return 0;
2450 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
2451 struct samba_kdc_db_context *kdc_db_ctx,
2452 TALLOC_CTX *mem_ctx,
2453 krb5_const_principal principal,
2454 unsigned flags,
2455 krb5_kvno kvno,
2456 struct sdb_entry *entry)
2458 struct ldb_dn *realm_dn;
2459 krb5_error_code ret;
2460 struct ldb_message *msg = NULL;
2462 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2463 mem_ctx, principal, user_attrs, DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
2464 &realm_dn, &msg);
2465 if (ret != 0) {
2466 return ret;
2469 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2470 principal, SAMBA_KDC_ENT_TYPE_CLIENT,
2471 flags, kvno,
2472 realm_dn, msg, entry);
2473 return ret;
2476 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
2477 struct samba_kdc_db_context *kdc_db_ctx,
2478 TALLOC_CTX *mem_ctx,
2479 krb5_const_principal principal,
2480 unsigned flags,
2481 uint32_t kvno,
2482 struct sdb_entry *entry)
2484 TALLOC_CTX *tmp_ctx = NULL;
2485 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
2486 krb5_error_code ret = 0;
2487 int is_krbtgt;
2488 struct ldb_message *msg = NULL;
2489 struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2490 char *realm_from_princ;
2491 char *realm_princ_comp = NULL;
2493 tmp_ctx = talloc_new(mem_ctx);
2494 if (tmp_ctx == NULL) {
2495 ret = ENOMEM;
2496 goto out;
2499 realm_from_princ = smb_krb5_principal_get_realm(
2500 tmp_ctx, context, principal);
2501 if (realm_from_princ == NULL) {
2502 /* can't happen */
2503 ret = SDB_ERR_NOENTRY;
2504 goto out;
2507 is_krbtgt = smb_krb5_principal_is_tgs(context, principal);
2508 if (is_krbtgt == -1) {
2509 ret = ENOMEM;
2510 goto out;
2511 } else if (!is_krbtgt) {
2512 /* Not a krbtgt */
2513 ret = SDB_ERR_NOENTRY;
2514 goto out;
2517 /* krbtgt case. Either us or a trusted realm */
2519 ret = smb_krb5_principal_get_comp_string(tmp_ctx, context, principal, 1, &realm_princ_comp);
2520 if (ret == ENOENT) {
2521 /* OK. */
2522 } else if (ret) {
2523 goto out;
2526 if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
2527 && (realm_princ_comp == NULL || lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp))) {
2528 /* us, or someone quite like us */
2529 /* Kludge, kludge, kludge. If the realm part of krbtgt/realm,
2530 * is in our db, then direct the caller at our primary
2531 * krbtgt */
2533 int lret;
2534 unsigned int krbtgt_number;
2535 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
2536 trust tickets. We don't yet know what this means, but we do
2537 seem to need to treat it as unspecified */
2538 if (flags & (SDB_F_KVNO_SPECIFIED|SDB_F_RODC_NUMBER_SPECIFIED)) {
2539 krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
2540 if (kdc_db_ctx->rodc) {
2541 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
2542 ret = SDB_ERR_NOT_FOUND_HERE;
2543 goto out;
2546 } else {
2547 krbtgt_number = kdc_db_ctx->my_krbtgt_number;
2550 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
2551 lret = dsdb_search_one(kdc_db_ctx->samdb, tmp_ctx,
2552 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
2553 krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
2554 "(objectClass=user)");
2555 } else {
2556 /* We need to look up an RODC krbtgt (perhaps
2557 * ours, if we are an RODC, perhaps another
2558 * RODC if we are a read-write DC */
2559 lret = dsdb_search_one(kdc_db_ctx->samdb, tmp_ctx,
2560 &msg, realm_dn, LDB_SCOPE_SUBTREE,
2561 krbtgt_attrs,
2562 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
2563 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
2566 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2567 krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2568 (unsigned)(krbtgt_number));
2569 krb5_set_error_message(context, SDB_ERR_NOENTRY,
2570 "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2571 (unsigned)(krbtgt_number));
2572 ret = SDB_ERR_NOENTRY;
2573 goto out;
2574 } else if (lret != LDB_SUCCESS) {
2575 krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2576 (unsigned)(krbtgt_number));
2577 krb5_set_error_message(context, SDB_ERR_NOENTRY,
2578 "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2579 (unsigned)(krbtgt_number));
2580 ret = SDB_ERR_NOENTRY;
2581 goto out;
2584 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2585 principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
2586 flags, kvno, realm_dn, msg, entry);
2587 if (ret != 0) {
2588 krb5_warnx(context, "samba_kdc_fetch_krbtgt: self krbtgt message2entry failed");
2590 } else {
2591 enum trust_direction direction = UNKNOWN;
2592 const char *realm = NULL;
2594 /* Either an inbound or outbound trust */
2596 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
2597 /* look for inbound trust */
2598 direction = INBOUND;
2599 realm = realm_princ_comp;
2600 } else {
2601 bool eq = false;
2603 ret = is_principal_component_equal_ignoring_case(context, principal, 1, lpcfg_realm(lp_ctx), &eq);
2604 if (ret) {
2605 goto out;
2608 if (eq) {
2609 /* look for outbound trust */
2610 direction = OUTBOUND;
2611 realm = realm_from_princ;
2612 } else {
2613 krb5_warnx(context, "samba_kdc_fetch_krbtgt: not our realm for trusts ('%s', '%s')",
2614 realm_from_princ,
2615 realm_princ_comp);
2616 krb5_set_error_message(context, SDB_ERR_NOENTRY, "samba_kdc_fetch_krbtgt: not our realm for trusts ('%s', '%s')",
2617 realm_from_princ,
2618 realm_princ_comp);
2619 ret = SDB_ERR_NOENTRY;
2620 goto out;
2624 /* Trusted domains are under CN=system */
2626 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
2627 tmp_ctx,
2628 realm, realm_dn, &msg);
2630 if (ret != 0) {
2631 krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find principal in DB");
2632 krb5_set_error_message(context, ret, "samba_kdc_fetch_krbtgt: could not find principal in DB");
2633 goto out;
2636 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
2637 direction,
2638 realm_dn, flags, kvno, msg, entry);
2639 if (ret != 0) {
2640 krb5_warnx(context, "samba_kdc_fetch_krbtgt: trust_message2entry failed for %s",
2641 ldb_dn_get_linearized(msg->dn));
2642 krb5_set_error_message(context, ret, "samba_kdc_fetch_krbtgt: "
2643 "trust_message2entry failed for %s",
2644 ldb_dn_get_linearized(msg->dn));
2648 out:
2649 talloc_free(tmp_ctx);
2650 return ret;
2653 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
2654 struct samba_kdc_db_context *kdc_db_ctx,
2655 TALLOC_CTX *mem_ctx,
2656 krb5_const_principal principal,
2657 unsigned flags,
2658 struct ldb_dn **realm_dn,
2659 struct ldb_message **msg)
2661 krb5_error_code ret;
2662 if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
2663 && krb5_princ_size(context, principal) >= 2) {
2664 /* 'normal server' case */
2665 int ldb_ret;
2666 NTSTATUS nt_status;
2667 struct ldb_dn *user_dn;
2668 char *principal_string;
2670 ret = krb5_unparse_name_flags(context, principal,
2671 KRB5_PRINCIPAL_UNPARSE_NO_REALM,
2672 &principal_string);
2673 if (ret != 0) {
2674 return ret;
2677 /* At this point we may find the host is known to be
2678 * in a different realm, so we should generate a
2679 * referral instead */
2680 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
2681 mem_ctx, principal_string,
2682 &user_dn, realm_dn);
2683 free(principal_string);
2685 if (!NT_STATUS_IS_OK(nt_status)) {
2686 return SDB_ERR_NOENTRY;
2689 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
2690 mem_ctx,
2691 msg, user_dn, LDB_SCOPE_BASE,
2692 server_attrs,
2693 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
2694 "(objectClass=*)");
2695 if (ldb_ret != LDB_SUCCESS) {
2696 return SDB_ERR_NOENTRY;
2698 return 0;
2699 } else if (!(flags & SDB_F_FOR_AS_REQ)
2700 && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2702 * The behaviour of accepting an
2703 * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
2704 * containing a UPN only applies to TGS-REQ packets,
2705 * not AS-REQ packets.
2707 return samba_kdc_lookup_client(context, kdc_db_ctx,
2708 mem_ctx, principal, server_attrs, DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
2709 realm_dn, msg);
2710 } else {
2712 * This case is for:
2713 * - the AS-REQ, where we only accept
2714 * samAccountName based lookups for the server, no
2715 * matter if the name is an
2716 * KRB5_NT_ENTERPRISE_PRINCIPAL or not
2717 * - for the TGS-REQ when we are not given an
2718 * KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
2719 * only lookup samAccountName based names.
2721 int lret;
2722 char *short_princ;
2723 krb5_principal enterprise_principal = NULL;
2724 krb5_const_principal used_principal = NULL;
2725 char *name1 = NULL;
2726 size_t len1 = 0;
2727 char *filter = NULL;
2729 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2730 char *str = NULL;
2731 /* Need to reparse the enterprise principal to find the real target */
2732 if (krb5_princ_size(context, principal) != 1) {
2733 ret = KRB5_PARSE_MALFORMED;
2734 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
2735 "enterprise principal with wrong (%d) number of components",
2736 krb5_princ_size(context, principal));
2737 return ret;
2739 ret = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0, &str);
2740 if (ret) {
2741 return KRB5_PARSE_MALFORMED;
2743 ret = krb5_parse_name(context, str,
2744 &enterprise_principal);
2745 talloc_free(str);
2746 if (ret) {
2747 return ret;
2749 used_principal = enterprise_principal;
2750 } else {
2751 used_principal = principal;
2754 /* server as client principal case, but we must not lookup userPrincipalNames */
2755 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2757 /* TODO: Check if it is our realm, otherwise give referral */
2759 ret = krb5_unparse_name_flags(context, used_principal,
2760 KRB5_PRINCIPAL_UNPARSE_NO_REALM |
2761 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2762 &short_princ);
2763 used_principal = NULL;
2764 krb5_free_principal(context, enterprise_principal);
2765 enterprise_principal = NULL;
2767 if (ret != 0) {
2768 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: could not parse principal");
2769 krb5_warnx(context, "samba_kdc_lookup_server: could not parse principal");
2770 return ret;
2773 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
2774 SAFE_FREE(short_princ);
2775 if (name1 == NULL) {
2776 return ENOMEM;
2778 len1 = strlen(name1);
2779 if (len1 >= 1 && name1[len1 - 1] != '$') {
2780 filter = talloc_asprintf(mem_ctx,
2781 "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
2782 name1, name1);
2783 if (filter == NULL) {
2784 return ENOMEM;
2786 } else {
2787 filter = talloc_asprintf(mem_ctx,
2788 "(&(objectClass=user)(samAccountName=%s))",
2789 name1);
2790 if (filter == NULL) {
2791 return ENOMEM;
2795 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
2796 *realm_dn, LDB_SCOPE_SUBTREE,
2797 server_attrs,
2798 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
2799 "%s", filter);
2800 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2801 DBG_DEBUG("Failed to find an entry for %s filter:%s\n",
2802 name1, filter);
2803 return SDB_ERR_NOENTRY;
2805 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
2806 DBG_DEBUG("Failed to find unique entry for %s filter:%s\n",
2807 name1, filter);
2808 return SDB_ERR_NOENTRY;
2810 if (lret != LDB_SUCCESS) {
2811 DBG_ERR("Failed single search for %s - %s\n",
2812 name1, ldb_errstring(kdc_db_ctx->samdb));
2813 return SDB_ERR_NOENTRY;
2815 return 0;
2817 return SDB_ERR_NOENTRY;
2822 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
2823 struct samba_kdc_db_context *kdc_db_ctx,
2824 TALLOC_CTX *mem_ctx,
2825 krb5_const_principal principal,
2826 unsigned flags,
2827 krb5_kvno kvno,
2828 struct sdb_entry *entry)
2830 krb5_error_code ret;
2831 struct ldb_dn *realm_dn;
2832 struct ldb_message *msg;
2834 ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
2835 flags, &realm_dn, &msg);
2836 if (ret != 0) {
2837 return ret;
2840 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2841 principal, SAMBA_KDC_ENT_TYPE_SERVER,
2842 flags, kvno,
2843 realm_dn, msg, entry);
2844 if (ret != 0) {
2845 char *client_name = NULL;
2846 krb5_error_code code;
2848 code = krb5_unparse_name(context, principal, &client_name);
2849 if (code == 0) {
2850 krb5_warnx(context,
2851 "samba_kdc_fetch_server: message2entry failed for "
2852 "%s",
2853 client_name);
2854 } else {
2855 krb5_warnx(context,
2856 "samba_kdc_fetch_server: message2entry and "
2857 "krb5_unparse_name failed");
2859 SAFE_FREE(client_name);
2862 return ret;
2865 static krb5_error_code samba_kdc_lookup_realm(krb5_context context,
2866 struct samba_kdc_db_context *kdc_db_ctx,
2867 krb5_const_principal principal,
2868 unsigned flags,
2869 struct sdb_entry *entry)
2871 TALLOC_CTX *frame = talloc_stackframe();
2872 NTSTATUS status;
2873 krb5_error_code ret;
2874 bool check_realm = false;
2875 const char *realm = NULL;
2876 struct dsdb_trust_routing_table *trt = NULL;
2877 const struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
2878 unsigned int num_comp;
2879 bool ok;
2880 char *upper = NULL;
2882 *entry = (struct sdb_entry) {};
2884 num_comp = krb5_princ_size(context, principal);
2886 if (flags & SDB_F_GET_CLIENT) {
2887 if (flags & SDB_F_FOR_AS_REQ) {
2888 check_realm = true;
2891 if (flags & SDB_F_GET_SERVER) {
2892 if (flags & SDB_F_FOR_TGS_REQ) {
2893 check_realm = true;
2897 if (!check_realm) {
2898 TALLOC_FREE(frame);
2899 return 0;
2902 realm = smb_krb5_principal_get_realm(frame, context, principal);
2903 if (realm == NULL) {
2904 TALLOC_FREE(frame);
2905 return ENOMEM;
2909 * The requested realm needs to be our own
2911 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2912 if (!ok) {
2914 * The request is not for us...
2916 TALLOC_FREE(frame);
2917 return SDB_ERR_NOENTRY;
2920 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2921 char *principal_string = NULL;
2922 krb5_principal enterprise_principal = NULL;
2923 char *enterprise_realm = NULL;
2925 if (num_comp != 1) {
2926 TALLOC_FREE(frame);
2927 return SDB_ERR_NOENTRY;
2930 ret = smb_krb5_principal_get_comp_string(frame, context,
2931 principal, 0, &principal_string);
2932 if (ret) {
2933 TALLOC_FREE(frame);
2934 return ret;
2937 ret = krb5_parse_name(context, principal_string,
2938 &enterprise_principal);
2939 TALLOC_FREE(principal_string);
2940 if (ret) {
2941 TALLOC_FREE(frame);
2942 return ret;
2945 enterprise_realm = smb_krb5_principal_get_realm(
2946 frame, context, enterprise_principal);
2947 krb5_free_principal(context, enterprise_principal);
2948 if (enterprise_realm != NULL) {
2949 realm = enterprise_realm;
2953 if (flags & SDB_F_GET_SERVER) {
2954 bool is_krbtgt = false;
2956 ret = is_principal_component_equal(context, principal, 0, KRB5_TGS_NAME, &is_krbtgt);
2957 if (ret) {
2958 TALLOC_FREE(frame);
2959 return ret;
2962 if (is_krbtgt) {
2964 * we need to search krbtgt/ locally
2966 TALLOC_FREE(frame);
2967 return 0;
2971 * We need to check the last component against the routing table.
2973 * Note this works only with 2 or 3 component principals, e.g:
2975 * servicePrincipalName: ldap/W2K8R2-219.bla.base
2976 * servicePrincipalName: ldap/W2K8R2-219.bla.base/bla.base
2977 * servicePrincipalName: ldap/W2K8R2-219.bla.base/ForestDnsZones.bla.base
2978 * servicePrincipalName: ldap/W2K8R2-219.bla.base/DomainDnsZones.bla.base
2981 if (num_comp == 2 || num_comp == 3) {
2982 char *service_realm = NULL;
2984 ret = smb_krb5_principal_get_comp_string(frame,
2985 context,
2986 principal,
2987 num_comp - 1,
2988 &service_realm);
2989 if (ret) {
2990 TALLOC_FREE(frame);
2991 return ret;
2992 } else {
2993 realm = service_realm;
2998 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2999 if (ok) {
3001 * skip the expensive routing lookup
3003 TALLOC_FREE(frame);
3004 return 0;
3007 status = dsdb_trust_routing_table_load(kdc_db_ctx->samdb,
3008 frame, &trt);
3009 if (!NT_STATUS_IS_OK(status)) {
3010 TALLOC_FREE(frame);
3011 return EINVAL;
3014 tdo = dsdb_trust_routing_by_name(trt, realm);
3015 if (tdo == NULL) {
3017 * This principal has to be local
3019 TALLOC_FREE(frame);
3020 return 0;
3023 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
3025 * TODO: handle the routing within the forest
3027 * This should likely be handled in
3028 * samba_kdc_message2entry() in case we're
3029 * a global catalog. We'd need to check
3030 * if realm_dn is our own domain and derive
3031 * the dns domain name from realm_dn and check that
3032 * against the routing table or fallback to
3033 * the tdo we found here.
3035 * But for now we don't support multiple domains
3036 * in our forest correctly anyway.
3038 * Just search in our local database.
3040 TALLOC_FREE(frame);
3041 return 0;
3044 ret = krb5_copy_principal(context, principal,
3045 &entry->principal);
3046 if (ret) {
3047 TALLOC_FREE(frame);
3048 return ret;
3051 upper = strupper_talloc(frame, tdo->domain_name.string);
3052 if (upper == NULL) {
3053 TALLOC_FREE(frame);
3054 return ENOMEM;
3057 ret = smb_krb5_principal_set_realm(context,
3058 entry->principal,
3059 upper);
3060 if (ret) {
3061 TALLOC_FREE(frame);
3062 return ret;
3065 TALLOC_FREE(frame);
3066 return SDB_ERR_WRONG_REALM;
3069 krb5_error_code samba_kdc_fetch(krb5_context context,
3070 struct samba_kdc_db_context *kdc_db_ctx,
3071 krb5_const_principal principal,
3072 unsigned flags,
3073 krb5_kvno kvno,
3074 struct sdb_entry *entry)
3076 krb5_error_code ret = SDB_ERR_NOENTRY;
3077 TALLOC_CTX *mem_ctx;
3079 mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
3080 if (!mem_ctx) {
3081 ret = ENOMEM;
3082 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
3083 return ret;
3086 ret = samba_kdc_lookup_realm(context, kdc_db_ctx,
3087 principal, flags, entry);
3088 if (ret != 0) {
3089 goto done;
3092 ret = SDB_ERR_NOENTRY;
3094 if (flags & SDB_F_GET_CLIENT) {
3095 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
3096 if (ret != SDB_ERR_NOENTRY) goto done;
3098 if (flags & SDB_F_GET_SERVER) {
3099 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
3100 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
3101 if (ret != SDB_ERR_NOENTRY) goto done;
3103 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
3104 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
3105 if (ret != SDB_ERR_NOENTRY) goto done;
3107 if (flags & SDB_F_GET_KRBTGT) {
3108 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
3109 if (ret != SDB_ERR_NOENTRY) goto done;
3112 done:
3113 talloc_free(mem_ctx);
3114 return ret;
3117 struct samba_kdc_seq {
3118 unsigned int index;
3119 unsigned int count;
3120 struct ldb_message **msgs;
3121 struct ldb_dn *realm_dn;
3124 static krb5_error_code samba_kdc_seq(krb5_context context,
3125 struct samba_kdc_db_context *kdc_db_ctx,
3126 struct sdb_entry *entry)
3128 krb5_error_code ret;
3129 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
3130 const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
3131 struct ldb_message *msg = NULL;
3132 const char *sAMAccountName = NULL;
3133 krb5_principal principal = NULL;
3134 TALLOC_CTX *mem_ctx;
3136 if (!priv) {
3137 return SDB_ERR_NOENTRY;
3140 mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
3142 if (!mem_ctx) {
3143 ret = ENOMEM;
3144 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
3145 goto out;
3148 while (priv->index < priv->count) {
3149 msg = priv->msgs[priv->index++];
3151 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
3152 if (sAMAccountName != NULL) {
3153 break;
3157 if (sAMAccountName == NULL) {
3158 ret = SDB_ERR_NOENTRY;
3159 goto out;
3162 ret = smb_krb5_make_principal(context, &principal,
3163 realm, sAMAccountName, NULL);
3164 if (ret != 0) {
3165 goto out;
3168 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
3169 principal, SAMBA_KDC_ENT_TYPE_ANY,
3170 SDB_F_ADMIN_DATA|SDB_F_GET_ANY,
3171 0 /* kvno */,
3172 priv->realm_dn, msg, entry);
3173 krb5_free_principal(context, principal);
3175 out:
3176 if (ret != 0) {
3177 TALLOC_FREE(priv);
3178 kdc_db_ctx->seq_ctx = NULL;
3179 } else {
3180 talloc_free(mem_ctx);
3183 return ret;
3186 krb5_error_code samba_kdc_firstkey(krb5_context context,
3187 struct samba_kdc_db_context *kdc_db_ctx,
3188 struct sdb_entry *entry)
3190 struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
3191 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
3192 char *realm;
3193 struct ldb_result *res = NULL;
3194 krb5_error_code ret;
3195 int lret;
3197 if (priv) {
3198 TALLOC_FREE(priv);
3199 kdc_db_ctx->seq_ctx = NULL;
3202 priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
3203 if (!priv) {
3204 ret = ENOMEM;
3205 krb5_set_error_message(context, ret, "talloc: out of memory");
3206 return ret;
3209 priv->index = 0;
3210 priv->msgs = NULL;
3211 priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
3212 priv->count = 0;
3214 ret = krb5_get_default_realm(context, &realm);
3215 if (ret != 0) {
3216 TALLOC_FREE(priv);
3217 return ret;
3219 krb5_free_default_realm(context, realm);
3221 lret = dsdb_search(ldb_ctx, priv, &res,
3222 priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
3223 DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
3224 "(objectClass=user)");
3226 if (lret != LDB_SUCCESS) {
3227 TALLOC_FREE(priv);
3228 return SDB_ERR_NOENTRY;
3231 priv->count = res->count;
3232 priv->msgs = talloc_steal(priv, res->msgs);
3233 talloc_free(res);
3235 kdc_db_ctx->seq_ctx = priv;
3237 ret = samba_kdc_seq(context, kdc_db_ctx, entry);
3239 if (ret != 0) {
3240 TALLOC_FREE(priv);
3241 kdc_db_ctx->seq_ctx = NULL;
3243 return ret;
3246 krb5_error_code samba_kdc_nextkey(krb5_context context,
3247 struct samba_kdc_db_context *kdc_db_ctx,
3248 struct sdb_entry *entry)
3250 return samba_kdc_seq(context, kdc_db_ctx, entry);
3253 /* Check if a given entry may delegate or do s4u2self to this target principal
3255 * The safest way to determine 'self' is to check the DB record made at
3256 * the time the principal was presented to the KDC.
3258 krb5_error_code
3259 samba_kdc_check_client_matches_target_service(krb5_context context,
3260 struct samba_kdc_entry *skdc_entry_client,
3261 struct samba_kdc_entry *skdc_entry_server_target)
3263 struct dom_sid *orig_sid;
3264 struct dom_sid *target_sid;
3265 TALLOC_CTX *frame = talloc_stackframe();
3267 orig_sid = samdb_result_dom_sid(frame,
3268 skdc_entry_client->msg,
3269 "objectSid");
3270 target_sid = samdb_result_dom_sid(frame,
3271 skdc_entry_server_target->msg,
3272 "objectSid");
3275 * Allow delegation to the same record (representing a
3276 * principal), even if by a different name. The easy and safe
3277 * way to prove this is by SID comparison
3279 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
3280 talloc_free(frame);
3281 return KRB5KRB_AP_ERR_BADMATCH;
3284 talloc_free(frame);
3285 return 0;
3288 /* Certificates printed by the Certificate Authority might have a
3289 * slightly different form of the user principal name to that in the
3290 * database. Allow a mismatch where they both refer to the same
3291 * SID */
3293 krb5_error_code
3294 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
3295 struct samba_kdc_db_context *kdc_db_ctx,
3296 struct samba_kdc_entry *skdc_entry,
3297 krb5_const_principal certificate_principal)
3299 krb5_error_code ret;
3300 struct ldb_dn *realm_dn;
3301 struct ldb_message *msg;
3302 struct dom_sid *orig_sid;
3303 struct dom_sid *target_sid;
3304 const char *ms_upn_check_attrs[] = {
3305 "objectSid", NULL
3308 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
3310 if (!mem_ctx) {
3311 ret = ENOMEM;
3312 krb5_set_error_message(context, ret, "samba_kdc_check_pkinit_ms_upn_match: talloc_named() failed!");
3313 return ret;
3316 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
3317 mem_ctx, certificate_principal,
3318 ms_upn_check_attrs, 0, &realm_dn, &msg);
3320 if (ret != 0) {
3321 talloc_free(mem_ctx);
3322 return ret;
3325 orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
3326 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
3328 /* Consider these to be the same principal, even if by a different
3329 * name. The easy and safe way to prove this is by SID
3330 * comparison */
3331 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
3332 talloc_free(mem_ctx);
3333 #if defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
3334 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
3335 #else /* Heimdal (where this is an enum) */
3336 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
3337 #endif
3340 talloc_free(mem_ctx);
3341 return ret;
3345 * Check if a given entry may delegate to this target principal
3346 * with S4U2Proxy.
3348 krb5_error_code
3349 samba_kdc_check_s4u2proxy(krb5_context context,
3350 struct samba_kdc_db_context *kdc_db_ctx,
3351 struct samba_kdc_entry *skdc_entry,
3352 krb5_const_principal target_principal)
3354 krb5_error_code ret;
3355 char *tmp = NULL;
3356 const char *client_dn = NULL;
3357 const char *target_principal_name = NULL;
3358 struct ldb_message_element *el;
3359 struct ldb_val val;
3360 unsigned int i;
3361 bool found = false;
3363 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
3365 if (!mem_ctx) {
3366 ret = ENOMEM;
3367 krb5_set_error_message(context, ret,
3368 "samba_kdc_check_s4u2proxy:"
3369 " talloc_named() failed!");
3370 return ret;
3373 client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
3374 if (!client_dn) {
3375 if (errno == 0) {
3376 errno = ENOMEM;
3378 ret = errno;
3379 krb5_set_error_message(context, ret,
3380 "samba_kdc_check_s4u2proxy:"
3381 " ldb_dn_get_linearized() failed!");
3382 talloc_free(mem_ctx);
3383 return ret;
3386 el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
3387 if (el == NULL) {
3388 ret = ENOENT;
3389 goto bad_option;
3391 SMB_ASSERT(el->num_values != 0);
3394 * This is the Microsoft forwardable flag behavior.
3396 * If the proxy (target) principal is NULL, and we have any authorized
3397 * delegation target, allow to forward.
3399 if (target_principal == NULL) {
3400 talloc_free(mem_ctx);
3401 return 0;
3406 * The main heimdal code already checked that the target_principal
3407 * belongs to the same realm as the client.
3409 * So we just need the principal without the realm,
3410 * as that is what is configured in the "msDS-AllowedToDelegateTo"
3411 * attribute.
3413 ret = krb5_unparse_name_flags(context, target_principal,
3414 KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
3415 if (ret) {
3416 talloc_free(mem_ctx);
3417 krb5_set_error_message(context, ret,
3418 "samba_kdc_check_s4u2proxy:"
3419 " krb5_unparse_name_flags() failed!");
3420 return ret;
3422 DBG_DEBUG("client[%s] for target[%s]\n",
3423 client_dn, tmp);
3425 target_principal_name = talloc_strdup(mem_ctx, tmp);
3426 SAFE_FREE(tmp);
3427 if (target_principal_name == NULL) {
3428 ret = ENOMEM;
3429 krb5_set_error_message(context, ret,
3430 "samba_kdc_check_s4u2proxy:"
3431 " talloc_strdup() failed!");
3432 talloc_free(mem_ctx);
3433 return ret;
3436 val = data_blob_string_const(target_principal_name);
3438 for (i=0; i<el->num_values; i++) {
3439 struct ldb_val *val1 = &val;
3440 struct ldb_val *val2 = &el->values[i];
3441 int cmp;
3443 if (val1->length != val2->length) {
3444 continue;
3447 cmp = strncasecmp((const char *)val1->data,
3448 (const char *)val2->data,
3449 val1->length);
3450 if (cmp != 0) {
3451 continue;
3454 found = true;
3455 break;
3458 if (!found) {
3459 ret = ENOENT;
3460 goto bad_option;
3463 DBG_DEBUG("client[%s] allowed target[%s]\n",
3464 client_dn, target_principal_name);
3465 talloc_free(mem_ctx);
3466 return 0;
3468 bad_option:
3469 krb5_set_error_message(context, ret,
3470 "samba_kdc_check_s4u2proxy: client[%s] "
3471 "not allowed for delegation to target[%s]",
3472 client_dn,
3473 target_principal_name);
3474 talloc_free(mem_ctx);
3475 return KRB5KDC_ERR_BADOPTION;
3479 * This method is called for S4U2Proxy requests and implements the
3480 * resource-based constrained delegation variant, which can support
3481 * cross-realm delegation.
3483 krb5_error_code samba_kdc_check_s4u2proxy_rbcd(
3484 krb5_context context,
3485 struct samba_kdc_db_context *kdc_db_ctx,
3486 krb5_const_principal client_principal,
3487 krb5_const_principal server_principal,
3488 const struct auth_user_info_dc *user_info_dc,
3489 const struct auth_user_info_dc *device_info_dc,
3490 const struct auth_claims auth_claims,
3491 struct samba_kdc_entry *proxy_skdc_entry)
3493 krb5_error_code code;
3494 enum ndr_err_code ndr_err;
3495 char *client_name = NULL;
3496 char *server_name = NULL;
3497 const char *proxy_dn = NULL;
3498 const DATA_BLOB *data = NULL;
3499 struct security_descriptor *rbcd_security_descriptor = NULL;
3500 struct security_token *security_token = NULL;
3501 uint32_t session_info_flags =
3502 AUTH_SESSION_INFO_DEFAULT_GROUPS |
3503 AUTH_SESSION_INFO_DEVICE_DEFAULT_GROUPS |
3504 AUTH_SESSION_INFO_SIMPLE_PRIVILEGES |
3505 AUTH_SESSION_INFO_FORCE_COMPOUNDED_AUTHENTICATION;
3507 * Testing shows that although Windows grants SEC_ADS_GENERIC_ALL access
3508 * in security descriptors it creates for RBCD, its KDC only requires
3509 * SEC_ADS_CONTROL_ACCESS for the access check to succeed.
3511 uint32_t access_desired = SEC_ADS_CONTROL_ACCESS;
3512 uint32_t access_granted = 0;
3513 NTSTATUS nt_status;
3514 TALLOC_CTX *mem_ctx = NULL;
3516 mem_ctx = talloc_named(kdc_db_ctx,
3518 "samba_kdc_check_s4u2proxy_rbcd");
3519 if (mem_ctx == NULL) {
3520 errno = ENOMEM;
3521 code = errno;
3523 return code;
3526 proxy_dn = ldb_dn_get_linearized(proxy_skdc_entry->msg->dn);
3527 if (proxy_dn == NULL) {
3528 DBG_ERR("ldb_dn_get_linearized failed for proxy_dn!\n");
3529 if (errno == 0) {
3530 errno = ENOMEM;
3532 code = errno;
3534 goto out;
3537 rbcd_security_descriptor = talloc_zero(mem_ctx,
3538 struct security_descriptor);
3539 if (rbcd_security_descriptor == NULL) {
3540 errno = ENOMEM;
3541 code = errno;
3543 goto out;
3546 code = krb5_unparse_name_flags(context,
3547 client_principal,
3548 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
3549 &client_name);
3550 if (code != 0) {
3551 DBG_ERR("Unable to parse client_principal!\n");
3552 goto out;
3555 code = krb5_unparse_name_flags(context,
3556 server_principal,
3557 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
3558 &server_name);
3559 if (code != 0) {
3560 DBG_ERR("Unable to parse server_principal!\n");
3561 goto out;
3564 DBG_INFO("Check delegation from client[%s] to server[%s] via "
3565 "proxy[%s]\n",
3566 client_name,
3567 server_name,
3568 proxy_dn);
3570 if (!(user_info_dc->info->user_flags & NETLOGON_GUEST)) {
3571 session_info_flags |= AUTH_SESSION_INFO_AUTHENTICATED;
3574 if (device_info_dc != NULL && !(device_info_dc->info->user_flags & NETLOGON_GUEST)) {
3575 session_info_flags |= AUTH_SESSION_INFO_DEVICE_AUTHENTICATED;
3578 nt_status = auth_generate_security_token(mem_ctx,
3579 kdc_db_ctx->lp_ctx,
3580 kdc_db_ctx->samdb,
3581 user_info_dc,
3582 device_info_dc,
3583 auth_claims,
3584 session_info_flags,
3585 &security_token);
3586 if (!NT_STATUS_IS_OK(nt_status)) {
3587 code = map_errno_from_nt_status(nt_status);
3588 goto out;
3591 data = ldb_msg_find_ldb_val(proxy_skdc_entry->msg,
3592 "msDS-AllowedToActOnBehalfOfOtherIdentity");
3593 if (data == NULL) {
3594 DBG_WARNING("Could not find security descriptor "
3595 "msDS-AllowedToActOnBehalfOfOtherIdentity in "
3596 "proxy[%s]\n",
3597 proxy_dn);
3598 code = KRB5KDC_ERR_BADOPTION;
3599 goto out;
3602 ndr_err = ndr_pull_struct_blob(
3603 data,
3604 mem_ctx,
3605 rbcd_security_descriptor,
3606 (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
3607 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3608 errno = ndr_map_error2errno(ndr_err);
3609 DBG_ERR("Failed to unmarshall "
3610 "msDS-AllowedToActOnBehalfOfOtherIdentity "
3611 "security descriptor of proxy[%s]\n",
3612 proxy_dn);
3613 code = KRB5KDC_ERR_BADOPTION;
3614 goto out;
3617 if (DEBUGLEVEL >= 10) {
3618 NDR_PRINT_DEBUG(security_token, security_token);
3619 NDR_PRINT_DEBUG(security_descriptor, rbcd_security_descriptor);
3622 nt_status = sec_access_check_ds(rbcd_security_descriptor,
3623 security_token,
3624 access_desired,
3625 &access_granted,
3626 NULL,
3627 NULL);
3629 if (!NT_STATUS_IS_OK(nt_status)) {
3630 DBG_WARNING("RBCD: sec_access_check_ds(access_desired=%#08x, "
3631 "access_granted:%#08x) failed with: %s\n",
3632 access_desired,
3633 access_granted,
3634 nt_errstr(nt_status));
3636 code = KRB5KDC_ERR_BADOPTION;
3637 goto out;
3640 DBG_NOTICE("RBCD: Access granted for client[%s]\n", client_name);
3642 code = 0;
3643 out:
3644 SAFE_FREE(client_name);
3645 SAFE_FREE(server_name);
3647 TALLOC_FREE(mem_ctx);
3648 return code;
3651 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
3652 struct samba_kdc_db_context **kdc_db_ctx_out)
3654 int ldb_ret;
3655 struct ldb_message *msg = NULL;
3656 struct samba_kdc_db_context *kdc_db_ctx = NULL;
3657 /* The idea here is very simple. Using Kerberos to
3658 * authenticate the KDC to the LDAP server is highly likely to
3659 * be circular.
3661 * In future we may set this up to use EXTERNAL and SSL
3662 * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
3665 kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
3666 if (kdc_db_ctx == NULL) {
3667 return NT_STATUS_NO_MEMORY;
3669 kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
3670 kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
3671 kdc_db_ctx->msg_ctx = base_ctx->msg_ctx;
3673 /* get default kdc policy */
3674 lpcfg_default_kdc_policy(mem_ctx,
3675 base_ctx->lp_ctx,
3676 &kdc_db_ctx->policy.svc_tkt_lifetime,
3677 &kdc_db_ctx->policy.usr_tkt_lifetime,
3678 &kdc_db_ctx->policy.renewal_lifetime);
3680 /* This is to allow "samba-tool domain exportkeytab to take a -H */
3681 if (base_ctx->samdb != NULL) {
3683 * Caller is responsible for lifetimes. In reality
3684 * the whole thing is destroyed before leaving the
3685 * function the samdb was passed into
3687 kdc_db_ctx->samdb = base_ctx->samdb;
3688 } else {
3689 struct auth_session_info *session_info = NULL;
3690 session_info = system_session(kdc_db_ctx->lp_ctx);
3691 if (session_info == NULL) {
3692 talloc_free(kdc_db_ctx);
3693 return NT_STATUS_INTERNAL_ERROR;
3696 /* Setup the link to LDB */
3697 kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx,
3698 base_ctx->ev_ctx,
3699 base_ctx->lp_ctx,
3700 session_info,
3701 NULL,
3703 if (kdc_db_ctx->samdb == NULL) {
3704 DBG_WARNING("Cannot open samdb for KDC backend!\n");
3705 talloc_free(kdc_db_ctx);
3706 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3710 /* Find out our own krbtgt kvno */
3711 ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
3712 if (ldb_ret != LDB_SUCCESS) {
3713 DBG_WARNING("Cannot determine if we are an RODC in KDC backend: %s\n",
3714 ldb_errstring(kdc_db_ctx->samdb));
3715 talloc_free(kdc_db_ctx);
3716 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3718 if (kdc_db_ctx->rodc) {
3719 int my_krbtgt_number;
3720 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
3721 struct ldb_dn *account_dn = NULL;
3722 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
3723 if (!server_dn) {
3724 DBG_WARNING("Cannot determine server DN in KDC backend: %s\n",
3725 ldb_errstring(kdc_db_ctx->samdb));
3726 talloc_free(kdc_db_ctx);
3727 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3730 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
3731 "serverReference", &account_dn);
3732 if (ldb_ret != LDB_SUCCESS) {
3733 DBG_WARNING("Cannot determine server account in KDC backend: %s\n",
3734 ldb_errstring(kdc_db_ctx->samdb));
3735 talloc_free(kdc_db_ctx);
3736 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3739 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
3740 "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
3741 talloc_free(account_dn);
3742 if (ldb_ret != LDB_SUCCESS) {
3743 DBG_WARNING("Cannot determine RODC krbtgt account in KDC backend: %s\n",
3744 ldb_errstring(kdc_db_ctx->samdb));
3745 talloc_free(kdc_db_ctx);
3746 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3749 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3750 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
3751 secondary_keytab,
3752 DSDB_SEARCH_NO_GLOBAL_CATALOG,
3753 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
3754 if (ldb_ret != LDB_SUCCESS) {
3755 DBG_WARNING("Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
3756 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3757 ldb_errstring(kdc_db_ctx->samdb),
3758 ldb_strerror(ldb_ret));
3759 talloc_free(kdc_db_ctx);
3760 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3762 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
3763 if (my_krbtgt_number == -1) {
3764 DBG_WARNING("Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
3765 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3766 my_krbtgt_number);
3767 talloc_free(kdc_db_ctx);
3768 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3770 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
3772 } else {
3773 kdc_db_ctx->my_krbtgt_number = 0;
3774 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3775 &msg,
3776 ldb_get_default_basedn(kdc_db_ctx->samdb),
3777 LDB_SCOPE_SUBTREE,
3778 krbtgt_attrs,
3779 DSDB_SEARCH_NO_GLOBAL_CATALOG | DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS,
3780 "(&(objectClass=user)(samAccountName=krbtgt))");
3782 if (ldb_ret != LDB_SUCCESS) {
3783 DBG_WARNING("could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb));
3784 talloc_free(kdc_db_ctx);
3785 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3787 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
3788 kdc_db_ctx->my_krbtgt_number = 0;
3789 talloc_free(msg);
3791 *kdc_db_ctx_out = kdc_db_ctx;
3792 return NT_STATUS_OK;
3795 krb5_error_code dsdb_extract_aes_256_key(krb5_context context,
3796 TALLOC_CTX *mem_ctx,
3797 struct ldb_context *ldb,
3798 const struct ldb_message *msg,
3799 uint32_t user_account_control,
3800 const uint32_t *kvno,
3801 uint32_t *kvno_out,
3802 DATA_BLOB *aes_256_key,
3803 DATA_BLOB *salt)
3805 krb5_error_code krb5_ret;
3806 uint32_t supported_enctypes;
3807 unsigned flags = SDB_F_GET_CLIENT;
3808 struct sdb_entry sentry = {};
3810 if (kvno != NULL) {
3811 flags |= SDB_F_KVNO_SPECIFIED;
3814 krb5_ret = samba_kdc_message2entry_keys(context,
3815 mem_ctx,
3816 ldb,
3817 msg,
3818 false, /* is_krbtgt */
3819 false, /* is_rodc */
3820 user_account_control,
3821 SAMBA_KDC_ENT_TYPE_CLIENT,
3822 flags,
3823 (kvno != NULL) ? *kvno : 0,
3824 &sentry,
3825 ENC_HMAC_SHA1_96_AES256,
3826 &supported_enctypes);
3827 if (krb5_ret != 0) {
3828 const char *krb5_err = krb5_get_error_message(context, krb5_ret);
3830 DBG_ERR("Failed to parse supplementalCredentials "
3831 "of %s with %s kvno using "
3832 "ENCTYPE_HMAC_SHA1_96_AES256 "
3833 "Kerberos Key: %s\n",
3834 ldb_dn_get_linearized(msg->dn),
3835 (kvno != NULL) ? "previous" : "current",
3836 krb5_err != NULL ? krb5_err : "<unknown>");
3838 krb5_free_error_message(context, krb5_err);
3840 return krb5_ret;
3843 if ((supported_enctypes & ENC_HMAC_SHA1_96_AES256) == 0 ||
3844 sentry.keys.len != 1) {
3845 DBG_INFO("Failed to find a ENCTYPE_HMAC_SHA1_96_AES256 "
3846 "key in supplementalCredentials "
3847 "of %s at KVNO %u (got %u keys, expected 1)\n",
3848 ldb_dn_get_linearized(msg->dn),
3849 sentry.kvno,
3850 sentry.keys.len);
3851 sdb_entry_free(&sentry);
3852 return ENOENT;
3855 if (sentry.keys.val[0].salt == NULL) {
3856 DBG_INFO("Failed to find a salt in "
3857 "supplementalCredentials "
3858 "of %s at KVNO %u\n",
3859 ldb_dn_get_linearized(msg->dn),
3860 sentry.kvno);
3861 sdb_entry_free(&sentry);
3862 return ENOENT;
3865 if (aes_256_key != NULL) {
3866 *aes_256_key = data_blob_talloc(mem_ctx,
3867 KRB5_KEY_DATA(&sentry.keys.val[0].key),
3868 KRB5_KEY_LENGTH(&sentry.keys.val[0].key));
3869 if (aes_256_key->data == NULL) {
3870 sdb_entry_free(&sentry);
3871 return ENOMEM;
3873 talloc_keep_secret(aes_256_key->data);
3876 if (salt != NULL) {
3877 *salt = data_blob_talloc(mem_ctx,
3878 sentry.keys.val[0].salt->salt.data,
3879 sentry.keys.val[0].salt->salt.length);
3880 if (salt->data == NULL) {
3881 sdb_entry_free(&sentry);
3882 return ENOMEM;
3886 if (kvno_out != NULL) {
3887 *kvno_out = sentry.kvno;
3890 sdb_entry_free(&sentry);
3892 return 0;