ctdbd_conn: Add deregister_from_ctdbd()
[Samba.git] / source4 / kdc / db-glue.c
bloba55f66e94c7f04434b5a82aefcef54460d448eaa
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 DEBUG(1,(__location__ ": 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);
113 * This seem to rely on the current IRPC implementation,
114 * which delivers the message in the _send function.
116 * TODO: we need a ONE_WAY IRPC handle and register
117 * a callback and wait for it to be triggered!
119 req = dcerpc_drepl_trigger_repl_secret_r_send(tmp_ctx,
120 event_ctx,
121 irpc_handle,
122 &r);
124 /* we aren't interested in a reply */
125 talloc_free(req);
126 TALLOC_FREE(tmp_ctx);
129 static time_t ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, time_t default_val)
131 const char *tmp;
132 const char *gentime;
133 struct tm tm;
135 gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
136 if (!gentime)
137 return default_val;
139 tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
140 if (tmp == NULL) {
141 return default_val;
144 return timegm(&tm);
147 static struct SDBFlags uf2SDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
149 struct SDBFlags flags = int2SDBFlags(0);
151 /* we don't allow kadmin deletes */
152 flags.immutable = 1;
154 /* mark the principal as invalid to start with */
155 flags.invalid = 1;
157 flags.renewable = 1;
159 /* All accounts are servers, but this may be disabled again in the caller */
160 flags.server = 1;
162 /* Account types - clear the invalid bit if it turns out to be valid */
163 if (userAccountControl & UF_NORMAL_ACCOUNT) {
164 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
165 flags.client = 1;
167 flags.invalid = 0;
170 if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
171 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
172 flags.client = 1;
174 flags.invalid = 0;
176 if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
177 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
178 flags.client = 1;
180 flags.invalid = 0;
182 if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
183 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
184 flags.client = 1;
186 flags.invalid = 0;
189 /* Not permitted to act as a client if disabled */
190 if (userAccountControl & UF_ACCOUNTDISABLE) {
191 flags.client = 0;
193 if (userAccountControl & UF_LOCKOUT) {
194 flags.locked_out = 1;
197 if (userAccountControl & UF_PASSWD_NOTREQD) {
198 flags.invalid = 1;
202 UF_PASSWD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevant
204 if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
205 flags.invalid = 1;
208 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
211 if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
212 flags.invalid = 1;
215 if (userAccountControl & UF_SMARTCARD_REQUIRED) {
216 flags.require_hwauth = 1;
218 if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
219 flags.ok_as_delegate = 1;
221 if (userAccountControl & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
223 * this is confusing...
225 * UF_TRUSTED_FOR_DELEGATION
226 * => ok_as_delegate
228 * and
230 * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
231 * => trusted_for_delegation
233 flags.trusted_for_delegation = 1;
235 if (!(userAccountControl & UF_NOT_DELEGATED)) {
236 flags.forwardable = 1;
237 flags.proxiable = 1;
240 if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
241 flags.require_preauth = 0;
242 } else {
243 flags.require_preauth = 1;
246 if (userAccountControl & UF_NO_AUTH_DATA_REQUIRED) {
247 flags.no_auth_data_reqd = 1;
250 return flags;
253 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
255 if (p->db_entry != NULL) {
257 * A sdb_entry still has a reference
259 return -1;
262 if (p->kdc_entry != NULL) {
264 * hdb_entry or krb5_db_entry still
265 * have a reference...
267 return -1;
270 return 0;
274 * Sort keys in descending order of strength.
276 * Explanaton from Greg Hudson:
278 * To encrypt tickets only the first returned key is used by the MIT KDC. The
279 * other keys just communicate support for session key enctypes, and aren't
280 * really used. The encryption key for the ticket enc part doesn't have
281 * to be of a type requested by the client. The session key enctype is chosen
282 * based on the client preference order, limited by the set of enctypes present
283 * in the server keys (unless the string attribute is set on the server
284 * principal overriding that set).
287 static int sdb_key_strength_priority(krb5_enctype etype)
289 static const krb5_enctype etype_list[] = {
290 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
291 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
292 ENCTYPE_DES3_CBC_SHA1,
293 ENCTYPE_ARCFOUR_HMAC,
294 ENCTYPE_DES_CBC_MD5,
295 ENCTYPE_DES_CBC_MD4,
296 ENCTYPE_DES_CBC_CRC,
297 ENCTYPE_NULL
299 int i;
301 for (i = 0; i < ARRAY_SIZE(etype_list); i++) {
302 if (etype == etype_list[i]) {
303 break;
307 return ARRAY_SIZE(etype_list) - i;
310 static int sdb_key_strength_cmp(const struct sdb_key *k1, const struct sdb_key *k2)
312 int p1 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k1->key));
313 int p2 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k2->key));
315 if (p1 == p2) {
316 return 0;
319 if (p1 > p2) {
321 * Higher priority comes first
323 return -1;
324 } else {
325 return 1;
329 static void samba_kdc_sort_keys(struct sdb_keys *keys)
331 if (keys == NULL) {
332 return;
335 TYPESAFE_QSORT(keys->val, keys->len, sdb_key_strength_cmp);
338 int samba_kdc_set_fixed_keys(krb5_context context,
339 const struct ldb_val *secretbuffer,
340 uint32_t supported_enctypes,
341 struct sdb_keys *keys)
343 uint16_t allocated_keys = 0;
344 int ret;
346 allocated_keys = 3;
347 keys->len = 0;
348 keys->val = calloc(allocated_keys, sizeof(struct sdb_key));
349 if (keys->val == NULL) {
350 memset(secretbuffer->data, 0, secretbuffer->length);
351 ret = ENOMEM;
352 goto out;
355 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
356 struct sdb_key key = {};
358 ret = smb_krb5_keyblock_init_contents(context,
359 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
360 secretbuffer->data,
361 MIN(secretbuffer->length, 32),
362 &key.key);
363 if (ret) {
364 memset(secretbuffer->data, 0, secretbuffer->length);
365 goto out;
368 keys->val[keys->len] = key;
369 keys->len++;
372 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
373 struct sdb_key key = {};
375 ret = smb_krb5_keyblock_init_contents(context,
376 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
377 secretbuffer->data,
378 MIN(secretbuffer->length, 16),
379 &key.key);
380 if (ret) {
381 memset(secretbuffer->data, 0, secretbuffer->length);
382 goto out;
385 keys->val[keys->len] = key;
386 keys->len++;
389 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
390 struct sdb_key key = {};
392 ret = smb_krb5_keyblock_init_contents(context,
393 ENCTYPE_ARCFOUR_HMAC,
394 secretbuffer->data,
395 MIN(secretbuffer->length, 16),
396 &key.key);
397 if (ret) {
398 memset(secretbuffer->data, 0, secretbuffer->length);
399 goto out;
402 keys->val[keys->len] = key;
403 keys->len++;
405 ret = 0;
406 out:
407 return ret;
411 static int samba_kdc_set_random_keys(krb5_context context,
412 uint32_t supported_enctypes,
413 struct sdb_keys *keys)
415 struct ldb_val secret_val;
416 uint8_t secretbuffer[32];
419 * Fake keys until we have a better way to reject
420 * non-pkinit requests.
422 * We just need to indicate which encryption types are
423 * supported.
425 generate_secret_buffer(secretbuffer, sizeof(secretbuffer));
427 secret_val = data_blob_const(secretbuffer,
428 sizeof(secretbuffer));
429 return samba_kdc_set_fixed_keys(context,
430 &secret_val,
431 supported_enctypes,
432 keys);
435 struct samba_kdc_user_keys {
436 struct sdb_keys *skeys;
437 uint32_t kvno;
438 uint32_t *returned_kvno;
439 uint32_t supported_enctypes;
440 uint32_t *available_enctypes;
441 const struct samr_Password *nthash;
442 const char *salt_string;
443 uint16_t num_pkeys;
444 const struct package_PrimaryKerberosKey4 *pkeys;
447 static krb5_error_code samba_kdc_fill_user_keys(krb5_context context,
448 struct samba_kdc_user_keys *p)
451 * Make sure we'll never reveal DES keys
453 uint32_t supported_enctypes = p->supported_enctypes &= ~(ENC_CRC32 | ENC_RSA_MD5);
454 uint32_t _available_enctypes = 0;
455 uint32_t *available_enctypes = p->available_enctypes;
456 uint32_t _returned_kvno = 0;
457 uint32_t *returned_kvno = p->returned_kvno;
458 uint32_t num_pkeys = p->num_pkeys;
459 uint32_t allocated_keys = num_pkeys;
460 uint32_t i;
461 int ret;
463 if (available_enctypes == NULL) {
464 available_enctypes = &_available_enctypes;
467 *available_enctypes = 0;
469 if (returned_kvno == NULL) {
470 returned_kvno = &_returned_kvno;
473 *returned_kvno = p->kvno;
475 if (p->nthash != NULL) {
476 allocated_keys += 1;
479 allocated_keys = MAX(1, allocated_keys);
481 /* allocate space to decode into */
482 p->skeys->len = 0;
483 p->skeys->val = calloc(allocated_keys, sizeof(struct sdb_key));
484 if (p->skeys->val == NULL) {
485 return ENOMEM;
488 for (i=0; i < num_pkeys; i++) {
489 struct sdb_key key = {};
490 uint32_t enctype_bit;
492 if (p->pkeys[i].value == NULL) {
493 continue;
496 enctype_bit = kerberos_enctype_to_bitmap(p->pkeys[i].keytype);
497 if (!(enctype_bit & supported_enctypes)) {
498 continue;
501 if (p->salt_string != NULL) {
502 DATA_BLOB salt;
504 salt = data_blob_string_const(p->salt_string);
506 key.salt = calloc(1, sizeof(*key.salt));
507 if (key.salt == NULL) {
508 ret = ENOMEM;
509 goto fail;
512 key.salt->type = KRB5_PW_SALT;
514 ret = smb_krb5_copy_data_contents(&key.salt->salt,
515 salt.data,
516 salt.length);
517 if (ret) {
518 ZERO_STRUCTP(key.salt);
519 sdb_key_free(&key);
520 goto fail;
524 ret = smb_krb5_keyblock_init_contents(context,
525 p->pkeys[i].keytype,
526 p->pkeys[i].value->data,
527 p->pkeys[i].value->length,
528 &key.key);
529 if (ret == 0) {
530 p->skeys->val[p->skeys->len++] = key;
531 *available_enctypes |= enctype_bit;
532 continue;
534 ZERO_STRUCT(key.key);
535 sdb_key_free(&key);
536 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
537 DEBUG(2,("Unsupported keytype ignored - type %u\n",
538 p->pkeys[i].keytype));
539 ret = 0;
540 continue;
543 goto fail;
546 if (p->nthash != NULL && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
547 struct sdb_key key = {};
549 ret = smb_krb5_keyblock_init_contents(context,
550 ENCTYPE_ARCFOUR_HMAC,
551 p->nthash->hash,
552 sizeof(p->nthash->hash),
553 &key.key);
554 if (ret == 0) {
555 p->skeys->val[p->skeys->len++] = key;
557 *available_enctypes |= ENC_RC4_HMAC_MD5;
558 } else if (ret == KRB5_PROG_ETYPE_NOSUPP) {
559 DEBUG(2,("Unsupported keytype ignored - type %u\n",
560 ENCTYPE_ARCFOUR_HMAC));
561 ret = 0;
563 if (ret != 0) {
564 goto fail;
568 samba_kdc_sort_keys(p->skeys);
570 return 0;
571 fail:
572 sdb_keys_free(p->skeys);
573 return ret;
576 krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
577 TALLOC_CTX *mem_ctx,
578 const struct ldb_message *msg,
579 bool is_krbtgt,
580 bool is_rodc,
581 uint32_t userAccountControl,
582 enum samba_kdc_ent_type ent_type,
583 unsigned flags,
584 krb5_kvno requested_kvno,
585 struct sdb_entry *entry,
586 const uint32_t supported_enctypes_in,
587 uint32_t *supported_enctypes_out)
589 krb5_error_code ret = 0;
590 enum ndr_err_code ndr_err;
591 struct samr_Password *hash;
592 unsigned int num_ntPwdHistory = 0;
593 struct samr_Password *ntPwdHistory = NULL;
594 struct samr_Password *old_hash = NULL;
595 struct samr_Password *older_hash = NULL;
596 const struct ldb_val *sc_val;
597 struct supplementalCredentialsBlob scb;
598 struct supplementalCredentialsPackage *scpk = NULL;
599 struct package_PrimaryKerberosBlob _pkb;
600 struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
601 int krbtgt_number = 0;
602 uint32_t current_kvno;
603 uint32_t old_kvno = 0;
604 uint32_t older_kvno = 0;
605 uint32_t returned_kvno = 0;
606 uint16_t i;
607 struct samba_kdc_user_keys keys = { .num_pkeys = 0, };
608 struct samba_kdc_user_keys old_keys = { .num_pkeys = 0, };
609 struct samba_kdc_user_keys older_keys = { .num_pkeys = 0, };
610 uint32_t available_enctypes = 0;
611 uint32_t supported_enctypes = supported_enctypes_in;
613 *supported_enctypes_out = 0;
615 /* Is this the krbtgt or a RODC krbtgt */
616 if (is_rodc) {
617 krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
619 if (krbtgt_number == -1) {
620 return EINVAL;
622 if (krbtgt_number == 0) {
623 return EINVAL;
627 if (flags & SDB_F_USER2USER_PRINCIPAL) {
629 * User2User uses the session key
630 * from the additional ticket,
631 * so we just provide random keys
632 * here in order to make sure
633 * we never expose the user password
634 * keys.
636 ret = samba_kdc_set_random_keys(context,
637 supported_enctypes,
638 &entry->keys);
640 *supported_enctypes_out = supported_enctypes & ENC_ALL_TYPES;
642 goto out;
645 if ((ent_type == SAMBA_KDC_ENT_TYPE_CLIENT)
646 && (userAccountControl & UF_SMARTCARD_REQUIRED)) {
647 ret = samba_kdc_set_random_keys(context,
648 supported_enctypes,
649 &entry->keys);
651 *supported_enctypes_out = supported_enctypes & ENC_ALL_TYPES;
653 goto out;
656 current_kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
657 if (current_kvno > 1) {
658 old_kvno = current_kvno - 1;
660 if (current_kvno > 2) {
661 older_kvno = current_kvno - 2;
663 if (is_krbtgt) {
665 * Even for the main krbtgt account
666 * we have to strictly split the kvno into
667 * two 16-bit parts and the upper 16-bit
668 * need to be all zero, even if
669 * the msDS-KeyVersionNumber has a value
670 * larger than 65535.
672 * See https://bugzilla.samba.org/show_bug.cgi?id=14951
674 current_kvno = SAMBA_KVNO_GET_VALUE(current_kvno);
675 old_kvno = SAMBA_KVNO_GET_VALUE(old_kvno);
676 older_kvno = SAMBA_KVNO_GET_VALUE(older_kvno);
677 requested_kvno = SAMBA_KVNO_GET_VALUE(requested_kvno);
680 /* Get keys from the db */
682 hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
683 num_ntPwdHistory = samdb_result_hashes(mem_ctx, msg,
684 "ntPwdHistory",
685 &ntPwdHistory);
686 if (num_ntPwdHistory > 1) {
687 old_hash = &ntPwdHistory[1];
689 if (num_ntPwdHistory > 2) {
690 older_hash = &ntPwdHistory[1];
692 sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
694 /* supplementalCredentials if present */
695 if (sc_val) {
696 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
697 (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
698 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
699 dump_data(0, sc_val->data, sc_val->length);
700 ret = EINVAL;
701 goto out;
704 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
705 if (scb.sub.num_packages != 0) {
706 NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
707 ret = EINVAL;
708 goto out;
712 for (i=0; i < scb.sub.num_packages; i++) {
713 if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
714 scpk = &scb.sub.packages[i];
715 if (!scpk->data || !scpk->data[0]) {
716 scpk = NULL;
717 continue;
719 break;
724 * Primary:Kerberos-Newer-Keys element
725 * of supplementalCredentials
727 * The legacy Primary:Kerberos only contains
728 * single DES keys, which are completely ignored
729 * now.
731 if (scpk) {
732 DATA_BLOB blob;
734 blob = strhex_to_data_blob(mem_ctx, scpk->data);
735 if (!blob.data) {
736 ret = ENOMEM;
737 goto out;
740 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
741 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
742 (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
743 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
744 ret = EINVAL;
745 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
746 krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
747 goto out;
750 if (_pkb.version != 4) {
751 ret = EINVAL;
752 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
753 krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
754 goto out;
757 pkb4 = &_pkb.ctr.ctr4;
760 keys = (struct samba_kdc_user_keys) {
761 .kvno = current_kvno,
762 .supported_enctypes = supported_enctypes,
763 .nthash = hash,
764 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
765 .num_pkeys = pkb4 != NULL ? pkb4->num_keys : 0,
766 .pkeys = pkb4 != NULL ? pkb4->keys : NULL,
769 old_keys = (struct samba_kdc_user_keys) {
770 .kvno = old_kvno,
771 .supported_enctypes = supported_enctypes,
772 .nthash = old_hash,
773 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
774 .num_pkeys = pkb4 != NULL ? pkb4->num_old_keys : 0,
775 .pkeys = pkb4 != NULL ? pkb4->old_keys : NULL,
777 older_keys = (struct samba_kdc_user_keys) {
778 .kvno = older_kvno,
779 .supported_enctypes = supported_enctypes,
780 .nthash = older_hash,
781 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
782 .num_pkeys = pkb4 != NULL ? pkb4->num_older_keys : 0,
783 .pkeys = pkb4 != NULL ? pkb4->older_keys : NULL,
786 if (flags & SDB_F_KVNO_SPECIFIED) {
787 if (requested_kvno == keys.kvno) {
789 * The current kvno was requested,
790 * so we return it.
792 keys.skeys = &entry->keys;
793 keys.available_enctypes = &available_enctypes;
794 keys.returned_kvno = &returned_kvno;
795 } else if (requested_kvno == 0) {
797 * don't return any keys
799 } else if (requested_kvno == old_keys.kvno) {
801 * return the old keys as default keys
802 * with the requested kvno.
804 old_keys.skeys = &entry->keys;
805 old_keys.available_enctypes = &available_enctypes;
806 old_keys.returned_kvno = &returned_kvno;
807 } else if (requested_kvno == older_keys.kvno) {
809 * return the older keys as default keys
810 * with the requested kvno.
812 older_keys.skeys = &entry->keys;
813 older_keys.available_enctypes = &available_enctypes;
814 older_keys.returned_kvno = &returned_kvno;
815 } else {
817 * don't return any keys
820 } else {
821 bool include_history = false;
823 if ((flags & SDB_F_GET_CLIENT) && (flags & SDB_F_FOR_AS_REQ)) {
824 include_history = true;
825 } else if (flags & SDB_F_ADMIN_DATA) {
826 include_history = true;
829 keys.skeys = &entry->keys;
830 keys.available_enctypes = &available_enctypes;
831 keys.returned_kvno = &returned_kvno;
833 if (include_history && old_keys.kvno != 0) {
834 old_keys.skeys = &entry->old_keys;
836 if (include_history && older_keys.kvno != 0) {
837 older_keys.skeys = &entry->older_keys;
841 if (keys.skeys != NULL) {
842 ret = samba_kdc_fill_user_keys(context, &keys);
843 if (ret != 0) {
844 goto out;
848 if (old_keys.skeys != NULL) {
849 ret = samba_kdc_fill_user_keys(context, &old_keys);
850 if (ret != 0) {
851 goto out;
855 if (older_keys.skeys != NULL) {
856 ret = samba_kdc_fill_user_keys(context, &older_keys);
857 if (ret != 0) {
858 goto out;
862 *supported_enctypes_out |= available_enctypes;
864 if (is_krbtgt) {
866 * Even for the main krbtgt account
867 * we have to strictly split the kvno into
868 * two 16-bit parts and the upper 16-bit
869 * need to be all zero, even if
870 * the msDS-KeyVersionNumber has a value
871 * larger than 65535.
873 * See https://bugzilla.samba.org/show_bug.cgi?id=14951
875 returned_kvno = SAMBA_KVNO_AND_KRBTGT(returned_kvno, krbtgt_number);
877 entry->kvno = returned_kvno;
879 out:
880 return ret;
883 static int principal_comp_strcmp_int(krb5_context context,
884 krb5_const_principal principal,
885 unsigned int component,
886 const char *string,
887 bool do_strcasecmp)
889 const char *p;
891 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
892 p = krb5_principal_get_comp_string(context, principal, component);
893 if (p == NULL) {
894 return -1;
896 if (do_strcasecmp) {
897 return strcasecmp(p, string);
898 } else {
899 return strcmp(p, string);
901 #else
902 size_t len;
903 krb5_data *d;
904 if (component >= krb5_princ_size(context, principal)) {
905 return -1;
908 d = krb5_princ_component(context, principal, component);
909 if (d == NULL) {
910 return -1;
913 p = d->data;
915 len = strlen(string);
918 * We explicitly return -1 or 1. Subtracting of the two lengths might
919 * give the wrong result if the result overflows or loses data when
920 * narrowed to int.
922 if (d->length < len) {
923 return -1;
924 } else if (d->length > len) {
925 return 1;
928 if (do_strcasecmp) {
929 return strncasecmp(p, string, len);
930 } else {
931 return memcmp(p, string, len);
933 #endif
936 static int principal_comp_strcasecmp(krb5_context context,
937 krb5_const_principal principal,
938 unsigned int component,
939 const char *string)
941 return principal_comp_strcmp_int(context, principal,
942 component, string, true);
945 static int principal_comp_strcmp(krb5_context context,
946 krb5_const_principal principal,
947 unsigned int component,
948 const char *string)
950 return principal_comp_strcmp_int(context, principal,
951 component, string, false);
954 static bool is_kadmin_changepw(krb5_context context,
955 krb5_const_principal principal)
957 return krb5_princ_size(context, principal) == 2 &&
958 (principal_comp_strcmp(context, principal, 0, "kadmin") == 0) &&
959 (principal_comp_strcmp(context, principal, 1, "changepw") == 0);
962 static krb5_error_code samba_kdc_get_entry_principal(
963 krb5_context context,
964 struct samba_kdc_db_context *kdc_db_ctx,
965 const char *samAccountName,
966 enum samba_kdc_ent_type ent_type,
967 unsigned flags,
968 bool is_kadmin_changepw,
969 krb5_const_principal in_princ,
970 krb5_principal *out_princ)
972 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
973 krb5_error_code code = 0;
974 bool canon = flags & (SDB_F_CANON|SDB_F_FORCE_CANON);
977 * If we are set to canonicalize, we get back the fixed UPPER
978 * case realm, and the real username (ie matching LDAP
979 * samAccountName)
981 * Otherwise, if we are set to enterprise, we
982 * get back the whole principal as-sent
984 * Finally, if we are not set to canonicalize, we get back the
985 * fixed UPPER case realm, but the as-sent username
989 * We need to ensure that the kadmin/changepw principal isn't able to
990 * issue krbtgt tickets, even if canonicalization is turned on.
992 if (!is_kadmin_changepw) {
993 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT && canon) {
995 * When requested to do so, ensure that the
996 * both realm values in the principal are set
997 * to the upper case, canonical realm
999 code = smb_krb5_make_principal(context,
1000 out_princ,
1001 lpcfg_realm(lp_ctx),
1002 "krbtgt",
1003 lpcfg_realm(lp_ctx),
1004 NULL);
1005 if (code != 0) {
1006 return code;
1008 smb_krb5_principal_set_type(context,
1009 *out_princ,
1010 KRB5_NT_SRV_INST);
1012 return 0;
1015 if ((canon && flags & (SDB_F_FORCE_CANON|SDB_F_FOR_AS_REQ)) ||
1016 (ent_type == SAMBA_KDC_ENT_TYPE_ANY && in_princ == NULL)) {
1018 * SDB_F_CANON maps from the canonicalize flag in the
1019 * packet, and has a different meaning between AS-REQ
1020 * and TGS-REQ. We only change the principal in the
1021 * AS-REQ case.
1023 * The SDB_F_FORCE_CANON if for new MIT KDC code that
1024 * wants the canonical name in all lookups, and takes
1025 * care to canonicalize only when appropriate.
1027 code = smb_krb5_make_principal(context,
1028 out_princ,
1029 lpcfg_realm(lp_ctx),
1030 samAccountName,
1031 NULL);
1032 return code;
1037 * For a krbtgt entry, this appears to be required regardless of the
1038 * canonicalize flag from the client.
1040 code = krb5_copy_principal(context, in_princ, out_princ);
1041 if (code != 0) {
1042 return code;
1046 * While we have copied the client principal, tests show that Win2k3
1047 * returns the 'corrected' realm, not the client-specified realm. This
1048 * code attempts to replace the client principal's realm with the one
1049 * we determine from our records
1051 code = smb_krb5_principal_set_realm(context,
1052 *out_princ,
1053 lpcfg_realm(lp_ctx));
1055 return code;
1059 * Construct an hdb_entry from a directory entry.
1061 static krb5_error_code samba_kdc_message2entry(krb5_context context,
1062 struct samba_kdc_db_context *kdc_db_ctx,
1063 TALLOC_CTX *mem_ctx,
1064 krb5_const_principal principal,
1065 enum samba_kdc_ent_type ent_type,
1066 unsigned flags,
1067 krb5_kvno kvno,
1068 struct ldb_dn *realm_dn,
1069 struct ldb_message *msg,
1070 struct sdb_entry *entry)
1072 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1073 uint32_t userAccountControl;
1074 uint32_t msDS_User_Account_Control_Computed;
1075 krb5_error_code ret = 0;
1076 krb5_boolean is_computer = FALSE;
1077 struct samba_kdc_entry *p;
1078 NTTIME acct_expiry;
1079 NTSTATUS status;
1080 bool protected_user = false;
1081 uint32_t rid;
1082 bool is_krbtgt = false;
1083 bool is_rodc = false;
1084 bool force_rc4 = lpcfg_kdc_force_enable_rc4_weak_session_keys(lp_ctx);
1085 struct ldb_message_element *objectclasses;
1086 struct ldb_val computer_val = data_blob_string_const("computer");
1087 uint32_t config_default_supported_enctypes = lpcfg_kdc_default_domain_supported_enctypes(lp_ctx);
1088 uint32_t default_supported_enctypes =
1089 config_default_supported_enctypes != 0 ?
1090 config_default_supported_enctypes :
1091 ENC_RC4_HMAC_MD5 | ENC_HMAC_SHA1_96_AES256_SK;
1092 uint32_t supported_enctypes
1093 = ldb_msg_find_attr_as_uint(msg,
1094 "msDS-SupportedEncryptionTypes",
1095 default_supported_enctypes);
1096 uint32_t pa_supported_enctypes;
1097 uint32_t supported_session_etypes;
1098 uint32_t available_enctypes = 0;
1100 * also lagacy enctypes are announced,
1101 * but effectively restricted by kdc_enctypes
1103 uint32_t domain_enctypes = ENC_RC4_HMAC_MD5 | ENC_RSA_MD5 | ENC_CRC32;
1104 uint32_t config_kdc_enctypes = lpcfg_kdc_supported_enctypes(lp_ctx);
1105 uint32_t kdc_enctypes =
1106 config_kdc_enctypes != 0 ?
1107 config_kdc_enctypes :
1108 ENC_ALL_TYPES;
1109 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
1111 const struct authn_kerberos_client_policy *authn_client_policy = NULL;
1112 const struct authn_server_policy *authn_server_policy = NULL;
1113 int64_t enforced_tgt_lifetime_raw;
1114 const bool user2user = (flags & SDB_F_USER2USER_PRINCIPAL);
1116 ZERO_STRUCTP(entry);
1118 if (supported_enctypes == 0) {
1119 supported_enctypes = default_supported_enctypes;
1122 if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1123 domain_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
1126 if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
1127 is_rodc = true;
1130 if (!samAccountName) {
1131 ret = ENOENT;
1132 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
1133 goto out;
1136 objectclasses = ldb_msg_find_element(msg, "objectClass");
1138 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
1139 is_computer = TRUE;
1142 p = talloc_zero(mem_ctx, struct samba_kdc_entry);
1143 if (!p) {
1144 ret = ENOMEM;
1145 goto out;
1148 p->is_rodc = is_rodc;
1149 p->kdc_db_ctx = kdc_db_ctx;
1150 p->realm_dn = talloc_reference(p, realm_dn);
1151 if (!p->realm_dn) {
1152 ret = ENOMEM;
1153 goto out;
1156 talloc_set_destructor(p, samba_kdc_entry_destructor);
1158 entry->skdc_entry = p;
1160 userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
1162 msDS_User_Account_Control_Computed
1163 = ldb_msg_find_attr_as_uint(msg,
1164 "msDS-User-Account-Control-Computed",
1165 UF_ACCOUNTDISABLE);
1168 * This brings in the lockout flag, block the account if not
1169 * found. We need the weird UF_ACCOUNTDISABLE check because
1170 * we do not want to fail open if the value is not returned,
1171 * but 0 is a valid value (all OK)
1173 if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
1174 ret = EINVAL;
1175 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
1176 "no msDS-User-Account-Control-Computed present");
1177 goto out;
1178 } else {
1179 userAccountControl |= msDS_User_Account_Control_Computed;
1182 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
1183 p->is_krbtgt = true;
1186 /* First try and figure out the flags based on the userAccountControl */
1187 entry->flags = uf2SDBFlags(context, userAccountControl, ent_type);
1190 * Take control of the returned principal here, rather than
1191 * allowing the Heimdal code to do it as we have specific
1192 * behaviour around the forced realm to honour
1194 entry->flags.force_canonicalize = true;
1197 * Windows 2008 seems to enforce this (very sensible) rule by
1198 * default - don't allow offline attacks on a user's password
1199 * by asking for a ticket to them as a service (encrypted with
1200 * their probably pathetically insecure password)
1202 * But user2user avoids using the keys bases on the password,
1203 * so we can allow it.
1206 if (entry->flags.server && !user2user
1207 && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
1208 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
1209 entry->flags.server = 0;
1214 * We restrict a 3-part SPN ending in my domain/realm to full
1215 * domain controllers.
1217 * This avoids any cases where (eg) a demoted DC still has
1218 * these more restricted SPNs.
1220 if (krb5_princ_size(context, principal) > 2) {
1221 char *third_part
1222 = smb_krb5_principal_get_comp_string(mem_ctx,
1223 context,
1224 principal,
1226 bool is_our_realm =
1227 lpcfg_is_my_domain_or_realm(lp_ctx,
1228 third_part);
1229 bool is_dc = userAccountControl &
1230 (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT);
1231 if (is_our_realm && !is_dc) {
1232 entry->flags.server = 0;
1236 * To give the correct type of error to the client, we must
1237 * not just return the entry without .server set, we must
1238 * pretend the principal does not exist. Otherwise we may
1239 * return ERR_POLICY instead of
1240 * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
1242 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry->flags.server == 0) {
1243 ret = SDB_ERR_NOENTRY;
1244 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
1245 goto out;
1247 if (flags & SDB_F_ADMIN_DATA) {
1248 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
1249 * of the Heimdal KDC. They are stored in a the traditional
1250 * DB for audit purposes, and still form part of the structure
1251 * we must return */
1253 /* use 'whenCreated' */
1254 entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1255 /* use 'kadmin' for now (needed by mit_samba) */
1257 ret = smb_krb5_make_principal(context,
1258 &entry->created_by.principal,
1259 lpcfg_realm(lp_ctx), "kadmin", NULL);
1260 if (ret) {
1261 krb5_clear_error_message(context);
1262 goto out;
1265 entry->modified_by = (struct sdb_event *) malloc(sizeof(struct sdb_event));
1266 if (entry->modified_by == NULL) {
1267 ret = ENOMEM;
1268 krb5_set_error_message(context, ret, "malloc: out of memory");
1269 goto out;
1272 /* use 'whenChanged' */
1273 entry->modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
1274 /* use 'kadmin' for now (needed by mit_samba) */
1275 ret = smb_krb5_make_principal(context,
1276 &entry->modified_by->principal,
1277 lpcfg_realm(lp_ctx), "kadmin", NULL);
1278 if (ret) {
1279 krb5_clear_error_message(context);
1280 goto out;
1285 /* The lack of password controls etc applies to krbtgt by
1286 * virtue of being that particular RID */
1287 status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
1289 if (!NT_STATUS_IS_OK(status)) {
1290 ret = EINVAL;
1291 goto out;
1294 if (rid == DOMAIN_RID_KRBTGT) {
1295 char *realm = NULL;
1297 entry->valid_end = NULL;
1298 entry->pw_end = NULL;
1300 entry->flags.invalid = 0;
1301 entry->flags.server = 1;
1303 realm = smb_krb5_principal_get_realm(
1304 mem_ctx, context, principal);
1305 if (realm == NULL) {
1306 ret = ENOMEM;
1307 goto out;
1310 /* Don't mark all requests for the krbtgt/realm as
1311 * 'change password', as otherwise we could get into
1312 * trouble, and not enforce the password expirty.
1313 * Instead, only do it when request is for the kpasswd service */
1314 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER &&
1315 is_kadmin_changepw(context, principal) &&
1316 lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
1317 entry->flags.change_pw = 1;
1320 TALLOC_FREE(realm);
1322 entry->flags.client = 0;
1323 entry->flags.forwardable = 1;
1324 entry->flags.ok_as_delegate = 1;
1325 } else if (is_rodc) {
1326 /* The RODC krbtgt account is like the main krbtgt,
1327 * but it does not have a changepw or kadmin
1328 * service */
1330 entry->valid_end = NULL;
1331 entry->pw_end = NULL;
1333 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
1334 entry->flags.client = 0;
1335 entry->flags.invalid = 0;
1336 entry->flags.server = 1;
1338 entry->flags.client = 0;
1339 entry->flags.forwardable = 1;
1340 entry->flags.ok_as_delegate = 0;
1341 } else if (entry->flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1342 /* The account/password expiry only applies when the account is used as a
1343 * client (ie password login), not when used as a server */
1345 /* Make very well sure we don't use this for a client,
1346 * it could bypass the password restrictions */
1347 entry->flags.client = 0;
1349 entry->valid_end = NULL;
1350 entry->pw_end = NULL;
1352 } else {
1353 NTTIME must_change_time
1354 = samdb_result_nttime(msg,
1355 "msDS-UserPasswordExpiryTimeComputed",
1357 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
1358 entry->pw_end = NULL;
1359 } else {
1360 entry->pw_end = malloc(sizeof(*entry->pw_end));
1361 if (entry->pw_end == NULL) {
1362 ret = ENOMEM;
1363 goto out;
1365 *entry->pw_end = nt_time_to_unix(must_change_time);
1368 acct_expiry = samdb_result_account_expires(msg);
1369 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
1370 entry->valid_end = NULL;
1371 } else {
1372 entry->valid_end = malloc(sizeof(*entry->valid_end));
1373 if (entry->valid_end == NULL) {
1374 ret = ENOMEM;
1375 goto out;
1377 *entry->valid_end = nt_time_to_unix(acct_expiry);
1381 ret = samba_kdc_get_entry_principal(context,
1382 kdc_db_ctx,
1383 samAccountName,
1384 ent_type,
1385 flags,
1386 entry->flags.change_pw,
1387 principal,
1388 &entry->principal);
1389 if (ret != 0) {
1390 krb5_clear_error_message(context);
1391 goto out;
1394 entry->valid_start = NULL;
1396 entry->max_life = malloc(sizeof(*entry->max_life));
1397 if (entry->max_life == NULL) {
1398 ret = ENOMEM;
1399 goto out;
1402 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1403 *entry->max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
1404 } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
1405 *entry->max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
1406 } else {
1407 *entry->max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
1408 kdc_db_ctx->policy.usr_tkt_lifetime);
1411 if (entry->flags.change_pw) {
1412 /* Limit lifetime of kpasswd tickets to two minutes or less. */
1413 *entry->max_life = MIN(*entry->max_life, CHANGEPW_LIFETIME);
1416 entry->max_renew = malloc(sizeof(*entry->max_renew));
1417 if (entry->max_renew == NULL) {
1418 ret = ENOMEM;
1419 goto out;
1422 *entry->max_renew = kdc_db_ctx->policy.renewal_lifetime;
1425 * A principal acting as a client that is not being looked up as the
1426 * principal of an armor ticket may have an authentication policy apply
1427 * to it.
1429 * We won’t get an authentication policy for the client of an S4U2Self
1430 * or S4U2Proxy request. Those clients are looked up with
1431 * SDB_F_FOR_TGS_REQ instead of with SDB_F_FOR_AS_REQ.
1433 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT &&
1434 (flags & SDB_F_FOR_AS_REQ) &&
1435 !(flags & SDB_F_ARMOR_PRINCIPAL))
1437 ret = authn_policy_kerberos_client(kdc_db_ctx->samdb, mem_ctx, msg,
1438 &authn_client_policy);
1439 if (ret) {
1440 goto out;
1445 * A principal acting as a server may have an authentication policy
1446 * apply to it.
1448 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1449 ret = authn_policy_server(kdc_db_ctx->samdb, mem_ctx, msg,
1450 &authn_server_policy);
1451 if (ret) {
1452 goto out;
1456 enforced_tgt_lifetime_raw = authn_policy_enforced_tgt_lifetime_raw(authn_client_policy);
1457 if (enforced_tgt_lifetime_raw != 0) {
1458 int64_t lifetime_secs = enforced_tgt_lifetime_raw;
1460 lifetime_secs /= INT64_C(1000) * 1000 * 10;
1461 lifetime_secs = MIN(lifetime_secs, INT_MAX);
1462 lifetime_secs = MAX(lifetime_secs, INT_MIN);
1465 * Set both lifetime and renewal time based only on the
1466 * configured maximum lifetime — not on the configured renewal
1467 * time. Yes, this is what Windows does.
1469 lifetime_secs = MIN(*entry->max_life, lifetime_secs);
1470 *entry->max_life = lifetime_secs;
1471 *entry->max_renew = lifetime_secs;
1474 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT && (flags & SDB_F_FOR_AS_REQ)) {
1475 int result;
1476 const struct auth_user_info_dc *user_info_dc = NULL;
1478 * These protections only apply to clients, so servers in the
1479 * Protected Users group may still have service tickets to them
1480 * encrypted with RC4. For accounts looked up as servers, note
1481 * that 'msg' does not contain the 'memberOf' attribute for
1482 * determining whether the account is a member of Protected
1483 * Users.
1485 * Additionally, Microsoft advises that accounts for services
1486 * and computers should never be members of Protected Users, or
1487 * they may fail to authenticate.
1489 status = samba_kdc_get_user_info_from_db(p, msg, &user_info_dc);
1490 if (!NT_STATUS_IS_OK(status)) {
1491 ret = EINVAL;
1492 goto out;
1495 result = dsdb_is_protected_user(kdc_db_ctx->samdb,
1496 user_info_dc->sids,
1497 user_info_dc->num_sids);
1498 if (result == -1) {
1499 ret = EINVAL;
1500 goto out;
1503 protected_user = result;
1505 if (protected_user && enforced_tgt_lifetime_raw == 0)
1508 * If a TGT lifetime hasn’t been set, Protected Users
1509 * enforces a four hour TGT lifetime.
1511 *entry->max_life = MIN(*entry->max_life, 4 * 60 * 60);
1512 *entry->max_renew = MIN(*entry->max_renew, 4 * 60 * 60);
1514 entry->flags.forwardable = 0;
1515 entry->flags.proxiable = 0;
1519 if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
1520 bool enable_fast;
1522 is_krbtgt = true;
1525 * KDCs (and KDCs on RODCs)
1526 * ignore msDS-SupportedEncryptionTypes completely
1527 * but support all supported enctypes by the domain.
1529 supported_enctypes = domain_enctypes;
1531 enable_fast = lpcfg_kdc_enable_fast(kdc_db_ctx->lp_ctx);
1532 if (enable_fast) {
1533 supported_enctypes |= ENC_FAST_SUPPORTED;
1536 supported_enctypes |= ENC_CLAIMS_SUPPORTED;
1537 supported_enctypes |= ENC_COMPOUND_IDENTITY_SUPPORTED;
1540 * Resource SID compression is enabled implicitly, unless
1541 * disabled in msDS-SupportedEncryptionTypes.
1544 } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
1546 * DCs and RODCs computer accounts take
1547 * msDS-SupportedEncryptionTypes unmodified, but
1548 * force all enctypes supported by the domain.
1550 supported_enctypes |= domain_enctypes;
1552 } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
1553 (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
1555 * for AS-REQ the client chooses the enc types it
1556 * supports, and this will vary between computers a
1557 * user logs in from. Therefore, so that we accept any
1558 * of the client's keys for decrypting padata,
1559 * supported_enctypes should not restrict etype usage.
1561 * likewise for 'any' return as much as is supported,
1562 * to export into a keytab.
1564 supported_enctypes |= ENC_ALL_TYPES;
1567 /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
1568 if (userAccountControl & UF_USE_DES_KEY_ONLY) {
1569 supported_enctypes &= ~ENC_ALL_TYPES;
1572 if (protected_user) {
1573 supported_enctypes &= ~ENC_RC4_HMAC_MD5;
1576 pa_supported_enctypes = supported_enctypes;
1577 supported_session_etypes = supported_enctypes;
1578 if (supported_session_etypes & ENC_HMAC_SHA1_96_AES256_SK) {
1579 supported_session_etypes |= ENC_HMAC_SHA1_96_AES256;
1580 supported_session_etypes |= ENC_HMAC_SHA1_96_AES128;
1582 if (force_rc4) {
1583 supported_session_etypes |= ENC_RC4_HMAC_MD5;
1586 * now that we remembered what to announce in pa_supported_enctypes
1587 * and normalized ENC_HMAC_SHA1_96_AES256_SK, we restrict the
1588 * rest to the enc types the local kdc supports.
1590 supported_enctypes &= kdc_enctypes;
1591 supported_session_etypes &= kdc_enctypes;
1593 /* Get keys from the db */
1594 ret = samba_kdc_message2entry_keys(context, p, msg,
1595 is_krbtgt, is_rodc,
1596 userAccountControl,
1597 ent_type, flags, kvno, entry,
1598 supported_enctypes,
1599 &available_enctypes);
1600 if (ret) {
1601 /* Could be bogus data in the entry, or out of memory */
1602 goto out;
1606 * If we only have a nthash stored,
1607 * but a better session key would be
1608 * available, we fallback to fetching the
1609 * RC4_HMAC_MD5, which implicitly also
1610 * would allow an RC4_HMAC_MD5 session key.
1611 * But only if the kdc actually supports
1612 * RC4_HMAC_MD5.
1614 if (available_enctypes == 0 &&
1615 (supported_enctypes & ENC_RC4_HMAC_MD5) == 0 &&
1616 (supported_enctypes & ~ENC_RC4_HMAC_MD5) != 0 &&
1617 (kdc_enctypes & ENC_RC4_HMAC_MD5) != 0)
1619 supported_enctypes = ENC_RC4_HMAC_MD5;
1620 ret = samba_kdc_message2entry_keys(context, p, msg,
1621 is_krbtgt, is_rodc,
1622 userAccountControl,
1623 ent_type, flags, kvno, entry,
1624 supported_enctypes,
1625 &available_enctypes);
1626 if (ret) {
1627 /* Could be bogus data in the entry, or out of memory */
1628 goto out;
1633 * We need to support all session keys enctypes for
1634 * all keys we provide
1636 supported_session_etypes |= available_enctypes;
1638 ret = sdb_entry_set_etypes(entry);
1639 if (ret) {
1640 goto out;
1643 if (entry->flags.server) {
1644 bool add_aes256 =
1645 supported_session_etypes & KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96;
1646 bool add_aes128 =
1647 supported_session_etypes & KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96;
1648 bool add_rc4 =
1649 supported_session_etypes & ENC_RC4_HMAC_MD5;
1650 ret = sdb_entry_set_session_etypes(entry,
1651 add_aes256,
1652 add_aes128,
1653 add_rc4);
1654 if (ret) {
1655 goto out;
1659 if (entry->keys.len != 0) {
1661 * FIXME: Currently limited to Heimdal so as not to
1662 * break MIT KDCs, for which no fix is available.
1664 #ifdef SAMBA4_USES_HEIMDAL
1665 if (is_krbtgt) {
1667 * The krbtgt account, having no reason to
1668 * issue tickets encrypted in weaker keys,
1669 * shall only make available its strongest
1670 * key. All weaker keys are stripped out. This
1671 * makes it impossible for an RC4-encrypted
1672 * TGT to be accepted when AES KDC keys exist.
1674 * This controls the ticket key and so the PAC
1675 * signature algorithms indirectly, preventing
1676 * a weak KDC checksum from being accepted
1677 * when we verify the signatures for an
1678 * S4U2Proxy evidence ticket. As such, this is
1679 * indispensable for addressing
1680 * CVE-2022-37966.
1682 * Being strict here also provides protection
1683 * against possible future attacks on weak
1684 * keys.
1686 entry->keys.len = 1;
1687 if (entry->etypes != NULL) {
1688 entry->etypes->len = 1;
1690 entry->old_keys.len = MIN(entry->old_keys.len, 1);
1691 entry->older_keys.len = MIN(entry->older_keys.len, 1);
1693 #endif
1694 } else if (kdc_db_ctx->rodc) {
1696 * We are on an RODC, but don't have keys for this
1697 * account. Signal this to the caller
1699 auth_sam_trigger_repl_secret(kdc_db_ctx,
1700 kdc_db_ctx->msg_ctx,
1701 kdc_db_ctx->ev_ctx,
1702 msg->dn);
1703 return SDB_ERR_NOT_FOUND_HERE;
1704 } else {
1706 * oh, no password. Apparently (comment in
1707 * hdb-ldap.c) this violates the ASN.1, but this
1708 * allows an entry with no keys (yet).
1712 p->msg = talloc_steal(p, msg);
1713 p->supported_enctypes = pa_supported_enctypes;
1715 p->client_policy = talloc_steal(p, authn_client_policy);
1716 p->server_policy = talloc_steal(p, authn_server_policy);
1718 out:
1719 if (ret != 0) {
1720 /* This doesn't free ent itself, that is for the eventual caller to do */
1721 sdb_entry_free(entry);
1722 } else {
1723 talloc_steal(kdc_db_ctx, p);
1726 return ret;
1730 * Construct an hdb_entry from a directory entry.
1731 * The kvno is what the remote client asked for
1733 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
1734 struct samba_kdc_db_context *kdc_db_ctx,
1735 TALLOC_CTX *mem_ctx,
1736 enum trust_direction direction,
1737 struct ldb_dn *realm_dn,
1738 unsigned flags,
1739 uint32_t kvno,
1740 struct ldb_message *msg,
1741 struct sdb_entry *entry)
1743 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1744 const char *our_realm = lpcfg_realm(lp_ctx);
1745 char *partner_realm = NULL;
1746 const char *realm = NULL;
1747 const char *krbtgt_realm = NULL;
1748 DATA_BLOB password_utf16 = data_blob_null;
1749 DATA_BLOB password_utf8 = data_blob_null;
1750 struct samr_Password _password_hash;
1751 const struct samr_Password *password_hash = NULL;
1752 const struct ldb_val *password_val;
1753 struct trustAuthInOutBlob password_blob;
1754 struct samba_kdc_entry *p;
1755 bool use_previous = false;
1756 uint32_t current_kvno;
1757 uint32_t previous_kvno;
1758 uint32_t num_keys = 0;
1759 enum ndr_err_code ndr_err;
1760 int ret;
1761 unsigned int i;
1762 struct AuthenticationInformationArray *auth_array;
1763 struct timeval tv;
1764 NTTIME an_hour_ago;
1765 uint32_t *auth_kvno;
1766 bool preferr_current = false;
1767 bool force_rc4 = lpcfg_kdc_force_enable_rc4_weak_session_keys(lp_ctx);
1768 uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
1769 uint32_t pa_supported_enctypes;
1770 uint32_t supported_session_etypes;
1771 uint32_t config_kdc_enctypes = lpcfg_kdc_supported_enctypes(lp_ctx);
1772 uint32_t kdc_enctypes =
1773 config_kdc_enctypes != 0 ?
1774 config_kdc_enctypes :
1775 ENC_ALL_TYPES;
1776 struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
1777 NTSTATUS status;
1779 ZERO_STRUCTP(entry);
1781 if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1782 /* If not told otherwise, Windows now assumes that trusts support AES. */
1783 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
1784 "msDS-SupportedEncryptionTypes",
1785 ENC_HMAC_SHA1_96_AES256);
1788 pa_supported_enctypes = supported_enctypes;
1789 supported_session_etypes = supported_enctypes;
1790 if (supported_session_etypes & ENC_HMAC_SHA1_96_AES256_SK) {
1791 supported_session_etypes |= ENC_HMAC_SHA1_96_AES256;
1792 supported_session_etypes |= ENC_HMAC_SHA1_96_AES128;
1794 if (force_rc4) {
1795 supported_session_etypes |= ENC_RC4_HMAC_MD5;
1798 * now that we remembered what to announce in pa_supported_enctypes
1799 * and normalized ENC_HMAC_SHA1_96_AES256_SK, we restrict the
1800 * rest to the enc types the local kdc supports.
1802 supported_enctypes &= kdc_enctypes;
1803 supported_session_etypes &= kdc_enctypes;
1805 status = dsdb_trust_parse_tdo_info(mem_ctx, msg, &tdo);
1806 if (!NT_STATUS_IS_OK(status)) {
1807 krb5_clear_error_message(context);
1808 ret = ENOMEM;
1809 goto out;
1812 if (!(tdo->trust_direction & direction)) {
1813 krb5_clear_error_message(context);
1814 ret = SDB_ERR_NOENTRY;
1815 goto out;
1818 if (tdo->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
1820 * Only UPLEVEL domains support kerberos here,
1821 * as we don't support LSA_TRUST_TYPE_MIT.
1823 krb5_clear_error_message(context);
1824 ret = SDB_ERR_NOENTRY;
1825 goto out;
1828 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_CROSS_ORGANIZATION) {
1830 * We don't support selective authentication yet.
1832 krb5_clear_error_message(context);
1833 ret = SDB_ERR_NOENTRY;
1834 goto out;
1837 if (tdo->domain_name.string == NULL) {
1838 krb5_clear_error_message(context);
1839 ret = SDB_ERR_NOENTRY;
1840 goto out;
1842 partner_realm = strupper_talloc(mem_ctx, tdo->domain_name.string);
1843 if (partner_realm == NULL) {
1844 krb5_clear_error_message(context);
1845 ret = ENOMEM;
1846 goto out;
1849 if (direction == INBOUND) {
1850 realm = our_realm;
1851 krbtgt_realm = partner_realm;
1853 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
1854 } else { /* OUTBOUND */
1855 realm = partner_realm;
1856 krbtgt_realm = our_realm;
1858 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
1861 if (password_val == NULL) {
1862 krb5_clear_error_message(context);
1863 ret = SDB_ERR_NOENTRY;
1864 goto out;
1867 ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
1868 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1869 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1870 krb5_clear_error_message(context);
1871 ret = EINVAL;
1872 goto out;
1875 p = talloc_zero(mem_ctx, struct samba_kdc_entry);
1876 if (!p) {
1877 ret = ENOMEM;
1878 goto out;
1881 p->is_trust = true;
1882 p->kdc_db_ctx = kdc_db_ctx;
1883 p->realm_dn = realm_dn;
1884 p->supported_enctypes = pa_supported_enctypes;
1886 talloc_set_destructor(p, samba_kdc_entry_destructor);
1888 entry->skdc_entry = p;
1890 /* use 'whenCreated' */
1891 entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1892 /* use 'kadmin' for now (needed by mit_samba) */
1893 ret = smb_krb5_make_principal(context,
1894 &entry->created_by.principal,
1895 realm, "kadmin", NULL);
1896 if (ret) {
1897 krb5_clear_error_message(context);
1898 goto out;
1902 * We always need to generate the canonicalized principal
1903 * with the values of our database.
1905 ret = smb_krb5_make_principal(context, &entry->principal, realm,
1906 "krbtgt", krbtgt_realm, NULL);
1907 if (ret) {
1908 krb5_clear_error_message(context);
1909 goto out;
1911 smb_krb5_principal_set_type(context, entry->principal,
1912 KRB5_NT_SRV_INST);
1914 entry->valid_start = NULL;
1916 /* we need to work out if we are going to use the current or
1917 * the previous password hash.
1918 * We base this on the kvno the client passes in. If the kvno
1919 * passed in is equal to the current kvno in our database then
1920 * we use the current structure. If it is the current kvno-1,
1921 * then we use the previous substrucure.
1925 * Windows preferrs the previous key for one hour.
1927 tv = timeval_current();
1928 if (tv.tv_sec > 3600) {
1929 tv.tv_sec -= 3600;
1931 an_hour_ago = timeval_to_nttime(&tv);
1933 /* first work out the current kvno */
1934 current_kvno = 0;
1935 for (i=0; i < password_blob.count; i++) {
1936 struct AuthenticationInformation *a =
1937 &password_blob.current.array[i];
1939 if (a->LastUpdateTime <= an_hour_ago) {
1940 preferr_current = true;
1943 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1944 current_kvno = a->AuthInfo.version.version;
1947 if (current_kvno == 0) {
1948 previous_kvno = 255;
1949 } else {
1950 previous_kvno = current_kvno - 1;
1952 for (i=0; i < password_blob.count; i++) {
1953 struct AuthenticationInformation *a =
1954 &password_blob.previous.array[i];
1956 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1957 previous_kvno = a->AuthInfo.version.version;
1961 /* work out whether we will use the previous or current
1962 password */
1963 if (password_blob.previous.count == 0) {
1964 /* there is no previous password */
1965 use_previous = false;
1966 } else if (!(flags & SDB_F_KVNO_SPECIFIED)) {
1968 * If not specified we use the lowest kvno
1969 * for the first hour after an update.
1971 if (preferr_current) {
1972 use_previous = false;
1973 } else if (previous_kvno < current_kvno) {
1974 use_previous = true;
1975 } else {
1976 use_previous = false;
1978 } else if (kvno == current_kvno) {
1980 * Exact match ...
1982 use_previous = false;
1983 } else if (kvno == previous_kvno) {
1985 * Exact match ...
1987 use_previous = true;
1988 } else {
1990 * Fallback to the current one for anything else
1992 use_previous = false;
1995 if (use_previous) {
1996 auth_array = &password_blob.previous;
1997 auth_kvno = &previous_kvno;
1998 } else {
1999 auth_array = &password_blob.current;
2000 auth_kvno = &current_kvno;
2003 /* use the kvno the client specified, if available */
2004 if (flags & SDB_F_KVNO_SPECIFIED) {
2005 entry->kvno = kvno;
2006 } else {
2007 entry->kvno = *auth_kvno;
2010 for (i=0; i < auth_array->count; i++) {
2011 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2012 bool ok;
2014 password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
2015 auth_array->array[i].AuthInfo.clear.size);
2016 if (password_utf16.length == 0) {
2017 break;
2020 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
2021 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
2022 if (password_hash == NULL) {
2023 num_keys += 1;
2025 password_hash = &_password_hash;
2028 if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
2029 break;
2032 ok = convert_string_talloc(mem_ctx,
2033 CH_UTF16MUNGED, CH_UTF8,
2034 password_utf16.data,
2035 password_utf16.length,
2036 (void *)&password_utf8.data,
2037 &password_utf8.length);
2038 if (!ok) {
2039 krb5_clear_error_message(context);
2040 ret = ENOMEM;
2041 goto out;
2044 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
2045 num_keys += 1;
2047 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
2048 num_keys += 1;
2050 break;
2051 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
2052 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
2053 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
2054 num_keys += 1;
2059 /* Must have found a cleartext or MD4 password */
2060 if (num_keys == 0) {
2061 DEBUG(1,(__location__ ": no usable key found\n"));
2062 krb5_clear_error_message(context);
2063 ret = SDB_ERR_NOENTRY;
2064 goto out;
2067 entry->keys.val = calloc(num_keys, sizeof(struct sdb_key));
2068 if (entry->keys.val == NULL) {
2069 krb5_clear_error_message(context);
2070 ret = ENOMEM;
2071 goto out;
2074 if (password_utf8.length != 0) {
2075 struct sdb_key key = {};
2076 krb5_const_principal salt_principal = entry->principal;
2077 krb5_data salt;
2078 krb5_data cleartext_data;
2080 cleartext_data.data = discard_const_p(char, password_utf8.data);
2081 cleartext_data.length = password_utf8.length;
2083 ret = smb_krb5_get_pw_salt(context,
2084 salt_principal,
2085 &salt);
2086 if (ret != 0) {
2087 goto out;
2090 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
2091 ret = smb_krb5_create_key_from_string(context,
2092 salt_principal,
2093 &salt,
2094 &cleartext_data,
2095 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
2096 &key.key);
2097 if (ret != 0) {
2098 smb_krb5_free_data_contents(context, &salt);
2099 goto out;
2102 entry->keys.val[entry->keys.len] = key;
2103 entry->keys.len++;
2106 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
2107 ret = smb_krb5_create_key_from_string(context,
2108 salt_principal,
2109 &salt,
2110 &cleartext_data,
2111 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
2112 &key.key);
2113 if (ret != 0) {
2114 smb_krb5_free_data_contents(context, &salt);
2115 goto out;
2118 entry->keys.val[entry->keys.len] = key;
2119 entry->keys.len++;
2122 smb_krb5_free_data_contents(context, &salt);
2125 if (password_hash != NULL) {
2126 struct sdb_key key = {};
2128 ret = smb_krb5_keyblock_init_contents(context,
2129 ENCTYPE_ARCFOUR_HMAC,
2130 password_hash->hash,
2131 sizeof(password_hash->hash),
2132 &key.key);
2133 if (ret != 0) {
2134 goto out;
2137 entry->keys.val[entry->keys.len] = key;
2138 entry->keys.len++;
2141 entry->flags = int2SDBFlags(0);
2142 entry->flags.immutable = 1;
2143 entry->flags.invalid = 0;
2144 entry->flags.server = 1;
2145 entry->flags.require_preauth = 1;
2147 entry->pw_end = NULL;
2149 entry->max_life = NULL;
2151 entry->max_renew = NULL;
2153 /* Match Windows behavior and allow forwardable flag in cross-realm. */
2154 entry->flags.forwardable = 1;
2156 samba_kdc_sort_keys(&entry->keys);
2158 ret = sdb_entry_set_etypes(entry);
2159 if (ret) {
2160 goto out;
2164 bool add_aes256 =
2165 supported_session_etypes & KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96;
2166 bool add_aes128 =
2167 supported_session_etypes & KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96;
2168 bool add_rc4 =
2169 supported_session_etypes & ENC_RC4_HMAC_MD5;
2170 ret = sdb_entry_set_session_etypes(entry,
2171 add_aes256,
2172 add_aes128,
2173 add_rc4);
2174 if (ret) {
2175 goto out;
2179 p->msg = talloc_steal(p, msg);
2181 out:
2182 TALLOC_FREE(partner_realm);
2184 if (ret != 0) {
2185 /* This doesn't free ent itself, that is for the eventual caller to do */
2186 sdb_entry_free(entry);
2187 } else {
2188 talloc_steal(kdc_db_ctx, p);
2191 return ret;
2195 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
2196 TALLOC_CTX *mem_ctx,
2197 const char *realm,
2198 struct ldb_dn *realm_dn,
2199 struct ldb_message **pmsg)
2201 NTSTATUS status;
2202 const char * const *attrs = trust_attrs;
2204 status = dsdb_trust_search_tdo(ldb_ctx, realm, realm,
2205 attrs, mem_ctx, pmsg);
2206 if (NT_STATUS_IS_OK(status)) {
2207 return 0;
2208 } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2209 return SDB_ERR_NOENTRY;
2210 } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
2211 int ret = ENOMEM;
2212 krb5_set_error_message(context, ret, "samba_kdc_lookup_trust: out of memory");
2213 return ret;
2214 } else {
2215 int ret = EINVAL;
2216 krb5_set_error_message(context, ret, "samba_kdc_lookup_trust: %s", nt_errstr(status));
2217 return ret;
2221 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
2222 struct samba_kdc_db_context *kdc_db_ctx,
2223 TALLOC_CTX *mem_ctx,
2224 krb5_const_principal principal,
2225 const char **attrs,
2226 struct ldb_dn **realm_dn,
2227 struct ldb_message **msg)
2229 NTSTATUS nt_status;
2230 char *principal_string = NULL;
2232 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2233 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
2234 principal, 0);
2235 if (principal_string == NULL) {
2236 return ENOMEM;
2238 } else {
2239 char *principal_string_m = NULL;
2240 krb5_error_code ret;
2242 ret = krb5_unparse_name(context, principal, &principal_string_m);
2243 if (ret != 0) {
2244 return ret;
2247 principal_string = talloc_strdup(mem_ctx, principal_string_m);
2248 SAFE_FREE(principal_string_m);
2249 if (principal_string == NULL) {
2250 return ENOMEM;
2254 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
2255 mem_ctx, principal_string, attrs,
2256 realm_dn, msg);
2257 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
2258 krb5_principal fallback_principal = NULL;
2259 unsigned int num_comp;
2260 char *fallback_realm = NULL;
2261 char *fallback_account = NULL;
2262 krb5_error_code ret;
2264 ret = krb5_parse_name(context, principal_string,
2265 &fallback_principal);
2266 TALLOC_FREE(principal_string);
2267 if (ret != 0) {
2268 return ret;
2271 num_comp = krb5_princ_size(context, fallback_principal);
2272 fallback_realm = smb_krb5_principal_get_realm(
2273 mem_ctx, context, fallback_principal);
2274 if (fallback_realm == NULL) {
2275 krb5_free_principal(context, fallback_principal);
2276 return ENOMEM;
2279 if (num_comp == 1) {
2280 size_t len;
2282 fallback_account = smb_krb5_principal_get_comp_string(mem_ctx,
2283 context, fallback_principal, 0);
2284 if (fallback_account == NULL) {
2285 krb5_free_principal(context, fallback_principal);
2286 TALLOC_FREE(fallback_realm);
2287 return ENOMEM;
2290 len = strlen(fallback_account);
2291 if (len >= 2 && fallback_account[len - 1] == '$') {
2292 TALLOC_FREE(fallback_account);
2295 krb5_free_principal(context, fallback_principal);
2296 fallback_principal = NULL;
2298 if (fallback_account != NULL) {
2299 char *with_dollar;
2301 with_dollar = talloc_asprintf(mem_ctx, "%s$",
2302 fallback_account);
2303 if (with_dollar == NULL) {
2304 TALLOC_FREE(fallback_realm);
2305 return ENOMEM;
2307 TALLOC_FREE(fallback_account);
2309 ret = smb_krb5_make_principal(context,
2310 &fallback_principal,
2311 fallback_realm,
2312 with_dollar, NULL);
2313 TALLOC_FREE(with_dollar);
2314 if (ret != 0) {
2315 TALLOC_FREE(fallback_realm);
2316 return ret;
2319 TALLOC_FREE(fallback_realm);
2321 if (fallback_principal != NULL) {
2322 char *fallback_string = NULL;
2324 ret = krb5_unparse_name(context,
2325 fallback_principal,
2326 &fallback_string);
2327 if (ret != 0) {
2328 krb5_free_principal(context, fallback_principal);
2329 return ret;
2332 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
2333 mem_ctx,
2334 fallback_string,
2335 attrs,
2336 realm_dn, msg);
2337 SAFE_FREE(fallback_string);
2339 krb5_free_principal(context, fallback_principal);
2340 fallback_principal = NULL;
2342 TALLOC_FREE(principal_string);
2344 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
2345 return SDB_ERR_NOENTRY;
2346 } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
2347 return ENOMEM;
2348 } else if (!NT_STATUS_IS_OK(nt_status)) {
2349 return EINVAL;
2352 return 0;
2355 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
2356 struct samba_kdc_db_context *kdc_db_ctx,
2357 TALLOC_CTX *mem_ctx,
2358 krb5_const_principal principal,
2359 unsigned flags,
2360 krb5_kvno kvno,
2361 struct sdb_entry *entry)
2363 struct ldb_dn *realm_dn;
2364 krb5_error_code ret;
2365 struct ldb_message *msg = NULL;
2367 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2368 mem_ctx, principal, user_attrs,
2369 &realm_dn, &msg);
2370 if (ret != 0) {
2371 return ret;
2374 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2375 principal, SAMBA_KDC_ENT_TYPE_CLIENT,
2376 flags, kvno,
2377 realm_dn, msg, entry);
2378 return ret;
2381 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
2382 struct samba_kdc_db_context *kdc_db_ctx,
2383 TALLOC_CTX *mem_ctx,
2384 krb5_const_principal principal,
2385 unsigned flags,
2386 uint32_t kvno,
2387 struct sdb_entry *entry)
2389 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
2390 krb5_error_code ret;
2391 struct ldb_message *msg = NULL;
2392 struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2393 char *realm_from_princ;
2394 char *realm_princ_comp = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 1);
2396 realm_from_princ = smb_krb5_principal_get_realm(
2397 mem_ctx, context, principal);
2398 if (realm_from_princ == NULL) {
2399 /* can't happen */
2400 return SDB_ERR_NOENTRY;
2403 if (krb5_princ_size(context, principal) != 2
2404 || (principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME) != 0)) {
2405 /* Not a krbtgt */
2406 return SDB_ERR_NOENTRY;
2409 /* krbtgt case. Either us or a trusted realm */
2411 if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
2412 && lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp)) {
2413 /* us, or someone quite like us */
2414 /* Cludge, cludge cludge. If the realm part of krbtgt/realm,
2415 * is in our db, then direct the caller at our primary
2416 * krbtgt */
2418 int lret;
2419 unsigned int krbtgt_number;
2420 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
2421 trust tickets. We don't yet know what this means, but we do
2422 seem to need to treat it as unspecified */
2423 if (flags & SDB_F_KVNO_SPECIFIED) {
2424 krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
2425 if (kdc_db_ctx->rodc) {
2426 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
2427 return SDB_ERR_NOT_FOUND_HERE;
2430 } else {
2431 krbtgt_number = kdc_db_ctx->my_krbtgt_number;
2434 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
2435 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
2436 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
2437 krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
2438 "(objectClass=user)");
2439 } else {
2440 /* We need to look up an RODC krbtgt (perhaps
2441 * ours, if we are an RODC, perhaps another
2442 * RODC if we are a read-write DC */
2443 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
2444 &msg, realm_dn, LDB_SCOPE_SUBTREE,
2445 krbtgt_attrs,
2446 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2447 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
2450 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2451 krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2452 (unsigned)(krbtgt_number));
2453 krb5_set_error_message(context, SDB_ERR_NOENTRY,
2454 "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2455 (unsigned)(krbtgt_number));
2456 return SDB_ERR_NOENTRY;
2457 } else if (lret != LDB_SUCCESS) {
2458 krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2459 (unsigned)(krbtgt_number));
2460 krb5_set_error_message(context, SDB_ERR_NOENTRY,
2461 "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2462 (unsigned)(krbtgt_number));
2463 return SDB_ERR_NOENTRY;
2466 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2467 principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
2468 flags, kvno, realm_dn, msg, entry);
2469 if (ret != 0) {
2470 krb5_warnx(context, "samba_kdc_fetch_krbtgt: self krbtgt message2entry failed");
2472 return ret;
2474 } else {
2475 enum trust_direction direction = UNKNOWN;
2476 const char *realm = NULL;
2478 /* Either an inbound or outbound trust */
2480 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
2481 /* look for inbound trust */
2482 direction = INBOUND;
2483 realm = realm_princ_comp;
2484 } else if (principal_comp_strcasecmp(context, principal, 1, lpcfg_realm(lp_ctx)) == 0) {
2485 /* look for outbound trust */
2486 direction = OUTBOUND;
2487 realm = realm_from_princ;
2488 } else {
2489 krb5_warnx(context, "samba_kdc_fetch_krbtgt: not our realm for trusts ('%s', '%s')",
2490 realm_from_princ,
2491 realm_princ_comp);
2492 krb5_set_error_message(context, SDB_ERR_NOENTRY, "samba_kdc_fetch_krbtgt: not our realm for trusts ('%s', '%s')",
2493 realm_from_princ,
2494 realm_princ_comp);
2495 return SDB_ERR_NOENTRY;
2498 /* Trusted domains are under CN=system */
2500 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
2501 mem_ctx,
2502 realm, realm_dn, &msg);
2504 if (ret != 0) {
2505 krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find principal in DB");
2506 krb5_set_error_message(context, ret, "samba_kdc_fetch_krbtgt: could not find principal in DB");
2507 return ret;
2510 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
2511 direction,
2512 realm_dn, flags, kvno, msg, entry);
2513 if (ret != 0) {
2514 krb5_warnx(context, "samba_kdc_fetch_krbtgt: trust_message2entry failed for %s",
2515 ldb_dn_get_linearized(msg->dn));
2516 krb5_set_error_message(context, ret, "samba_kdc_fetch_krbtgt: "
2517 "trust_message2entry failed for %s",
2518 ldb_dn_get_linearized(msg->dn));
2520 return ret;
2525 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
2526 struct samba_kdc_db_context *kdc_db_ctx,
2527 TALLOC_CTX *mem_ctx,
2528 krb5_const_principal principal,
2529 unsigned flags,
2530 const char **attrs,
2531 struct ldb_dn **realm_dn,
2532 struct ldb_message **msg)
2534 krb5_error_code ret;
2535 if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
2536 && krb5_princ_size(context, principal) >= 2) {
2537 /* 'normal server' case */
2538 int ldb_ret;
2539 NTSTATUS nt_status;
2540 struct ldb_dn *user_dn;
2541 char *principal_string;
2543 ret = krb5_unparse_name_flags(context, principal,
2544 KRB5_PRINCIPAL_UNPARSE_NO_REALM,
2545 &principal_string);
2546 if (ret != 0) {
2547 return ret;
2550 /* At this point we may find the host is known to be
2551 * in a different realm, so we should generate a
2552 * referral instead */
2553 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
2554 mem_ctx, principal_string,
2555 &user_dn, realm_dn);
2556 free(principal_string);
2558 if (!NT_STATUS_IS_OK(nt_status)) {
2559 return SDB_ERR_NOENTRY;
2562 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
2563 mem_ctx,
2564 msg, user_dn, LDB_SCOPE_BASE,
2565 attrs,
2566 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2567 "(objectClass=*)");
2568 if (ldb_ret != LDB_SUCCESS) {
2569 return SDB_ERR_NOENTRY;
2571 return 0;
2572 } else if (!(flags & SDB_F_FOR_AS_REQ)
2573 && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2575 * The behaviour of accepting an
2576 * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
2577 * containing a UPN only applies to TGS-REQ packets,
2578 * not AS-REQ packets.
2580 return samba_kdc_lookup_client(context, kdc_db_ctx,
2581 mem_ctx, principal, attrs,
2582 realm_dn, msg);
2583 } else {
2585 * This case is for:
2586 * - the AS-REQ, where we only accept
2587 * samAccountName based lookups for the server, no
2588 * matter if the name is an
2589 * KRB5_NT_ENTERPRISE_PRINCIPAL or not
2590 * - for the TGS-REQ when we are not given an
2591 * KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
2592 * only lookup samAccountName based names.
2594 int lret;
2595 char *short_princ;
2596 krb5_principal enterprise_principal = NULL;
2597 krb5_const_principal used_principal = NULL;
2598 char *name1 = NULL;
2599 size_t len1 = 0;
2600 char *filter = NULL;
2602 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2603 char *str = NULL;
2604 /* Need to reparse the enterprise principal to find the real target */
2605 if (krb5_princ_size(context, principal) != 1) {
2606 ret = KRB5_PARSE_MALFORMED;
2607 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
2608 "enterprise principal with wrong (%d) number of components",
2609 krb5_princ_size(context, principal));
2610 return ret;
2612 str = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0);
2613 if (str == NULL) {
2614 return KRB5_PARSE_MALFORMED;
2616 ret = krb5_parse_name(context, str,
2617 &enterprise_principal);
2618 talloc_free(str);
2619 if (ret) {
2620 return ret;
2622 used_principal = enterprise_principal;
2623 } else {
2624 used_principal = principal;
2627 /* server as client principal case, but we must not lookup userPrincipalNames */
2628 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2630 /* TODO: Check if it is our realm, otherwise give referral */
2632 ret = krb5_unparse_name_flags(context, used_principal,
2633 KRB5_PRINCIPAL_UNPARSE_NO_REALM |
2634 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2635 &short_princ);
2636 used_principal = NULL;
2637 krb5_free_principal(context, enterprise_principal);
2638 enterprise_principal = NULL;
2640 if (ret != 0) {
2641 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: could not parse principal");
2642 krb5_warnx(context, "samba_kdc_lookup_server: could not parse principal");
2643 return ret;
2646 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
2647 SAFE_FREE(short_princ);
2648 if (name1 == NULL) {
2649 return ENOMEM;
2651 len1 = strlen(name1);
2652 if (len1 >= 1 && name1[len1 - 1] != '$') {
2653 filter = talloc_asprintf(mem_ctx,
2654 "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
2655 name1, name1);
2656 if (filter == NULL) {
2657 return ENOMEM;
2659 } else {
2660 filter = talloc_asprintf(mem_ctx,
2661 "(&(objectClass=user)(samAccountName=%s))",
2662 name1);
2663 if (filter == NULL) {
2664 return ENOMEM;
2668 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
2669 *realm_dn, LDB_SCOPE_SUBTREE,
2670 attrs,
2671 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2672 "%s", filter);
2673 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2674 DEBUG(10, ("Failed to find an entry for %s filter:%s\n",
2675 name1, filter));
2676 return SDB_ERR_NOENTRY;
2678 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
2679 DEBUG(10, ("Failed to find unique entry for %s filter:%s\n",
2680 name1, filter));
2681 return SDB_ERR_NOENTRY;
2683 if (lret != LDB_SUCCESS) {
2684 DEBUG(0, ("Failed single search for %s - %s\n",
2685 name1, ldb_errstring(kdc_db_ctx->samdb)));
2686 return SDB_ERR_NOENTRY;
2688 return 0;
2690 return SDB_ERR_NOENTRY;
2695 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
2696 struct samba_kdc_db_context *kdc_db_ctx,
2697 TALLOC_CTX *mem_ctx,
2698 krb5_const_principal principal,
2699 unsigned flags,
2700 krb5_kvno kvno,
2701 struct sdb_entry *entry)
2703 krb5_error_code ret;
2704 struct ldb_dn *realm_dn;
2705 struct ldb_message *msg;
2707 ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
2708 flags, server_attrs, &realm_dn, &msg);
2709 if (ret != 0) {
2710 return ret;
2713 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2714 principal, SAMBA_KDC_ENT_TYPE_SERVER,
2715 flags, kvno,
2716 realm_dn, msg, entry);
2717 if (ret != 0) {
2718 char *client_name = NULL;
2719 krb5_error_code code;
2721 code = krb5_unparse_name(context, principal, &client_name);
2722 if (code == 0) {
2723 krb5_warnx(context,
2724 "samba_kdc_fetch_server: message2entry failed for "
2725 "%s",
2726 client_name);
2727 } else {
2728 krb5_warnx(context,
2729 "samba_kdc_fetch_server: message2entry and "
2730 "krb5_unparse_name failed");
2732 SAFE_FREE(client_name);
2735 return ret;
2738 static krb5_error_code samba_kdc_lookup_realm(krb5_context context,
2739 struct samba_kdc_db_context *kdc_db_ctx,
2740 TALLOC_CTX *mem_ctx,
2741 krb5_const_principal principal,
2742 unsigned flags,
2743 struct sdb_entry *entry)
2745 TALLOC_CTX *frame = talloc_stackframe();
2746 NTSTATUS status;
2747 krb5_error_code ret;
2748 bool check_realm = false;
2749 const char *realm = NULL;
2750 struct dsdb_trust_routing_table *trt = NULL;
2751 const struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
2752 unsigned int num_comp;
2753 bool ok;
2754 char *upper = NULL;
2756 num_comp = krb5_princ_size(context, principal);
2758 if (flags & SDB_F_GET_CLIENT) {
2759 if (flags & SDB_F_FOR_AS_REQ) {
2760 check_realm = true;
2763 if (flags & SDB_F_GET_SERVER) {
2764 if (flags & SDB_F_FOR_TGS_REQ) {
2765 check_realm = true;
2769 if (!check_realm) {
2770 TALLOC_FREE(frame);
2771 return 0;
2774 realm = smb_krb5_principal_get_realm(frame, context, principal);
2775 if (realm == NULL) {
2776 TALLOC_FREE(frame);
2777 return ENOMEM;
2781 * The requested realm needs to be our own
2783 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2784 if (!ok) {
2786 * The request is not for us...
2788 TALLOC_FREE(frame);
2789 return SDB_ERR_NOENTRY;
2792 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2793 char *principal_string = NULL;
2794 krb5_principal enterprise_principal = NULL;
2795 char *enterprise_realm = NULL;
2797 if (num_comp != 1) {
2798 TALLOC_FREE(frame);
2799 return SDB_ERR_NOENTRY;
2802 principal_string = smb_krb5_principal_get_comp_string(frame, context,
2803 principal, 0);
2804 if (principal_string == NULL) {
2805 TALLOC_FREE(frame);
2806 return ENOMEM;
2809 ret = krb5_parse_name(context, principal_string,
2810 &enterprise_principal);
2811 TALLOC_FREE(principal_string);
2812 if (ret) {
2813 TALLOC_FREE(frame);
2814 return ret;
2817 enterprise_realm = smb_krb5_principal_get_realm(
2818 frame, context, enterprise_principal);
2819 krb5_free_principal(context, enterprise_principal);
2820 if (enterprise_realm != NULL) {
2821 realm = enterprise_realm;
2825 if (flags & SDB_F_GET_SERVER) {
2826 char *service_realm = NULL;
2828 ret = principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME);
2829 if (ret == 0) {
2831 * we need to search krbtgt/ locally
2833 TALLOC_FREE(frame);
2834 return 0;
2838 * We need to check the last component against the routing table.
2840 * Note this works only with 2 or 3 component principals, e.g:
2842 * servicePrincipalName: ldap/W2K8R2-219.bla.base
2843 * servicePrincipalName: ldap/W2K8R2-219.bla.base/bla.base
2844 * servicePrincipalName: ldap/W2K8R2-219.bla.base/ForestDnsZones.bla.base
2845 * servicePrincipalName: ldap/W2K8R2-219.bla.base/DomainDnsZones.bla.base
2848 if (num_comp == 2 || num_comp == 3) {
2849 service_realm = smb_krb5_principal_get_comp_string(frame,
2850 context,
2851 principal,
2852 num_comp - 1);
2855 if (service_realm != NULL) {
2856 realm = service_realm;
2860 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2861 if (ok) {
2863 * skip the expensive routing lookup
2865 TALLOC_FREE(frame);
2866 return 0;
2869 status = dsdb_trust_routing_table_load(kdc_db_ctx->samdb,
2870 frame, &trt);
2871 if (!NT_STATUS_IS_OK(status)) {
2872 TALLOC_FREE(frame);
2873 return EINVAL;
2876 tdo = dsdb_trust_routing_by_name(trt, realm);
2877 if (tdo == NULL) {
2879 * This principal has to be local
2881 TALLOC_FREE(frame);
2882 return 0;
2885 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
2887 * TODO: handle the routing within the forest
2889 * This should likely be handled in
2890 * samba_kdc_message2entry() in case we're
2891 * a global catalog. We'd need to check
2892 * if realm_dn is our own domain and derive
2893 * the dns domain name from realm_dn and check that
2894 * against the routing table or fallback to
2895 * the tdo we found here.
2897 * But for now we don't support multiple domains
2898 * in our forest correctly anyway.
2900 * Just search in our local database.
2902 TALLOC_FREE(frame);
2903 return 0;
2906 ZERO_STRUCTP(entry);
2908 ret = krb5_copy_principal(context, principal,
2909 &entry->principal);
2910 if (ret) {
2911 TALLOC_FREE(frame);
2912 return ret;
2915 upper = strupper_talloc(frame, tdo->domain_name.string);
2916 if (upper == NULL) {
2917 TALLOC_FREE(frame);
2918 return ENOMEM;
2921 ret = smb_krb5_principal_set_realm(context,
2922 entry->principal,
2923 upper);
2924 if (ret) {
2925 TALLOC_FREE(frame);
2926 return ret;
2929 TALLOC_FREE(frame);
2930 return SDB_ERR_WRONG_REALM;
2933 krb5_error_code samba_kdc_fetch(krb5_context context,
2934 struct samba_kdc_db_context *kdc_db_ctx,
2935 krb5_const_principal principal,
2936 unsigned flags,
2937 krb5_kvno kvno,
2938 struct sdb_entry *entry)
2940 krb5_error_code ret = SDB_ERR_NOENTRY;
2941 TALLOC_CTX *mem_ctx;
2943 mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
2944 if (!mem_ctx) {
2945 ret = ENOMEM;
2946 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2947 return ret;
2950 ret = samba_kdc_lookup_realm(context, kdc_db_ctx, mem_ctx,
2951 principal, flags, entry);
2952 if (ret != 0) {
2953 goto done;
2956 ret = SDB_ERR_NOENTRY;
2958 if (flags & SDB_F_GET_CLIENT) {
2959 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
2960 if (ret != SDB_ERR_NOENTRY) goto done;
2962 if (flags & SDB_F_GET_SERVER) {
2963 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
2964 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
2965 if (ret != SDB_ERR_NOENTRY) goto done;
2967 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
2968 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
2969 if (ret != SDB_ERR_NOENTRY) goto done;
2971 if (flags & SDB_F_GET_KRBTGT) {
2972 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
2973 if (ret != SDB_ERR_NOENTRY) goto done;
2976 done:
2977 talloc_free(mem_ctx);
2978 return ret;
2981 struct samba_kdc_seq {
2982 unsigned int index;
2983 unsigned int count;
2984 struct ldb_message **msgs;
2985 struct ldb_dn *realm_dn;
2988 static krb5_error_code samba_kdc_seq(krb5_context context,
2989 struct samba_kdc_db_context *kdc_db_ctx,
2990 struct sdb_entry *entry)
2992 krb5_error_code ret;
2993 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2994 const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
2995 struct ldb_message *msg = NULL;
2996 const char *sAMAccountName = NULL;
2997 krb5_principal principal = NULL;
2998 TALLOC_CTX *mem_ctx;
3000 if (!priv) {
3001 return SDB_ERR_NOENTRY;
3004 mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
3006 if (!mem_ctx) {
3007 ret = ENOMEM;
3008 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
3009 return ret;
3012 while (priv->index < priv->count) {
3013 msg = priv->msgs[priv->index++];
3015 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
3016 if (sAMAccountName != NULL) {
3017 break;
3021 if (sAMAccountName == NULL) {
3022 ret = SDB_ERR_NOENTRY;
3023 goto out;
3026 ret = smb_krb5_make_principal(context, &principal,
3027 realm, sAMAccountName, NULL);
3028 if (ret != 0) {
3029 goto out;
3032 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
3033 principal, SAMBA_KDC_ENT_TYPE_ANY,
3034 SDB_F_ADMIN_DATA|SDB_F_GET_ANY,
3035 0 /* kvno */,
3036 priv->realm_dn, msg, entry);
3038 out:
3039 if (principal != NULL) {
3040 krb5_free_principal(context, principal);
3043 if (ret != 0) {
3044 TALLOC_FREE(priv);
3045 kdc_db_ctx->seq_ctx = NULL;
3046 } else {
3047 talloc_free(mem_ctx);
3050 return ret;
3053 krb5_error_code samba_kdc_firstkey(krb5_context context,
3054 struct samba_kdc_db_context *kdc_db_ctx,
3055 struct sdb_entry *entry)
3057 struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
3058 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
3059 char *realm;
3060 struct ldb_result *res = NULL;
3061 krb5_error_code ret;
3062 TALLOC_CTX *mem_ctx;
3063 int lret;
3065 if (priv) {
3066 TALLOC_FREE(priv);
3067 kdc_db_ctx->seq_ctx = NULL;
3070 priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
3071 if (!priv) {
3072 ret = ENOMEM;
3073 krb5_set_error_message(context, ret, "talloc: out of memory");
3074 return ret;
3077 priv->index = 0;
3078 priv->msgs = NULL;
3079 priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
3080 priv->count = 0;
3082 mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
3084 if (!mem_ctx) {
3085 ret = ENOMEM;
3086 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
3087 TALLOC_FREE(priv);
3088 return ret;
3091 ret = krb5_get_default_realm(context, &realm);
3092 if (ret != 0) {
3093 TALLOC_FREE(priv);
3094 return ret;
3096 krb5_free_default_realm(context, realm);
3098 lret = dsdb_search(ldb_ctx, priv, &res,
3099 priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
3100 DSDB_SEARCH_NO_GLOBAL_CATALOG,
3101 "(objectClass=user)");
3103 if (lret != LDB_SUCCESS) {
3104 TALLOC_FREE(priv);
3105 return SDB_ERR_NOENTRY;
3108 priv->count = res->count;
3109 priv->msgs = talloc_steal(priv, res->msgs);
3110 talloc_free(res);
3112 kdc_db_ctx->seq_ctx = priv;
3114 ret = samba_kdc_seq(context, kdc_db_ctx, entry);
3116 if (ret != 0) {
3117 TALLOC_FREE(priv);
3118 kdc_db_ctx->seq_ctx = NULL;
3119 } else {
3120 talloc_free(mem_ctx);
3122 return ret;
3125 krb5_error_code samba_kdc_nextkey(krb5_context context,
3126 struct samba_kdc_db_context *kdc_db_ctx,
3127 struct sdb_entry *entry)
3129 return samba_kdc_seq(context, kdc_db_ctx, entry);
3132 /* Check if a given entry may delegate or do s4u2self to this target principal
3134 * The safest way to determine 'self' is to check the DB record made at
3135 * the time the principal was presented to the KDC.
3137 krb5_error_code
3138 samba_kdc_check_client_matches_target_service(krb5_context context,
3139 struct samba_kdc_entry *skdc_entry_client,
3140 struct samba_kdc_entry *skdc_entry_server_target)
3142 struct dom_sid *orig_sid;
3143 struct dom_sid *target_sid;
3144 TALLOC_CTX *frame = talloc_stackframe();
3146 orig_sid = samdb_result_dom_sid(frame,
3147 skdc_entry_client->msg,
3148 "objectSid");
3149 target_sid = samdb_result_dom_sid(frame,
3150 skdc_entry_server_target->msg,
3151 "objectSid");
3154 * Allow delegation to the same record (representing a
3155 * principal), even if by a different name. The easy and safe
3156 * way to prove this is by SID comparison
3158 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
3159 talloc_free(frame);
3160 return KRB5KRB_AP_ERR_BADMATCH;
3163 talloc_free(frame);
3164 return 0;
3167 /* Certificates printed by a the Certificate Authority might have a
3168 * slightly different form of the user principal name to that in the
3169 * database. Allow a mismatch where they both refer to the same
3170 * SID */
3172 krb5_error_code
3173 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
3174 struct samba_kdc_db_context *kdc_db_ctx,
3175 struct samba_kdc_entry *skdc_entry,
3176 krb5_const_principal certificate_principal)
3178 krb5_error_code ret;
3179 struct ldb_dn *realm_dn;
3180 struct ldb_message *msg;
3181 struct dom_sid *orig_sid;
3182 struct dom_sid *target_sid;
3183 const char *ms_upn_check_attrs[] = {
3184 "objectSid", NULL
3187 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
3189 if (!mem_ctx) {
3190 ret = ENOMEM;
3191 krb5_set_error_message(context, ret, "samba_kdc_check_pkinit_ms_upn_match: talloc_named() failed!");
3192 return ret;
3195 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
3196 mem_ctx, certificate_principal,
3197 ms_upn_check_attrs, &realm_dn, &msg);
3199 if (ret != 0) {
3200 talloc_free(mem_ctx);
3201 return ret;
3204 orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
3205 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
3207 /* Consider these to be the same principal, even if by a different
3208 * name. The easy and safe way to prove this is by SID
3209 * comparison */
3210 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
3211 talloc_free(mem_ctx);
3212 #if defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
3213 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
3214 #else /* Heimdal (where this is an enum) */
3215 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
3216 #endif
3219 talloc_free(mem_ctx);
3220 return ret;
3224 * Check if a given entry may delegate to this target principal
3225 * with S4U2Proxy.
3227 krb5_error_code
3228 samba_kdc_check_s4u2proxy(krb5_context context,
3229 struct samba_kdc_db_context *kdc_db_ctx,
3230 struct samba_kdc_entry *skdc_entry,
3231 krb5_const_principal target_principal)
3233 krb5_error_code ret;
3234 char *tmp = NULL;
3235 const char *client_dn = NULL;
3236 const char *target_principal_name = NULL;
3237 struct ldb_message_element *el;
3238 struct ldb_val val;
3239 unsigned int i;
3240 bool found = false;
3242 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
3244 if (!mem_ctx) {
3245 ret = ENOMEM;
3246 krb5_set_error_message(context, ret,
3247 "samba_kdc_check_s4u2proxy:"
3248 " talloc_named() failed!");
3249 return ret;
3252 client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
3253 if (!client_dn) {
3254 if (errno == 0) {
3255 errno = ENOMEM;
3257 ret = errno;
3258 krb5_set_error_message(context, ret,
3259 "samba_kdc_check_s4u2proxy:"
3260 " ldb_dn_get_linearized() failed!");
3261 talloc_free(mem_ctx);
3262 return ret;
3265 el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
3266 if (el == NULL) {
3267 ret = ENOENT;
3268 goto bad_option;
3270 SMB_ASSERT(el->num_values != 0);
3273 * This is the Microsoft forwardable flag behavior.
3275 * If the proxy (target) principal is NULL, and we have any authorized
3276 * delegation target, allow to forward.
3278 if (target_principal == NULL) {
3279 talloc_free(mem_ctx);
3280 return 0;
3285 * The main heimdal code already checked that the target_principal
3286 * belongs to the same realm as the client.
3288 * So we just need the principal without the realm,
3289 * as that is what is configured in the "msDS-AllowedToDelegateTo"
3290 * attribute.
3292 ret = krb5_unparse_name_flags(context, target_principal,
3293 KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
3294 if (ret) {
3295 talloc_free(mem_ctx);
3296 krb5_set_error_message(context, ret,
3297 "samba_kdc_check_s4u2proxy:"
3298 " krb5_unparse_name() failed!");
3299 return ret;
3301 DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
3302 client_dn, tmp));
3304 target_principal_name = talloc_strdup(mem_ctx, tmp);
3305 SAFE_FREE(tmp);
3306 if (target_principal_name == NULL) {
3307 ret = ENOMEM;
3308 krb5_set_error_message(context, ret,
3309 "samba_kdc_check_s4u2proxy:"
3310 " talloc_strdup() failed!");
3311 talloc_free(mem_ctx);
3312 return ret;
3315 val = data_blob_string_const(target_principal_name);
3317 for (i=0; i<el->num_values; i++) {
3318 struct ldb_val *val1 = &val;
3319 struct ldb_val *val2 = &el->values[i];
3320 int cmp;
3322 if (val1->length != val2->length) {
3323 continue;
3326 cmp = strncasecmp((const char *)val1->data,
3327 (const char *)val2->data,
3328 val1->length);
3329 if (cmp != 0) {
3330 continue;
3333 found = true;
3334 break;
3337 if (!found) {
3338 ret = ENOENT;
3339 goto bad_option;
3342 DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
3343 client_dn, target_principal_name));
3344 talloc_free(mem_ctx);
3345 return 0;
3347 bad_option:
3348 krb5_set_error_message(context, ret,
3349 "samba_kdc_check_s4u2proxy: client[%s] "
3350 "not allowed for delegation to target[%s]",
3351 client_dn,
3352 target_principal_name);
3353 talloc_free(mem_ctx);
3354 return KRB5KDC_ERR_BADOPTION;
3358 * This method is called for S4U2Proxy requests and implements the
3359 * resource-based constrained delegation variant, which can support
3360 * cross-realm delegation.
3362 krb5_error_code samba_kdc_check_s4u2proxy_rbcd(
3363 krb5_context context,
3364 struct samba_kdc_db_context *kdc_db_ctx,
3365 krb5_const_principal client_principal,
3366 krb5_const_principal server_principal,
3367 krb5_const_pac header_pac,
3368 struct samba_kdc_entry *proxy_skdc_entry)
3370 krb5_error_code code;
3371 enum ndr_err_code ndr_err;
3372 char *client_name = NULL;
3373 char *server_name = NULL;
3374 const char *proxy_dn = NULL;
3375 const DATA_BLOB *data = NULL;
3376 struct security_descriptor *rbcd_security_descriptor = NULL;
3377 struct auth_user_info_dc *user_info_dc = NULL;
3378 struct security_token *security_token = NULL;
3379 uint32_t session_info_flags =
3380 AUTH_SESSION_INFO_DEFAULT_GROUPS |
3381 AUTH_SESSION_INFO_SIMPLE_PRIVILEGES;
3383 * Testing shows that although Windows grants SEC_ADS_GENERIC_ALL access
3384 * in security descriptors it creates for RBCD, its KDC only requires
3385 * SEC_ADS_CONTROL_ACCESS for the access check to succeed.
3387 uint32_t access_desired = SEC_ADS_CONTROL_ACCESS;
3388 uint32_t access_granted = 0;
3389 NTSTATUS nt_status;
3390 TALLOC_CTX *mem_ctx = NULL;
3392 mem_ctx = talloc_named(kdc_db_ctx,
3394 "samba_kdc_check_s4u2proxy_rbcd");
3395 if (mem_ctx == NULL) {
3396 errno = ENOMEM;
3397 code = errno;
3399 return code;
3402 proxy_dn = ldb_dn_get_linearized(proxy_skdc_entry->msg->dn);
3403 if (proxy_dn == NULL) {
3404 DBG_ERR("ldb_dn_get_linearized failed for proxy_dn!\n");
3405 if (errno == 0) {
3406 errno = ENOMEM;
3408 code = errno;
3410 goto out;
3413 rbcd_security_descriptor = talloc_zero(mem_ctx,
3414 struct security_descriptor);
3415 if (rbcd_security_descriptor == NULL) {
3416 errno = ENOMEM;
3417 code = errno;
3419 goto out;
3422 code = krb5_unparse_name_flags(context,
3423 client_principal,
3424 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
3425 &client_name);
3426 if (code != 0) {
3427 DBG_ERR("Unable to parse client_principal!\n");
3428 goto out;
3431 code = krb5_unparse_name_flags(context,
3432 server_principal,
3433 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
3434 &server_name);
3435 if (code != 0) {
3436 DBG_ERR("Unable to parse server_principal!\n");
3437 goto out;
3440 DBG_INFO("Check delegation from client[%s] to server[%s] via "
3441 "proxy[%s]\n",
3442 client_name,
3443 server_name,
3444 proxy_dn);
3446 code = kerberos_pac_to_user_info_dc(mem_ctx,
3447 header_pac,
3448 context,
3449 &user_info_dc,
3450 AUTH_INCLUDE_RESOURCE_GROUPS,
3451 NULL,
3452 NULL,
3453 NULL);
3454 if (code != 0) {
3455 goto out;
3458 if (!(user_info_dc->info->user_flags & NETLOGON_GUEST)) {
3459 session_info_flags |= AUTH_SESSION_INFO_AUTHENTICATED;
3462 nt_status = auth_generate_security_token(mem_ctx,
3463 kdc_db_ctx->lp_ctx,
3464 kdc_db_ctx->samdb,
3465 user_info_dc,
3466 session_info_flags,
3467 &security_token);
3468 if (!NT_STATUS_IS_OK(nt_status)) {
3469 code = map_errno_from_nt_status(nt_status);
3470 goto out;
3473 data = ldb_msg_find_ldb_val(proxy_skdc_entry->msg,
3474 "msDS-AllowedToActOnBehalfOfOtherIdentity");
3475 if (data == NULL) {
3476 DBG_WARNING("Could not find security descriptor "
3477 "msDS-AllowedToActOnBehalfOfOtherIdentity in "
3478 "proxy[%s]\n",
3479 proxy_dn);
3480 code = KRB5KDC_ERR_BADOPTION;
3481 goto out;
3484 ndr_err = ndr_pull_struct_blob(
3485 data,
3486 mem_ctx,
3487 rbcd_security_descriptor,
3488 (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
3489 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3490 errno = ndr_map_error2errno(ndr_err);
3491 DBG_ERR("Failed to unmarshall "
3492 "msDS-AllowedToActOnBehalfOfOtherIdentity "
3493 "security descriptor of proxy[%s]\n",
3494 proxy_dn);
3495 code = KRB5KDC_ERR_BADOPTION;
3496 goto out;
3499 if (DEBUGLEVEL >= 10) {
3500 NDR_PRINT_DEBUG(security_token, security_token);
3501 NDR_PRINT_DEBUG(security_descriptor, rbcd_security_descriptor);
3504 nt_status = sec_access_check_ds(rbcd_security_descriptor,
3505 security_token,
3506 access_desired,
3507 &access_granted,
3508 NULL,
3509 NULL);
3511 if (!NT_STATUS_IS_OK(nt_status)) {
3512 DBG_WARNING("RBCD: sec_access_check_ds(access_desired=%#08x, "
3513 "access_granted:%#08x) failed with: %s\n",
3514 access_desired,
3515 access_granted,
3516 nt_errstr(nt_status));
3518 code = KRB5KDC_ERR_BADOPTION;
3519 goto out;
3522 DBG_NOTICE("RBCD: Access granted for client[%s]\n", client_name);
3524 code = 0;
3525 out:
3526 SAFE_FREE(client_name);
3527 SAFE_FREE(server_name);
3529 TALLOC_FREE(mem_ctx);
3530 return code;
3533 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
3534 struct samba_kdc_db_context **kdc_db_ctx_out)
3536 int ldb_ret;
3537 struct ldb_message *msg;
3538 struct auth_session_info *session_info;
3539 struct samba_kdc_db_context *kdc_db_ctx;
3540 /* The idea here is very simple. Using Kerberos to
3541 * authenticate the KDC to the LDAP server is highly likely to
3542 * be circular.
3544 * In future we may set this up to use EXERNAL and SSL
3545 * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
3548 kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
3549 if (kdc_db_ctx == NULL) {
3550 return NT_STATUS_NO_MEMORY;
3552 kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
3553 kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
3554 kdc_db_ctx->msg_ctx = base_ctx->msg_ctx;
3556 /* get default kdc policy */
3557 lpcfg_default_kdc_policy(mem_ctx,
3558 base_ctx->lp_ctx,
3559 &kdc_db_ctx->policy.svc_tkt_lifetime,
3560 &kdc_db_ctx->policy.usr_tkt_lifetime,
3561 &kdc_db_ctx->policy.renewal_lifetime);
3563 session_info = system_session(kdc_db_ctx->lp_ctx);
3564 if (session_info == NULL) {
3565 talloc_free(kdc_db_ctx);
3566 return NT_STATUS_INTERNAL_ERROR;
3569 /* Setup the link to LDB */
3570 kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx,
3571 base_ctx->ev_ctx,
3572 base_ctx->lp_ctx,
3573 session_info,
3574 NULL,
3576 if (kdc_db_ctx->samdb == NULL) {
3577 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
3578 talloc_free(kdc_db_ctx);
3579 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3582 /* Find out our own krbtgt kvno */
3583 ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
3584 if (ldb_ret != LDB_SUCCESS) {
3585 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
3586 ldb_errstring(kdc_db_ctx->samdb)));
3587 talloc_free(kdc_db_ctx);
3588 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3590 if (kdc_db_ctx->rodc) {
3591 int my_krbtgt_number;
3592 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
3593 struct ldb_dn *account_dn;
3594 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
3595 if (!server_dn) {
3596 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
3597 ldb_errstring(kdc_db_ctx->samdb)));
3598 talloc_free(kdc_db_ctx);
3599 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3602 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
3603 "serverReference", &account_dn);
3604 if (ldb_ret != LDB_SUCCESS) {
3605 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
3606 ldb_errstring(kdc_db_ctx->samdb)));
3607 talloc_free(kdc_db_ctx);
3608 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3611 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
3612 "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
3613 talloc_free(account_dn);
3614 if (ldb_ret != LDB_SUCCESS) {
3615 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
3616 ldb_errstring(kdc_db_ctx->samdb)));
3617 talloc_free(kdc_db_ctx);
3618 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3621 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3622 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
3623 secondary_keytab,
3624 DSDB_SEARCH_NO_GLOBAL_CATALOG,
3625 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
3626 if (ldb_ret != LDB_SUCCESS) {
3627 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
3628 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3629 ldb_errstring(kdc_db_ctx->samdb),
3630 ldb_strerror(ldb_ret)));
3631 talloc_free(kdc_db_ctx);
3632 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3634 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
3635 if (my_krbtgt_number == -1) {
3636 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
3637 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3638 my_krbtgt_number));
3639 talloc_free(kdc_db_ctx);
3640 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3642 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
3644 } else {
3645 kdc_db_ctx->my_krbtgt_number = 0;
3646 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3647 &msg,
3648 ldb_get_default_basedn(kdc_db_ctx->samdb),
3649 LDB_SCOPE_SUBTREE,
3650 krbtgt_attrs,
3651 DSDB_SEARCH_NO_GLOBAL_CATALOG,
3652 "(&(objectClass=user)(samAccountName=krbtgt))");
3654 if (ldb_ret != LDB_SUCCESS) {
3655 DEBUG(1, ("samba_kdc_setup_db_ctx: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
3656 talloc_free(kdc_db_ctx);
3657 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3659 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
3660 kdc_db_ctx->my_krbtgt_number = 0;
3661 talloc_free(msg);
3663 *kdc_db_ctx_out = kdc_db_ctx;
3664 return NT_STATUS_OK;
3667 krb5_error_code dsdb_extract_aes_256_key(krb5_context context,
3668 TALLOC_CTX *mem_ctx,
3669 const struct ldb_message *msg,
3670 uint32_t user_account_control,
3671 const uint32_t *kvno,
3672 uint32_t *kvno_out,
3673 DATA_BLOB *aes_256_key,
3674 DATA_BLOB *salt)
3676 krb5_error_code krb5_ret;
3677 uint32_t supported_enctypes;
3678 unsigned flags = SDB_F_GET_CLIENT;
3679 struct sdb_entry sentry = {};
3681 if (kvno != NULL) {
3682 flags |= SDB_F_KVNO_SPECIFIED;
3685 krb5_ret = samba_kdc_message2entry_keys(context,
3686 mem_ctx,
3687 msg,
3688 false, /* is_krbtgt */
3689 false, /* is_rodc */
3690 user_account_control,
3691 SAMBA_KDC_ENT_TYPE_CLIENT,
3692 flags,
3693 (kvno != NULL) ? *kvno : 0,
3694 &sentry,
3695 ENC_HMAC_SHA1_96_AES256,
3696 &supported_enctypes);
3697 if (krb5_ret != 0) {
3698 DBG_ERR("Failed to parse supplementalCredentials "
3699 "of %s with %s kvno using "
3700 "ENCTYPE_HMAC_SHA1_96_AES256 "
3701 "Kerberos Key: %s\n",
3702 ldb_dn_get_linearized(msg->dn),
3703 (kvno != NULL) ? "previous" : "current",
3704 krb5_get_error_message(context,
3705 krb5_ret));
3706 return krb5_ret;
3709 if ((supported_enctypes & ENC_HMAC_SHA1_96_AES256) == 0 ||
3710 sentry.keys.len != 1) {
3711 DBG_INFO("Failed to find a ENCTYPE_HMAC_SHA1_96_AES256 "
3712 "key in supplementalCredentials "
3713 "of %s at KVNO %u (got %u keys, expected 1)\n",
3714 ldb_dn_get_linearized(msg->dn),
3715 sentry.kvno,
3716 sentry.keys.len);
3717 sdb_entry_free(&sentry);
3718 return ENOENT;
3721 if (sentry.keys.val[0].salt == NULL) {
3722 DBG_INFO("Failed to find a salt in "
3723 "supplementalCredentials "
3724 "of %s at KVNO %u\n",
3725 ldb_dn_get_linearized(msg->dn),
3726 sentry.kvno);
3727 sdb_entry_free(&sentry);
3728 return ENOENT;
3731 if (aes_256_key != NULL) {
3732 *aes_256_key = data_blob_talloc(mem_ctx,
3733 KRB5_KEY_DATA(&sentry.keys.val[0].key),
3734 KRB5_KEY_LENGTH(&sentry.keys.val[0].key));
3735 if (aes_256_key->data == NULL) {
3736 sdb_entry_free(&sentry);
3737 return ENOMEM;
3739 talloc_keep_secret(aes_256_key->data);
3742 if (salt != NULL) {
3743 *salt = data_blob_talloc(mem_ctx,
3744 sentry.keys.val[0].salt->salt.data,
3745 sentry.keys.val[0].salt->salt.length);
3746 if (salt->data == NULL) {
3747 sdb_entry_free(&sentry);
3748 return ENOMEM;
3752 if (kvno_out != NULL) {
3753 *kvno_out = sentry.kvno;
3756 sdb_entry_free(&sentry);
3758 return 0;