s4:kdc: only pass sdb_entry to samba_kdc_message2entry()
[Samba.git] / source4 / kdc / db-glue.c
blob982f1ed62256d8c145ab1e6509332f464cea2200
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/sdb.h"
38 #include "kdc/samba_kdc.h"
39 #include "kdc/db-glue.h"
40 #include "kdc/pac-glue.h"
41 #include "librpc/gen_ndr/ndr_irpc_c.h"
42 #include "lib/messaging/irpc.h"
44 #undef strcasecmp
45 #undef strncasecmp
47 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
48 ((uint16_t)(((uint32_t)kvno) >> 16))
50 #define SAMBA_KVNO_GET_VALUE(kvno) \
51 ((uint16_t)(((uint32_t)kvno) & 0xFFFF))
53 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
54 ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
55 ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
57 enum samba_kdc_ent_type
58 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
59 SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
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_PASSWORD_NOTREQD) {
198 flags.invalid = 1;
202 UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
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 struct samba_kdc_db_context *kdc_db_ctx,
340 const struct ldb_val *secretbuffer,
341 bool is_protected,
342 struct sdb_keys *keys)
344 uint32_t supported_enctypes = ENC_ALL_TYPES;
345 uint16_t allocated_keys = 0;
346 int ret;
348 allocated_keys = 3;
349 keys->len = 0;
350 keys->val = calloc(allocated_keys, sizeof(struct sdb_key));
351 if (keys->val == NULL) {
352 memset(secretbuffer->data, 0, secretbuffer->length);
353 ret = ENOMEM;
354 goto out;
357 if (is_protected) {
358 supported_enctypes &= ~ENC_RC4_HMAC_MD5;
361 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
362 struct sdb_key key = {};
364 ret = smb_krb5_keyblock_init_contents(context,
365 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
366 secretbuffer->data,
367 MIN(secretbuffer->length, 32),
368 &key.key);
369 if (ret) {
370 memset(secretbuffer->data, 0, secretbuffer->length);
371 goto out;
374 keys->val[keys->len] = key;
375 keys->len++;
378 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
379 struct sdb_key key = {};
381 ret = smb_krb5_keyblock_init_contents(context,
382 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
383 secretbuffer->data,
384 MIN(secretbuffer->length, 16),
385 &key.key);
386 if (ret) {
387 memset(secretbuffer->data, 0, secretbuffer->length);
388 goto out;
391 keys->val[keys->len] = key;
392 keys->len++;
395 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
396 struct sdb_key key = {};
398 ret = smb_krb5_keyblock_init_contents(context,
399 ENCTYPE_ARCFOUR_HMAC,
400 secretbuffer->data,
401 MIN(secretbuffer->length, 16),
402 &key.key);
403 if (ret) {
404 memset(secretbuffer->data, 0, secretbuffer->length);
405 goto out;
408 keys->val[keys->len] = key;
409 keys->len++;
411 ret = 0;
412 out:
413 return ret;
417 static int samba_kdc_set_random_keys(krb5_context context,
418 struct samba_kdc_db_context *kdc_db_ctx,
419 struct sdb_keys *keys,
420 bool is_protected)
422 struct ldb_val secret_val;
423 uint8_t secretbuffer[32];
426 * Fake keys until we have a better way to reject
427 * non-pkinit requests.
429 * We just need to indicate which encryption types are
430 * supported.
432 generate_secret_buffer(secretbuffer, sizeof(secretbuffer));
434 secret_val = data_blob_const(secretbuffer,
435 sizeof(secretbuffer));
436 return samba_kdc_set_fixed_keys(context, kdc_db_ctx,
437 &secret_val,
438 is_protected,
439 keys);
442 struct samba_kdc_user_keys {
443 struct sdb_keys *skeys;
444 uint32_t kvno;
445 uint32_t *returned_kvno;
446 uint32_t supported_enctypes;
447 uint32_t *available_enctypes;
448 const struct samr_Password *nthash;
449 const char *salt_string;
450 uint16_t num_pkeys;
451 const struct package_PrimaryKerberosKey4 *pkeys;
454 static krb5_error_code samba_kdc_fill_user_keys(krb5_context context,
455 struct samba_kdc_user_keys *p)
458 * Make sure we'll never reveal DES keys
460 uint32_t supported_enctypes = p->supported_enctypes & ENC_ALL_TYPES;
461 uint32_t _available_enctypes = 0;
462 uint32_t *available_enctypes = p->available_enctypes;
463 uint32_t _returned_kvno = 0;
464 uint32_t *returned_kvno = p->returned_kvno;
465 uint32_t num_pkeys = p->num_pkeys;
466 uint32_t allocated_keys = num_pkeys;
467 uint32_t i;
468 int ret;
470 if (available_enctypes == NULL) {
471 available_enctypes = &_available_enctypes;
474 *available_enctypes = 0;
476 if (returned_kvno == NULL) {
477 returned_kvno = &_returned_kvno;
480 *returned_kvno = p->kvno;
482 if (p->nthash != NULL) {
483 allocated_keys += 1;
486 allocated_keys = MAX(1, allocated_keys);
488 /* allocate space to decode into */
489 p->skeys->len = 0;
490 p->skeys->val = calloc(allocated_keys, sizeof(struct sdb_key));
491 if (p->skeys->val == NULL) {
492 return ENOMEM;
495 for (i=0; i < num_pkeys; i++) {
496 struct sdb_key key = {};
497 uint32_t enctype_bit;
499 if (p->pkeys[i].value == NULL) {
500 continue;
503 enctype_bit = kerberos_enctype_to_bitmap(p->pkeys[i].keytype);
504 if (!(enctype_bit & supported_enctypes)) {
505 continue;
508 if (p->salt_string != NULL) {
509 DATA_BLOB salt;
511 salt = data_blob_string_const(p->salt_string);
513 key.salt = calloc(1, sizeof(*key.salt));
514 if (key.salt == NULL) {
515 ret = ENOMEM;
516 goto fail;
519 key.salt->type = KRB5_PW_SALT;
521 ret = smb_krb5_copy_data_contents(&key.salt->salt,
522 salt.data,
523 salt.length);
524 if (ret) {
525 ZERO_STRUCTP(key.salt);
526 sdb_key_free(&key);
527 goto fail;
531 ret = smb_krb5_keyblock_init_contents(context,
532 p->pkeys[i].keytype,
533 p->pkeys[i].value->data,
534 p->pkeys[i].value->length,
535 &key.key);
536 if (ret == 0) {
537 p->skeys->val[p->skeys->len++] = key;
538 *available_enctypes |= enctype_bit;
539 continue;
541 ZERO_STRUCT(key.key);
542 sdb_key_free(&key);
543 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
544 DEBUG(2,("Unsupported keytype ignored - type %u\n",
545 p->pkeys[i].keytype));
546 ret = 0;
547 continue;
550 goto fail;
553 if (p->nthash != NULL && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
554 struct sdb_key key = {};
556 ret = smb_krb5_keyblock_init_contents(context,
557 ENCTYPE_ARCFOUR_HMAC,
558 p->nthash->hash,
559 sizeof(p->nthash->hash),
560 &key.key);
561 if (ret == 0) {
562 p->skeys->val[p->skeys->len++] = key;
564 *available_enctypes |= ENC_RC4_HMAC_MD5;
565 } else if (ret == KRB5_PROG_ETYPE_NOSUPP) {
566 DEBUG(2,("Unsupported keytype ignored - type %u\n",
567 ENCTYPE_ARCFOUR_HMAC));
568 ret = 0;
570 if (ret != 0) {
571 goto fail;
575 samba_kdc_sort_keys(p->skeys);
577 return 0;
578 fail:
579 sdb_keys_free(p->skeys);
580 return ret;
583 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
584 struct samba_kdc_db_context *kdc_db_ctx,
585 TALLOC_CTX *mem_ctx,
586 struct ldb_message *msg,
587 uint32_t rid,
588 bool is_rodc,
589 uint32_t userAccountControl,
590 enum samba_kdc_ent_type ent_type,
591 struct sdb_entry *entry,
592 bool is_protected,
593 uint32_t *supported_enctypes_out)
595 krb5_error_code ret = 0;
596 enum ndr_err_code ndr_err;
597 struct samr_Password *hash;
598 const struct ldb_val *sc_val;
599 struct supplementalCredentialsBlob scb;
600 struct supplementalCredentialsPackage *scpk = NULL;
601 struct package_PrimaryKerberosBlob _pkb;
602 struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
603 bool is_krbtgt = false;
604 int krbtgt_number = 0;
605 uint32_t current_kvno;
606 uint32_t returned_kvno = 0;
607 uint16_t i;
608 struct samba_kdc_user_keys keys = { .num_pkeys = 0, };
609 uint32_t available_enctypes = 0;
610 uint32_t supported_enctypes
611 = ldb_msg_find_attr_as_uint(msg,
612 "msDS-SupportedEncryptionTypes",
614 *supported_enctypes_out = 0;
616 if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
617 bool enable_fast;
619 /* KDCs (and KDCs on RODCs) use AES */
620 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
621 is_krbtgt = true;
623 enable_fast = lpcfg_kdc_enable_fast(kdc_db_ctx->lp_ctx);
624 if (enable_fast) {
625 supported_enctypes |= ENC_FAST_SUPPORTED;
627 } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
628 /* DCs and RODCs comptuer accounts use AES */
629 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
630 } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
631 (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
632 /* for AS-REQ the client chooses the enc types it
633 * supports, and this will vary between computers a
634 * user logs in from.
636 * likewise for 'any' return as much as is supported,
637 * to export into a keytab */
638 supported_enctypes = ENC_ALL_TYPES;
641 /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
642 if (userAccountControl & UF_USE_DES_KEY_ONLY) {
643 supported_enctypes = 0;
644 } else {
645 /* Otherwise, add in the default enc types */
646 supported_enctypes |= ENC_RC4_HMAC_MD5;
649 if (is_protected) {
650 supported_enctypes &= ~ENC_RC4_HMAC_MD5;
653 /* Is this the krbtgt or a RODC krbtgt */
654 if (is_rodc) {
655 krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
657 if (krbtgt_number == -1) {
658 return EINVAL;
660 if (krbtgt_number == 0) {
661 return EINVAL;
665 if ((ent_type == SAMBA_KDC_ENT_TYPE_CLIENT)
666 && (userAccountControl & UF_SMARTCARD_REQUIRED)) {
667 ret = samba_kdc_set_random_keys(context,
668 kdc_db_ctx,
669 &entry->keys,
670 is_protected);
672 *supported_enctypes_out = supported_enctypes;
674 goto out;
677 current_kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
678 if (is_krbtgt) {
680 * Even for the main krbtgt account
681 * we have to strictly split the kvno into
682 * two 16-bit parts and the upper 16-bit
683 * need to be all zero, even if
684 * the msDS-KeyVersionNumber has a value
685 * larger than 65535.
687 * See https://bugzilla.samba.org/show_bug.cgi?id=14951
689 current_kvno = SAMBA_KVNO_GET_VALUE(current_kvno);
692 /* Get keys from the db */
694 hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
695 sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
697 /* supplementalCredentials if present */
698 if (sc_val) {
699 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
700 (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
701 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
702 dump_data(0, sc_val->data, sc_val->length);
703 ret = EINVAL;
704 goto out;
707 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
708 if (scb.sub.num_packages != 0) {
709 NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
710 ret = EINVAL;
711 goto out;
715 for (i=0; i < scb.sub.num_packages; i++) {
716 if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
717 scpk = &scb.sub.packages[i];
718 if (!scpk->data || !scpk->data[0]) {
719 scpk = NULL;
720 continue;
722 break;
727 * Primary:Kerberos-Newer-Keys element
728 * of supplementalCredentials
730 * The legacy Primary:Kerberos only contains
731 * single DES keys, which are completely ignored
732 * now.
734 if (scpk) {
735 DATA_BLOB blob;
737 blob = strhex_to_data_blob(mem_ctx, scpk->data);
738 if (!blob.data) {
739 ret = ENOMEM;
740 goto out;
743 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
744 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
745 (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
746 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
747 ret = EINVAL;
748 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
749 krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
750 goto out;
753 if (_pkb.version != 4) {
754 ret = EINVAL;
755 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
756 krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
757 goto out;
760 pkb4 = &_pkb.ctr.ctr4;
763 keys = (struct samba_kdc_user_keys) {
764 .kvno = current_kvno,
765 .supported_enctypes = supported_enctypes,
766 .nthash = hash,
767 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
768 .num_pkeys = pkb4 != NULL ? pkb4->num_keys : 0,
769 .pkeys = pkb4 != NULL ? pkb4->keys : NULL,
770 .skeys = &entry->keys,
771 .available_enctypes = &available_enctypes,
772 .returned_kvno = &returned_kvno,
775 if (keys.skeys != NULL) {
776 ret = samba_kdc_fill_user_keys(context, &keys);
777 if (ret != 0) {
778 goto out;
782 *supported_enctypes_out |= available_enctypes;
784 /* Set FAST support bits */
785 *supported_enctypes_out |= supported_enctypes & (ENC_FAST_SUPPORTED |
786 ENC_COMPOUND_IDENTITY_SUPPORTED |
787 ENC_CLAIMS_SUPPORTED);
789 if (is_krbtgt) {
791 * Even for the main krbtgt account
792 * we have to strictly split the kvno into
793 * two 16-bit parts and the upper 16-bit
794 * need to be all zero, even if
795 * the msDS-KeyVersionNumber has a value
796 * larger than 65535.
798 * See https://bugzilla.samba.org/show_bug.cgi?id=14951
800 returned_kvno = SAMBA_KVNO_AND_KRBTGT(returned_kvno, krbtgt_number);
802 entry->kvno = returned_kvno;
804 if (entry->keys.len == 0) {
805 if (kdc_db_ctx->rodc) {
806 /* We are on an RODC, but don't have keys for this account. Signal this to the caller */
807 auth_sam_trigger_repl_secret(kdc_db_ctx, kdc_db_ctx->msg_ctx,
808 kdc_db_ctx->ev_ctx, msg->dn);
809 return SDB_ERR_NOT_FOUND_HERE;
813 * oh, no password. Apparently (comment in
814 * hdb-ldap.c) this violates the ASN.1, but this
815 * allows an entry with no keys (yet).
819 out:
820 return ret;
823 static int principal_comp_strcmp_int(krb5_context context,
824 krb5_const_principal principal,
825 unsigned int component,
826 const char *string,
827 bool do_strcasecmp)
829 const char *p;
830 size_t len;
832 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
833 p = krb5_principal_get_comp_string(context, principal, component);
834 if (p == NULL) {
835 return -1;
837 len = strlen(p);
838 #else
839 krb5_data *d;
840 if (component >= krb5_princ_size(context, principal)) {
841 return -1;
844 d = krb5_princ_component(context, principal, component);
845 if (d == NULL) {
846 return -1;
849 p = d->data;
850 len = d->length;
851 #endif
852 if (do_strcasecmp) {
853 return strncasecmp(p, string, len);
854 } else {
855 return strncmp(p, string, len);
859 static int principal_comp_strcasecmp(krb5_context context,
860 krb5_const_principal principal,
861 unsigned int component,
862 const char *string)
864 return principal_comp_strcmp_int(context, principal,
865 component, string, true);
868 static int principal_comp_strcmp(krb5_context context,
869 krb5_const_principal principal,
870 unsigned int component,
871 const char *string)
873 return principal_comp_strcmp_int(context, principal,
874 component, string, false);
878 * Construct an hdb_entry from a directory entry.
880 static krb5_error_code samba_kdc_message2entry(krb5_context context,
881 struct samba_kdc_db_context *kdc_db_ctx,
882 TALLOC_CTX *mem_ctx,
883 krb5_const_principal principal,
884 enum samba_kdc_ent_type ent_type,
885 unsigned flags,
886 struct ldb_dn *realm_dn,
887 struct ldb_message *msg,
888 struct sdb_entry *entry)
890 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
891 uint32_t userAccountControl;
892 uint32_t msDS_User_Account_Control_Computed;
893 krb5_error_code ret = 0;
894 krb5_boolean is_computer = FALSE;
895 struct samba_kdc_entry *p;
896 uint32_t supported_enctypes = 0;
897 NTTIME acct_expiry;
898 NTSTATUS status;
899 bool protected_user = false;
900 uint32_t rid;
901 bool is_rodc = false;
902 struct ldb_message_element *objectclasses;
903 struct ldb_val computer_val = data_blob_string_const("computer");
904 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
906 ZERO_STRUCTP(entry);
908 if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
909 is_rodc = true;
912 if (!samAccountName) {
913 ret = ENOENT;
914 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
915 goto out;
918 objectclasses = ldb_msg_find_element(msg, "objectClass");
920 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
921 is_computer = TRUE;
924 p = talloc_zero(mem_ctx, struct samba_kdc_entry);
925 if (!p) {
926 ret = ENOMEM;
927 goto out;
930 p->is_rodc = is_rodc;
931 p->kdc_db_ctx = kdc_db_ctx;
932 p->realm_dn = talloc_reference(p, realm_dn);
933 if (!p->realm_dn) {
934 ret = ENOMEM;
935 goto out;
938 talloc_set_destructor(p, samba_kdc_entry_destructor);
940 entry->skdc_entry = p;
942 userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
944 msDS_User_Account_Control_Computed
945 = ldb_msg_find_attr_as_uint(msg,
946 "msDS-User-Account-Control-Computed",
947 UF_ACCOUNTDISABLE);
950 * This brings in the lockout flag, block the account if not
951 * found. We need the weird UF_ACCOUNTDISABLE check because
952 * we do not want to fail open if the value is not returned,
953 * but 0 is a valid value (all OK)
955 if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
956 ret = EINVAL;
957 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
958 "no msDS-User-Account-Control-Computed present");
959 goto out;
960 } else {
961 userAccountControl |= msDS_User_Account_Control_Computed;
965 * If we are set to canonicalize, we get back the fixed UPPER
966 * case realm, and the real username (ie matching LDAP
967 * samAccountName)
969 * Otherwise, if we are set to enterprise, we
970 * get back the whole principal as-sent
972 * Finally, if we are not set to canonicalize, we get back the
973 * fixed UPPER case realm, but the as-sent username
976 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
977 p->is_krbtgt = true;
979 if (flags & (SDB_F_CANON|SDB_F_FORCE_CANON)) {
981 * When requested to do so, ensure that the
982 * both realm values in the principal are set
983 * to the upper case, canonical realm
985 ret = smb_krb5_make_principal(context, &entry->principal,
986 lpcfg_realm(lp_ctx), "krbtgt",
987 lpcfg_realm(lp_ctx), NULL);
988 if (ret) {
989 krb5_clear_error_message(context);
990 goto out;
992 smb_krb5_principal_set_type(context, entry->principal, KRB5_NT_SRV_INST);
993 } else {
994 ret = krb5_copy_principal(context, principal, &entry->principal);
995 if (ret) {
996 krb5_clear_error_message(context);
997 goto out;
1000 * this appears to be required regardless of
1001 * the canonicalize flag from the client
1003 ret = smb_krb5_principal_set_realm(context, entry->principal, lpcfg_realm(lp_ctx));
1004 if (ret) {
1005 krb5_clear_error_message(context);
1006 goto out;
1010 } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
1011 ret = smb_krb5_make_principal(context, &entry->principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
1012 if (ret) {
1013 krb5_clear_error_message(context);
1014 goto out;
1016 } else if ((flags & SDB_F_FORCE_CANON) ||
1017 ((flags & SDB_F_CANON) && (flags & SDB_F_FOR_AS_REQ))) {
1019 * SDB_F_CANON maps from the canonicalize flag in the
1020 * packet, and has a different meaning between AS-REQ
1021 * and TGS-REQ. We only change the principal in the AS-REQ case
1023 * The SDB_F_FORCE_CANON if for new MIT KDC code that wants
1024 * the canonical name in all lookups, and takes care to
1025 * canonicalize only when appropriate.
1027 ret = smb_krb5_make_principal(context, &entry->principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
1028 if (ret) {
1029 krb5_clear_error_message(context);
1030 goto out;
1032 } else {
1033 ret = krb5_copy_principal(context, principal, &entry->principal);
1034 if (ret) {
1035 krb5_clear_error_message(context);
1036 goto out;
1039 /* While we have copied the client principal, tests
1040 * show that Win2k3 returns the 'corrected' realm, not
1041 * the client-specified realm. This code attempts to
1042 * replace the client principal's realm with the one
1043 * we determine from our records */
1045 /* this has to be with malloc() */
1046 ret = smb_krb5_principal_set_realm(context, entry->principal, lpcfg_realm(lp_ctx));
1047 if (ret) {
1048 krb5_clear_error_message(context);
1049 goto out;
1053 /* First try and figure out the flags based on the userAccountControl */
1054 entry->flags = uf2SDBFlags(context, userAccountControl, ent_type);
1057 * Take control of the returned principal here, rather than
1058 * allowing the Heimdal code to do it as we have specific
1059 * behaviour around the forced realm to honour
1061 entry->flags.force_canonicalize = true;
1063 /* Windows 2008 seems to enforce this (very sensible) rule by
1064 * default - don't allow offline attacks on a user's password
1065 * by asking for a ticket to them as a service (encrypted with
1066 * their probably patheticly insecure password) */
1068 if (entry->flags.server
1069 && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
1070 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
1071 entry->flags.server = 0;
1076 * We restrict a 3-part SPN ending in my domain/realm to full
1077 * domain controllers.
1079 * This avoids any cases where (eg) a demoted DC still has
1080 * these more restricted SPNs.
1082 if (krb5_princ_size(context, principal) > 2) {
1083 char *third_part
1084 = smb_krb5_principal_get_comp_string(mem_ctx,
1085 context,
1086 principal,
1088 bool is_our_realm =
1089 lpcfg_is_my_domain_or_realm(lp_ctx,
1090 third_part);
1091 bool is_dc = userAccountControl &
1092 (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT);
1093 if (is_our_realm && !is_dc) {
1094 entry->flags.server = 0;
1098 * To give the correct type of error to the client, we must
1099 * not just return the entry without .server set, we must
1100 * pretend the principal does not exist. Otherwise we may
1101 * return ERR_POLICY instead of
1102 * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
1104 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry->flags.server == 0) {
1105 ret = SDB_ERR_NOENTRY;
1106 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
1107 goto out;
1109 if (flags & SDB_F_ADMIN_DATA) {
1110 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
1111 * of the Heimdal KDC. They are stored in a the traditional
1112 * DB for audit purposes, and still form part of the structure
1113 * we must return */
1115 /* use 'whenCreated' */
1116 entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1117 /* use 'kadmin' for now (needed by mit_samba) */
1119 ret = smb_krb5_make_principal(context,
1120 &entry->created_by.principal,
1121 lpcfg_realm(lp_ctx), "kadmin", NULL);
1122 if (ret) {
1123 krb5_clear_error_message(context);
1124 goto out;
1127 entry->modified_by = (struct sdb_event *) malloc(sizeof(struct sdb_event));
1128 if (entry->modified_by == NULL) {
1129 ret = ENOMEM;
1130 krb5_set_error_message(context, ret, "malloc: out of memory");
1131 goto out;
1134 /* use 'whenChanged' */
1135 entry->modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
1136 /* use 'kadmin' for now (needed by mit_samba) */
1137 ret = smb_krb5_make_principal(context,
1138 &entry->modified_by->principal,
1139 lpcfg_realm(lp_ctx), "kadmin", NULL);
1140 if (ret) {
1141 krb5_clear_error_message(context);
1142 goto out;
1147 /* The lack of password controls etc applies to krbtgt by
1148 * virtue of being that particular RID */
1149 status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
1151 if (!NT_STATUS_IS_OK(status)) {
1152 ret = EINVAL;
1153 goto out;
1156 if (rid == DOMAIN_RID_KRBTGT) {
1157 char *realm = NULL;
1159 entry->valid_end = NULL;
1160 entry->pw_end = NULL;
1162 entry->flags.invalid = 0;
1163 entry->flags.server = 1;
1165 realm = smb_krb5_principal_get_realm(
1166 mem_ctx, context, principal);
1167 if (realm == NULL) {
1168 ret = ENOMEM;
1169 goto out;
1172 /* Don't mark all requests for the krbtgt/realm as
1173 * 'change password', as otherwise we could get into
1174 * trouble, and not enforce the password expirty.
1175 * Instead, only do it when request is for the kpasswd service */
1176 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
1177 && krb5_princ_size(context, principal) == 2
1178 && (principal_comp_strcmp(context, principal, 0, "kadmin") == 0)
1179 && (principal_comp_strcmp(context, principal, 1, "changepw") == 0)
1180 && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
1181 entry->flags.change_pw = 1;
1184 TALLOC_FREE(realm);
1186 entry->flags.client = 0;
1187 entry->flags.forwardable = 1;
1188 entry->flags.ok_as_delegate = 1;
1189 } else if (is_rodc) {
1190 /* The RODC krbtgt account is like the main krbtgt,
1191 * but it does not have a changepw or kadmin
1192 * service */
1194 entry->valid_end = NULL;
1195 entry->pw_end = NULL;
1197 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
1198 entry->flags.client = 0;
1199 entry->flags.invalid = 0;
1200 entry->flags.server = 1;
1202 entry->flags.client = 0;
1203 entry->flags.forwardable = 1;
1204 entry->flags.ok_as_delegate = 0;
1205 } else if (entry->flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1206 /* The account/password expiry only applies when the account is used as a
1207 * client (ie password login), not when used as a server */
1209 /* Make very well sure we don't use this for a client,
1210 * it could bypass the password restrictions */
1211 entry->flags.client = 0;
1213 entry->valid_end = NULL;
1214 entry->pw_end = NULL;
1216 } else {
1217 NTTIME must_change_time
1218 = samdb_result_nttime(msg,
1219 "msDS-UserPasswordExpiryTimeComputed",
1221 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
1222 entry->pw_end = NULL;
1223 } else {
1224 entry->pw_end = malloc(sizeof(*entry->pw_end));
1225 if (entry->pw_end == NULL) {
1226 ret = ENOMEM;
1227 goto out;
1229 *entry->pw_end = nt_time_to_unix(must_change_time);
1232 acct_expiry = samdb_result_account_expires(msg);
1233 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
1234 entry->valid_end = NULL;
1235 } else {
1236 entry->valid_end = malloc(sizeof(*entry->valid_end));
1237 if (entry->valid_end == NULL) {
1238 ret = ENOMEM;
1239 goto out;
1241 *entry->valid_end = nt_time_to_unix(acct_expiry);
1245 entry->valid_start = NULL;
1247 entry->max_life = malloc(sizeof(*entry->max_life));
1248 if (entry->max_life == NULL) {
1249 ret = ENOMEM;
1250 goto out;
1253 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1254 *entry->max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
1255 } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
1256 *entry->max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
1257 } else {
1258 *entry->max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
1259 kdc_db_ctx->policy.usr_tkt_lifetime);
1262 entry->max_renew = malloc(sizeof(*entry->max_renew));
1263 if (entry->max_renew == NULL) {
1264 ret = ENOMEM;
1265 goto out;
1268 *entry->max_renew = kdc_db_ctx->policy.renewal_lifetime;
1270 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT && (flags & SDB_F_FOR_AS_REQ)) {
1271 int result;
1272 struct auth_user_info_dc *user_info_dc = NULL;
1274 * These protections only apply to clients, so servers in the
1275 * Protected Users group may still have service tickets to them
1276 * encrypted with RC4. For accounts looked up as servers, note
1277 * that 'msg' does not contain the 'memberOf' attribute for
1278 * determining whether the account is a member of Protected
1279 * Users.
1281 * Additionally, Microsoft advises that accounts for services
1282 * and computers should never be members of Protected Users, or
1283 * they may fail to authenticate.
1285 status = samba_kdc_get_user_info_from_db(p, msg, &user_info_dc);
1286 if (!NT_STATUS_IS_OK(status)) {
1287 ret = EINVAL;
1288 goto out;
1291 result = dsdb_is_protected_user(kdc_db_ctx->samdb,
1292 user_info_dc->sids,
1293 user_info_dc->num_sids);
1294 if (result == -1) {
1295 ret = EINVAL;
1296 goto out;
1299 protected_user = result;
1301 if (protected_user) {
1302 *entry->max_life = MIN(*entry->max_life, 4 * 60 * 60);
1303 *entry->max_renew = MIN(*entry->max_renew, 4 * 60 * 60);
1305 entry->flags.forwardable = 0;
1306 entry->flags.proxiable = 0;
1310 /* Get keys from the db */
1311 ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
1312 rid, is_rodc, userAccountControl,
1313 ent_type, entry,
1314 protected_user, &supported_enctypes);
1315 if (ret) {
1316 /* Could be bogus data in the entry, or out of memory */
1317 goto out;
1320 p->msg = talloc_steal(p, msg);
1321 p->supported_enctypes = supported_enctypes;
1323 out:
1324 if (ret != 0) {
1325 /* This doesn't free ent itself, that is for the eventual caller to do */
1326 sdb_entry_free(entry);
1327 } else {
1328 talloc_steal(kdc_db_ctx, p);
1331 return ret;
1335 * Construct an hdb_entry from a directory entry.
1336 * The kvno is what the remote client asked for
1338 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
1339 struct samba_kdc_db_context *kdc_db_ctx,
1340 TALLOC_CTX *mem_ctx,
1341 enum trust_direction direction,
1342 struct ldb_dn *realm_dn,
1343 unsigned flags,
1344 uint32_t kvno,
1345 struct ldb_message *msg,
1346 struct sdb_entry *entry)
1348 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1349 const char *our_realm = lpcfg_realm(lp_ctx);
1350 char *partner_realm = NULL;
1351 const char *realm = NULL;
1352 const char *krbtgt_realm = NULL;
1353 DATA_BLOB password_utf16 = data_blob_null;
1354 DATA_BLOB password_utf8 = data_blob_null;
1355 struct samr_Password _password_hash;
1356 const struct samr_Password *password_hash = NULL;
1357 const struct ldb_val *password_val;
1358 struct trustAuthInOutBlob password_blob;
1359 struct samba_kdc_entry *p;
1360 bool use_previous = false;
1361 uint32_t current_kvno;
1362 uint32_t previous_kvno;
1363 uint32_t num_keys = 0;
1364 enum ndr_err_code ndr_err;
1365 int ret;
1366 unsigned int i;
1367 struct AuthenticationInformationArray *auth_array;
1368 struct timeval tv;
1369 NTTIME an_hour_ago;
1370 uint32_t *auth_kvno;
1371 bool preferr_current = false;
1372 uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
1373 struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
1374 NTSTATUS status;
1376 ZERO_STRUCTP(entry);
1378 if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1379 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
1380 "msDS-SupportedEncryptionTypes",
1381 supported_enctypes);
1384 status = dsdb_trust_parse_tdo_info(mem_ctx, msg, &tdo);
1385 if (!NT_STATUS_IS_OK(status)) {
1386 krb5_clear_error_message(context);
1387 ret = ENOMEM;
1388 goto out;
1391 if (!(tdo->trust_direction & direction)) {
1392 krb5_clear_error_message(context);
1393 ret = SDB_ERR_NOENTRY;
1394 goto out;
1397 if (tdo->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
1399 * Only UPLEVEL domains support kerberos here,
1400 * as we don't support LSA_TRUST_TYPE_MIT.
1402 krb5_clear_error_message(context);
1403 ret = SDB_ERR_NOENTRY;
1404 goto out;
1407 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_CROSS_ORGANIZATION) {
1409 * We don't support selective authentication yet.
1411 krb5_clear_error_message(context);
1412 ret = SDB_ERR_NOENTRY;
1413 goto out;
1416 if (tdo->domain_name.string == NULL) {
1417 krb5_clear_error_message(context);
1418 ret = SDB_ERR_NOENTRY;
1419 goto out;
1421 partner_realm = strupper_talloc(mem_ctx, tdo->domain_name.string);
1422 if (partner_realm == NULL) {
1423 krb5_clear_error_message(context);
1424 ret = ENOMEM;
1425 goto out;
1428 if (direction == INBOUND) {
1429 realm = our_realm;
1430 krbtgt_realm = partner_realm;
1432 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
1433 } else { /* OUTBOUND */
1434 realm = partner_realm;
1435 krbtgt_realm = our_realm;
1437 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
1440 if (password_val == NULL) {
1441 krb5_clear_error_message(context);
1442 ret = SDB_ERR_NOENTRY;
1443 goto out;
1446 ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
1447 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1448 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1449 krb5_clear_error_message(context);
1450 ret = EINVAL;
1451 goto out;
1454 p = talloc_zero(mem_ctx, struct samba_kdc_entry);
1455 if (!p) {
1456 ret = ENOMEM;
1457 goto out;
1460 p->is_trust = true;
1461 p->kdc_db_ctx = kdc_db_ctx;
1462 p->realm_dn = realm_dn;
1463 p->supported_enctypes = supported_enctypes;
1465 talloc_set_destructor(p, samba_kdc_entry_destructor);
1467 entry->skdc_entry = p;
1469 /* use 'whenCreated' */
1470 entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1471 /* use 'kadmin' for now (needed by mit_samba) */
1472 ret = smb_krb5_make_principal(context,
1473 &entry->created_by.principal,
1474 realm, "kadmin", NULL);
1475 if (ret) {
1476 krb5_clear_error_message(context);
1477 goto out;
1481 * We always need to generate the canonicalized principal
1482 * with the values of our database.
1484 ret = smb_krb5_make_principal(context, &entry->principal, realm,
1485 "krbtgt", krbtgt_realm, NULL);
1486 if (ret) {
1487 krb5_clear_error_message(context);
1488 goto out;
1490 smb_krb5_principal_set_type(context, entry->principal,
1491 KRB5_NT_SRV_INST);
1493 entry->valid_start = NULL;
1495 /* we need to work out if we are going to use the current or
1496 * the previous password hash.
1497 * We base this on the kvno the client passes in. If the kvno
1498 * passed in is equal to the current kvno in our database then
1499 * we use the current structure. If it is the current kvno-1,
1500 * then we use the previous substrucure.
1504 * Windows preferrs the previous key for one hour.
1506 tv = timeval_current();
1507 if (tv.tv_sec > 3600) {
1508 tv.tv_sec -= 3600;
1510 an_hour_ago = timeval_to_nttime(&tv);
1512 /* first work out the current kvno */
1513 current_kvno = 0;
1514 for (i=0; i < password_blob.count; i++) {
1515 struct AuthenticationInformation *a =
1516 &password_blob.current.array[i];
1518 if (a->LastUpdateTime <= an_hour_ago) {
1519 preferr_current = true;
1522 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1523 current_kvno = a->AuthInfo.version.version;
1526 if (current_kvno == 0) {
1527 previous_kvno = 255;
1528 } else {
1529 previous_kvno = current_kvno - 1;
1531 for (i=0; i < password_blob.count; i++) {
1532 struct AuthenticationInformation *a =
1533 &password_blob.previous.array[i];
1535 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1536 previous_kvno = a->AuthInfo.version.version;
1540 /* work out whether we will use the previous or current
1541 password */
1542 if (password_blob.previous.count == 0) {
1543 /* there is no previous password */
1544 use_previous = false;
1545 } else if (!(flags & SDB_F_KVNO_SPECIFIED)) {
1547 * If not specified we use the lowest kvno
1548 * for the first hour after an update.
1550 if (preferr_current) {
1551 use_previous = false;
1552 } else if (previous_kvno < current_kvno) {
1553 use_previous = true;
1554 } else {
1555 use_previous = false;
1557 } else if (kvno == current_kvno) {
1559 * Exact match ...
1561 use_previous = false;
1562 } else if (kvno == previous_kvno) {
1564 * Exact match ...
1566 use_previous = true;
1567 } else {
1569 * Fallback to the current one for anything else
1571 use_previous = false;
1574 if (use_previous) {
1575 auth_array = &password_blob.previous;
1576 auth_kvno = &previous_kvno;
1577 } else {
1578 auth_array = &password_blob.current;
1579 auth_kvno = &current_kvno;
1582 /* use the kvno the client specified, if available */
1583 if (flags & SDB_F_KVNO_SPECIFIED) {
1584 entry->kvno = kvno;
1585 } else {
1586 entry->kvno = *auth_kvno;
1589 for (i=0; i < auth_array->count; i++) {
1590 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1591 bool ok;
1593 password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
1594 auth_array->array[i].AuthInfo.clear.size);
1595 if (password_utf16.length == 0) {
1596 break;
1599 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1600 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
1601 if (password_hash == NULL) {
1602 num_keys += 1;
1604 password_hash = &_password_hash;
1607 if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1608 break;
1611 ok = convert_string_talloc(mem_ctx,
1612 CH_UTF16MUNGED, CH_UTF8,
1613 password_utf16.data,
1614 password_utf16.length,
1615 (void *)&password_utf8.data,
1616 &password_utf8.length);
1617 if (!ok) {
1618 krb5_clear_error_message(context);
1619 ret = ENOMEM;
1620 goto out;
1623 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1624 num_keys += 1;
1626 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1627 num_keys += 1;
1629 break;
1630 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
1631 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1632 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
1633 num_keys += 1;
1638 /* Must have found a cleartext or MD4 password */
1639 if (num_keys == 0) {
1640 DEBUG(1,(__location__ ": no usable key found\n"));
1641 krb5_clear_error_message(context);
1642 ret = SDB_ERR_NOENTRY;
1643 goto out;
1646 entry->keys.val = calloc(num_keys, sizeof(struct sdb_key));
1647 if (entry->keys.val == NULL) {
1648 krb5_clear_error_message(context);
1649 ret = ENOMEM;
1650 goto out;
1653 if (password_utf8.length != 0) {
1654 struct sdb_key key = {};
1655 krb5_const_principal salt_principal = entry->principal;
1656 krb5_data salt;
1657 krb5_data cleartext_data;
1659 cleartext_data.data = discard_const_p(char, password_utf8.data);
1660 cleartext_data.length = password_utf8.length;
1662 ret = smb_krb5_get_pw_salt(context,
1663 salt_principal,
1664 &salt);
1665 if (ret != 0) {
1666 goto out;
1669 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1670 ret = smb_krb5_create_key_from_string(context,
1671 salt_principal,
1672 &salt,
1673 &cleartext_data,
1674 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
1675 &key.key);
1676 if (ret != 0) {
1677 smb_krb5_free_data_contents(context, &salt);
1678 goto out;
1681 entry->keys.val[entry->keys.len] = key;
1682 entry->keys.len++;
1685 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1686 ret = smb_krb5_create_key_from_string(context,
1687 salt_principal,
1688 &salt,
1689 &cleartext_data,
1690 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
1691 &key.key);
1692 if (ret != 0) {
1693 smb_krb5_free_data_contents(context, &salt);
1694 goto out;
1697 entry->keys.val[entry->keys.len] = key;
1698 entry->keys.len++;
1701 smb_krb5_free_data_contents(context, &salt);
1704 if (password_hash != NULL) {
1705 struct sdb_key key = {};
1707 ret = smb_krb5_keyblock_init_contents(context,
1708 ENCTYPE_ARCFOUR_HMAC,
1709 password_hash->hash,
1710 sizeof(password_hash->hash),
1711 &key.key);
1712 if (ret != 0) {
1713 goto out;
1716 entry->keys.val[entry->keys.len] = key;
1717 entry->keys.len++;
1720 entry->flags = int2SDBFlags(0);
1721 entry->flags.immutable = 1;
1722 entry->flags.invalid = 0;
1723 entry->flags.server = 1;
1724 entry->flags.require_preauth = 1;
1726 entry->pw_end = NULL;
1728 entry->max_life = NULL;
1730 entry->max_renew = NULL;
1732 /* Match Windows behavior and allow forwardable flag in cross-realm. */
1733 entry->flags.forwardable = 1;
1735 samba_kdc_sort_keys(&entry->keys);
1737 p->msg = talloc_steal(p, msg);
1739 out:
1740 TALLOC_FREE(partner_realm);
1742 if (ret != 0) {
1743 /* This doesn't free ent itself, that is for the eventual caller to do */
1744 sdb_entry_free(entry);
1745 } else {
1746 talloc_steal(kdc_db_ctx, p);
1749 return ret;
1753 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
1754 TALLOC_CTX *mem_ctx,
1755 const char *realm,
1756 struct ldb_dn *realm_dn,
1757 struct ldb_message **pmsg)
1759 NTSTATUS status;
1760 const char * const *attrs = trust_attrs;
1762 status = dsdb_trust_search_tdo(ldb_ctx, realm, realm,
1763 attrs, mem_ctx, pmsg);
1764 if (NT_STATUS_IS_OK(status)) {
1765 return 0;
1766 } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1767 return SDB_ERR_NOENTRY;
1768 } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1769 int ret = ENOMEM;
1770 krb5_set_error_message(context, ret, "get_sam_result_trust: out of memory");
1771 return ret;
1772 } else {
1773 int ret = EINVAL;
1774 krb5_set_error_message(context, ret, "get_sam_result_trust: %s", nt_errstr(status));
1775 return ret;
1779 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1780 struct samba_kdc_db_context *kdc_db_ctx,
1781 TALLOC_CTX *mem_ctx,
1782 krb5_const_principal principal,
1783 const char **attrs,
1784 struct ldb_dn **realm_dn,
1785 struct ldb_message **msg)
1787 NTSTATUS nt_status;
1788 char *principal_string = NULL;
1790 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1791 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
1792 principal, 0);
1793 if (principal_string == NULL) {
1794 return ENOMEM;
1796 } else {
1797 char *principal_string_m = NULL;
1798 krb5_error_code ret;
1800 ret = krb5_unparse_name(context, principal, &principal_string_m);
1801 if (ret != 0) {
1802 return ret;
1805 principal_string = talloc_strdup(mem_ctx, principal_string_m);
1806 SAFE_FREE(principal_string_m);
1807 if (principal_string == NULL) {
1808 return ENOMEM;
1812 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1813 mem_ctx, principal_string, attrs,
1814 realm_dn, msg);
1815 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1816 krb5_principal fallback_principal = NULL;
1817 unsigned int num_comp;
1818 char *fallback_realm = NULL;
1819 char *fallback_account = NULL;
1820 krb5_error_code ret;
1822 ret = krb5_parse_name(context, principal_string,
1823 &fallback_principal);
1824 TALLOC_FREE(principal_string);
1825 if (ret != 0) {
1826 return ret;
1829 num_comp = krb5_princ_size(context, fallback_principal);
1830 fallback_realm = smb_krb5_principal_get_realm(
1831 mem_ctx, context, fallback_principal);
1832 if (fallback_realm == NULL) {
1833 krb5_free_principal(context, fallback_principal);
1834 return ENOMEM;
1837 if (num_comp == 1) {
1838 size_t len;
1840 fallback_account = smb_krb5_principal_get_comp_string(mem_ctx,
1841 context, fallback_principal, 0);
1842 if (fallback_account == NULL) {
1843 krb5_free_principal(context, fallback_principal);
1844 TALLOC_FREE(fallback_realm);
1845 return ENOMEM;
1848 len = strlen(fallback_account);
1849 if (len >= 2 && fallback_account[len - 1] == '$') {
1850 TALLOC_FREE(fallback_account);
1853 krb5_free_principal(context, fallback_principal);
1854 fallback_principal = NULL;
1856 if (fallback_account != NULL) {
1857 char *with_dollar;
1859 with_dollar = talloc_asprintf(mem_ctx, "%s$",
1860 fallback_account);
1861 if (with_dollar == NULL) {
1862 TALLOC_FREE(fallback_realm);
1863 return ENOMEM;
1865 TALLOC_FREE(fallback_account);
1867 ret = smb_krb5_make_principal(context,
1868 &fallback_principal,
1869 fallback_realm,
1870 with_dollar, NULL);
1871 TALLOC_FREE(with_dollar);
1872 if (ret != 0) {
1873 TALLOC_FREE(fallback_realm);
1874 return ret;
1877 TALLOC_FREE(fallback_realm);
1879 if (fallback_principal != NULL) {
1880 char *fallback_string = NULL;
1882 ret = krb5_unparse_name(context,
1883 fallback_principal,
1884 &fallback_string);
1885 if (ret != 0) {
1886 krb5_free_principal(context, fallback_principal);
1887 return ret;
1890 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1891 mem_ctx,
1892 fallback_string,
1893 attrs,
1894 realm_dn, msg);
1895 SAFE_FREE(fallback_string);
1897 krb5_free_principal(context, fallback_principal);
1898 fallback_principal = NULL;
1900 TALLOC_FREE(principal_string);
1902 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1903 return SDB_ERR_NOENTRY;
1904 } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1905 return ENOMEM;
1906 } else if (!NT_STATUS_IS_OK(nt_status)) {
1907 return EINVAL;
1910 return 0;
1913 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1914 struct samba_kdc_db_context *kdc_db_ctx,
1915 TALLOC_CTX *mem_ctx,
1916 krb5_const_principal principal,
1917 unsigned flags,
1918 struct sdb_entry_ex *entry_ex)
1920 struct sdb_entry *entry = &entry_ex->entry;
1921 struct ldb_dn *realm_dn;
1922 krb5_error_code ret;
1923 struct ldb_message *msg = NULL;
1925 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1926 mem_ctx, principal, user_attrs,
1927 &realm_dn, &msg);
1928 if (ret != 0) {
1929 return ret;
1932 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1933 principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1934 flags,
1935 realm_dn, msg, entry);
1936 return ret;
1939 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1940 struct samba_kdc_db_context *kdc_db_ctx,
1941 TALLOC_CTX *mem_ctx,
1942 krb5_const_principal principal,
1943 unsigned flags,
1944 uint32_t kvno,
1945 struct sdb_entry_ex *entry_ex)
1947 struct sdb_entry *entry = &entry_ex->entry;
1948 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1949 krb5_error_code ret;
1950 struct ldb_message *msg = NULL;
1951 struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1952 char *realm_from_princ;
1953 char *realm_princ_comp = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 1);
1955 realm_from_princ = smb_krb5_principal_get_realm(
1956 mem_ctx, context, principal);
1957 if (realm_from_princ == NULL) {
1958 /* can't happen */
1959 return SDB_ERR_NOENTRY;
1962 if (krb5_princ_size(context, principal) != 2
1963 || (principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME) != 0)) {
1964 /* Not a krbtgt */
1965 return SDB_ERR_NOENTRY;
1968 /* krbtgt case. Either us or a trusted realm */
1970 if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
1971 && lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp)) {
1972 /* us, or someone quite like us */
1973 /* Cludge, cludge cludge. If the realm part of krbtgt/realm,
1974 * is in our db, then direct the caller at our primary
1975 * krbtgt */
1977 int lret;
1978 unsigned int krbtgt_number;
1979 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
1980 trust tickets. We don't yet know what this means, but we do
1981 seem to need to treat it as unspecified */
1982 if (flags & SDB_F_KVNO_SPECIFIED) {
1983 krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
1984 if (kdc_db_ctx->rodc) {
1985 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1986 return SDB_ERR_NOT_FOUND_HERE;
1989 } else {
1990 krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1993 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1994 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1995 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1996 krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
1997 "(objectClass=user)");
1998 } else {
1999 /* We need to look up an RODC krbtgt (perhaps
2000 * ours, if we are an RODC, perhaps another
2001 * RODC if we are a read-write DC */
2002 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
2003 &msg, realm_dn, LDB_SCOPE_SUBTREE,
2004 krbtgt_attrs,
2005 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2006 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
2009 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2010 krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
2011 (unsigned)(krbtgt_number));
2012 krb5_set_error_message(context, SDB_ERR_NOENTRY,
2013 "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
2014 (unsigned)(krbtgt_number));
2015 return SDB_ERR_NOENTRY;
2016 } else if (lret != LDB_SUCCESS) {
2017 krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
2018 (unsigned)(krbtgt_number));
2019 krb5_set_error_message(context, SDB_ERR_NOENTRY,
2020 "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
2021 (unsigned)(krbtgt_number));
2022 return SDB_ERR_NOENTRY;
2025 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2026 principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
2027 flags, realm_dn, msg, entry);
2028 if (ret != 0) {
2029 krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
2031 return ret;
2033 } else {
2034 enum trust_direction direction = UNKNOWN;
2035 const char *realm = NULL;
2037 /* Either an inbound or outbound trust */
2039 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
2040 /* look for inbound trust */
2041 direction = INBOUND;
2042 realm = realm_princ_comp;
2043 } else if (principal_comp_strcasecmp(context, principal, 1, lpcfg_realm(lp_ctx)) == 0) {
2044 /* look for outbound trust */
2045 direction = OUTBOUND;
2046 realm = realm_from_princ;
2047 } else {
2048 krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
2049 realm_from_princ,
2050 realm_princ_comp);
2051 krb5_set_error_message(context, SDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
2052 realm_from_princ,
2053 realm_princ_comp);
2054 return SDB_ERR_NOENTRY;
2057 /* Trusted domains are under CN=system */
2059 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
2060 mem_ctx,
2061 realm, realm_dn, &msg);
2063 if (ret != 0) {
2064 krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
2065 krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
2066 return ret;
2069 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
2070 direction,
2071 realm_dn, flags, kvno, msg, entry);
2072 if (ret != 0) {
2073 krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed for %s",
2074 ldb_dn_get_linearized(msg->dn));
2075 krb5_set_error_message(context, ret, "samba_kdc_fetch: "
2076 "trust_message2entry failed for %s",
2077 ldb_dn_get_linearized(msg->dn));
2079 return ret;
2084 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
2085 struct samba_kdc_db_context *kdc_db_ctx,
2086 TALLOC_CTX *mem_ctx,
2087 krb5_const_principal principal,
2088 unsigned flags,
2089 const char **attrs,
2090 struct ldb_dn **realm_dn,
2091 struct ldb_message **msg)
2093 krb5_error_code ret;
2094 if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
2095 && krb5_princ_size(context, principal) >= 2) {
2096 /* 'normal server' case */
2097 int ldb_ret;
2098 NTSTATUS nt_status;
2099 struct ldb_dn *user_dn;
2100 char *principal_string;
2102 ret = krb5_unparse_name_flags(context, principal,
2103 KRB5_PRINCIPAL_UNPARSE_NO_REALM,
2104 &principal_string);
2105 if (ret != 0) {
2106 return ret;
2109 /* At this point we may find the host is known to be
2110 * in a different realm, so we should generate a
2111 * referral instead */
2112 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
2113 mem_ctx, principal_string,
2114 &user_dn, realm_dn);
2115 free(principal_string);
2117 if (!NT_STATUS_IS_OK(nt_status)) {
2118 return SDB_ERR_NOENTRY;
2121 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
2122 mem_ctx,
2123 msg, user_dn, LDB_SCOPE_BASE,
2124 attrs,
2125 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2126 "(objectClass=*)");
2127 if (ldb_ret != LDB_SUCCESS) {
2128 return SDB_ERR_NOENTRY;
2130 return 0;
2131 } else if (!(flags & SDB_F_FOR_AS_REQ)
2132 && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2134 * The behaviour of accepting an
2135 * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
2136 * containing a UPN only applies to TGS-REQ packets,
2137 * not AS-REQ packets.
2139 return samba_kdc_lookup_client(context, kdc_db_ctx,
2140 mem_ctx, principal, attrs,
2141 realm_dn, msg);
2142 } else {
2144 * This case is for:
2145 * - the AS-REQ, where we only accept
2146 * samAccountName based lookups for the server, no
2147 * matter if the name is an
2148 * KRB5_NT_ENTERPRISE_PRINCIPAL or not
2149 * - for the TGS-REQ when we are not given an
2150 * KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
2151 * only lookup samAccountName based names.
2153 int lret;
2154 char *short_princ;
2155 krb5_principal enterprise_principal = NULL;
2156 krb5_const_principal used_principal = NULL;
2157 char *name1 = NULL;
2158 size_t len1 = 0;
2159 char *filter = NULL;
2161 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2162 char *str = NULL;
2163 /* Need to reparse the enterprise principal to find the real target */
2164 if (krb5_princ_size(context, principal) != 1) {
2165 ret = KRB5_PARSE_MALFORMED;
2166 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
2167 "enterprise principal with wrong (%d) number of components",
2168 krb5_princ_size(context, principal));
2169 return ret;
2171 str = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0);
2172 if (str == NULL) {
2173 return KRB5_PARSE_MALFORMED;
2175 ret = krb5_parse_name(context, str,
2176 &enterprise_principal);
2177 talloc_free(str);
2178 if (ret) {
2179 return ret;
2181 used_principal = enterprise_principal;
2182 } else {
2183 used_principal = principal;
2186 /* server as client principal case, but we must not lookup userPrincipalNames */
2187 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2189 /* TODO: Check if it is our realm, otherwise give referral */
2191 ret = krb5_unparse_name_flags(context, used_principal,
2192 KRB5_PRINCIPAL_UNPARSE_NO_REALM |
2193 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2194 &short_princ);
2195 used_principal = NULL;
2196 krb5_free_principal(context, enterprise_principal);
2197 enterprise_principal = NULL;
2199 if (ret != 0) {
2200 krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
2201 krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
2202 return ret;
2205 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
2206 SAFE_FREE(short_princ);
2207 if (name1 == NULL) {
2208 return ENOMEM;
2210 len1 = strlen(name1);
2211 if (len1 >= 1 && name1[len1 - 1] != '$') {
2212 filter = talloc_asprintf(mem_ctx,
2213 "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
2214 name1, name1);
2215 if (filter == NULL) {
2216 return ENOMEM;
2218 } else {
2219 filter = talloc_asprintf(mem_ctx,
2220 "(&(objectClass=user)(samAccountName=%s))",
2221 name1);
2222 if (filter == NULL) {
2223 return ENOMEM;
2227 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
2228 *realm_dn, LDB_SCOPE_SUBTREE,
2229 attrs,
2230 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2231 "%s", filter);
2232 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2233 DEBUG(10, ("Failed to find an entry for %s filter:%s\n",
2234 name1, filter));
2235 return SDB_ERR_NOENTRY;
2237 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
2238 DEBUG(10, ("Failed to find unique entry for %s filter:%s\n",
2239 name1, filter));
2240 return SDB_ERR_NOENTRY;
2242 if (lret != LDB_SUCCESS) {
2243 DEBUG(0, ("Failed single search for %s - %s\n",
2244 name1, ldb_errstring(kdc_db_ctx->samdb)));
2245 return SDB_ERR_NOENTRY;
2247 return 0;
2249 return SDB_ERR_NOENTRY;
2254 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
2255 struct samba_kdc_db_context *kdc_db_ctx,
2256 TALLOC_CTX *mem_ctx,
2257 krb5_const_principal principal,
2258 unsigned flags,
2259 struct sdb_entry_ex *entry_ex)
2261 struct sdb_entry *entry = &entry_ex->entry;
2262 krb5_error_code ret;
2263 struct ldb_dn *realm_dn;
2264 struct ldb_message *msg;
2266 ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
2267 flags, server_attrs, &realm_dn, &msg);
2268 if (ret != 0) {
2269 return ret;
2272 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2273 principal, SAMBA_KDC_ENT_TYPE_SERVER,
2274 flags,
2275 realm_dn, msg, entry);
2276 if (ret != 0) {
2277 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
2280 return ret;
2283 static krb5_error_code samba_kdc_lookup_realm(krb5_context context,
2284 struct samba_kdc_db_context *kdc_db_ctx,
2285 TALLOC_CTX *mem_ctx,
2286 krb5_const_principal principal,
2287 unsigned flags,
2288 struct sdb_entry_ex *entry_ex)
2290 TALLOC_CTX *frame = talloc_stackframe();
2291 NTSTATUS status;
2292 krb5_error_code ret;
2293 bool check_realm = false;
2294 const char *realm = NULL;
2295 struct dsdb_trust_routing_table *trt = NULL;
2296 const struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
2297 unsigned int num_comp;
2298 bool ok;
2299 char *upper = NULL;
2301 num_comp = krb5_princ_size(context, principal);
2303 if (flags & SDB_F_GET_CLIENT) {
2304 if (flags & SDB_F_FOR_AS_REQ) {
2305 check_realm = true;
2308 if (flags & SDB_F_GET_SERVER) {
2309 if (flags & SDB_F_FOR_TGS_REQ) {
2310 check_realm = true;
2314 if (!check_realm) {
2315 TALLOC_FREE(frame);
2316 return 0;
2319 realm = smb_krb5_principal_get_realm(frame, context, principal);
2320 if (realm == NULL) {
2321 TALLOC_FREE(frame);
2322 return ENOMEM;
2326 * The requested realm needs to be our own
2328 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2329 if (!ok) {
2331 * The request is not for us...
2333 TALLOC_FREE(frame);
2334 return SDB_ERR_NOENTRY;
2337 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2338 char *principal_string = NULL;
2339 krb5_principal enterprise_principal = NULL;
2340 char *enterprise_realm = NULL;
2342 if (num_comp != 1) {
2343 TALLOC_FREE(frame);
2344 return SDB_ERR_NOENTRY;
2347 principal_string = smb_krb5_principal_get_comp_string(frame, context,
2348 principal, 0);
2349 if (principal_string == NULL) {
2350 TALLOC_FREE(frame);
2351 return ENOMEM;
2354 ret = krb5_parse_name(context, principal_string,
2355 &enterprise_principal);
2356 TALLOC_FREE(principal_string);
2357 if (ret) {
2358 TALLOC_FREE(frame);
2359 return ret;
2362 enterprise_realm = smb_krb5_principal_get_realm(
2363 frame, context, enterprise_principal);
2364 krb5_free_principal(context, enterprise_principal);
2365 if (enterprise_realm != NULL) {
2366 realm = enterprise_realm;
2370 if (flags & SDB_F_GET_SERVER) {
2371 char *service_realm = NULL;
2373 ret = principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME);
2374 if (ret == 0) {
2376 * we need to search krbtgt/ locally
2378 TALLOC_FREE(frame);
2379 return 0;
2383 * We need to check the last component against the routing table.
2385 * Note this works only with 2 or 3 component principals, e.g:
2387 * servicePrincipalName: ldap/W2K8R2-219.bla.base
2388 * servicePrincipalName: ldap/W2K8R2-219.bla.base/bla.base
2389 * servicePrincipalName: ldap/W2K8R2-219.bla.base/ForestDnsZones.bla.base
2390 * servicePrincipalName: ldap/W2K8R2-219.bla.base/DomainDnsZones.bla.base
2393 if (num_comp == 2 || num_comp == 3) {
2394 service_realm = smb_krb5_principal_get_comp_string(frame,
2395 context,
2396 principal,
2397 num_comp - 1);
2400 if (service_realm != NULL) {
2401 realm = service_realm;
2405 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2406 if (ok) {
2408 * skip the expensive routing lookup
2410 TALLOC_FREE(frame);
2411 return 0;
2414 status = dsdb_trust_routing_table_load(kdc_db_ctx->samdb,
2415 frame, &trt);
2416 if (!NT_STATUS_IS_OK(status)) {
2417 TALLOC_FREE(frame);
2418 return EINVAL;
2421 tdo = dsdb_trust_routing_by_name(trt, realm);
2422 if (tdo == NULL) {
2424 * This principal has to be local
2426 TALLOC_FREE(frame);
2427 return 0;
2430 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
2432 * TODO: handle the routing within the forest
2434 * This should likely be handled in
2435 * samba_kdc_message2entry() in case we're
2436 * a global catalog. We'd need to check
2437 * if realm_dn is our own domain and derive
2438 * the dns domain name from realm_dn and check that
2439 * against the routing table or fallback to
2440 * the tdo we found here.
2442 * But for now we don't support multiple domains
2443 * in our forest correctly anyway.
2445 * Just search in our local database.
2447 TALLOC_FREE(frame);
2448 return 0;
2451 ZERO_STRUCT(entry_ex->entry);
2453 ret = krb5_copy_principal(context, principal,
2454 &entry_ex->entry.principal);
2455 if (ret) {
2456 TALLOC_FREE(frame);
2457 return ret;
2460 upper = strupper_talloc(frame, tdo->domain_name.string);
2461 if (upper == NULL) {
2462 TALLOC_FREE(frame);
2463 return ENOMEM;
2466 ret = smb_krb5_principal_set_realm(context,
2467 entry_ex->entry.principal,
2468 upper);
2469 if (ret) {
2470 TALLOC_FREE(frame);
2471 return ret;
2474 TALLOC_FREE(frame);
2475 return SDB_ERR_WRONG_REALM;
2478 krb5_error_code samba_kdc_fetch(krb5_context context,
2479 struct samba_kdc_db_context *kdc_db_ctx,
2480 krb5_const_principal principal,
2481 unsigned flags,
2482 krb5_kvno kvno,
2483 struct sdb_entry_ex *entry_ex)
2485 krb5_error_code ret = SDB_ERR_NOENTRY;
2486 TALLOC_CTX *mem_ctx;
2488 mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
2489 if (!mem_ctx) {
2490 ret = ENOMEM;
2491 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2492 return ret;
2495 ret = samba_kdc_lookup_realm(context, kdc_db_ctx, mem_ctx,
2496 principal, flags, entry_ex);
2497 if (ret != 0) {
2498 goto done;
2501 ret = SDB_ERR_NOENTRY;
2503 if (flags & SDB_F_GET_CLIENT) {
2504 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2505 if (ret != SDB_ERR_NOENTRY) goto done;
2507 if (flags & SDB_F_GET_SERVER) {
2508 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
2509 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2510 if (ret != SDB_ERR_NOENTRY) goto done;
2512 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
2513 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2514 if (ret != SDB_ERR_NOENTRY) goto done;
2516 if (flags & SDB_F_GET_KRBTGT) {
2517 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2518 if (ret != SDB_ERR_NOENTRY) goto done;
2521 done:
2522 talloc_free(mem_ctx);
2523 return ret;
2526 struct samba_kdc_seq {
2527 unsigned int index;
2528 unsigned int count;
2529 struct ldb_message **msgs;
2530 struct ldb_dn *realm_dn;
2533 static krb5_error_code samba_kdc_seq(krb5_context context,
2534 struct samba_kdc_db_context *kdc_db_ctx,
2535 struct sdb_entry_ex *entry_ex)
2537 struct sdb_entry *entry = &entry_ex->entry;
2538 krb5_error_code ret;
2539 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2540 const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
2541 struct ldb_message *msg = NULL;
2542 const char *sAMAccountName = NULL;
2543 krb5_principal principal = NULL;
2544 TALLOC_CTX *mem_ctx;
2546 if (!priv) {
2547 return SDB_ERR_NOENTRY;
2550 mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
2552 if (!mem_ctx) {
2553 ret = ENOMEM;
2554 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
2555 return ret;
2558 while (priv->index < priv->count) {
2559 msg = priv->msgs[priv->index++];
2561 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
2562 if (sAMAccountName != NULL) {
2563 break;
2567 if (sAMAccountName == NULL) {
2568 ret = SDB_ERR_NOENTRY;
2569 goto out;
2572 ret = smb_krb5_make_principal(context, &principal,
2573 realm, sAMAccountName, NULL);
2574 if (ret != 0) {
2575 goto out;
2578 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2579 principal, SAMBA_KDC_ENT_TYPE_ANY,
2580 SDB_F_ADMIN_DATA|SDB_F_GET_ANY,
2581 priv->realm_dn, msg, entry);
2583 out:
2584 if (principal != NULL) {
2585 krb5_free_principal(context, principal);
2588 if (ret != 0) {
2589 TALLOC_FREE(priv);
2590 kdc_db_ctx->seq_ctx = NULL;
2591 } else {
2592 talloc_free(mem_ctx);
2595 return ret;
2598 krb5_error_code samba_kdc_firstkey(krb5_context context,
2599 struct samba_kdc_db_context *kdc_db_ctx,
2600 struct sdb_entry_ex *entry)
2602 struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
2603 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2604 char *realm;
2605 struct ldb_result *res = NULL;
2606 krb5_error_code ret;
2607 TALLOC_CTX *mem_ctx;
2608 int lret;
2610 if (priv) {
2611 TALLOC_FREE(priv);
2612 kdc_db_ctx->seq_ctx = NULL;
2615 priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
2616 if (!priv) {
2617 ret = ENOMEM;
2618 krb5_set_error_message(context, ret, "talloc: out of memory");
2619 return ret;
2622 priv->index = 0;
2623 priv->msgs = NULL;
2624 priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
2625 priv->count = 0;
2627 mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
2629 if (!mem_ctx) {
2630 ret = ENOMEM;
2631 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
2632 return ret;
2635 ret = krb5_get_default_realm(context, &realm);
2636 if (ret != 0) {
2637 TALLOC_FREE(priv);
2638 return ret;
2640 krb5_free_default_realm(context, realm);
2642 lret = dsdb_search(ldb_ctx, priv, &res,
2643 priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
2644 DSDB_SEARCH_NO_GLOBAL_CATALOG,
2645 "(objectClass=user)");
2647 if (lret != LDB_SUCCESS) {
2648 TALLOC_FREE(priv);
2649 return SDB_ERR_NOENTRY;
2652 priv->count = res->count;
2653 priv->msgs = talloc_steal(priv, res->msgs);
2654 talloc_free(res);
2656 kdc_db_ctx->seq_ctx = priv;
2658 ret = samba_kdc_seq(context, kdc_db_ctx, entry);
2660 if (ret != 0) {
2661 TALLOC_FREE(priv);
2662 kdc_db_ctx->seq_ctx = NULL;
2663 } else {
2664 talloc_free(mem_ctx);
2666 return ret;
2669 krb5_error_code samba_kdc_nextkey(krb5_context context,
2670 struct samba_kdc_db_context *kdc_db_ctx,
2671 struct sdb_entry_ex *entry)
2673 return samba_kdc_seq(context, kdc_db_ctx, entry);
2676 /* Check if a given entry may delegate or do s4u2self to this target principal
2678 * The safest way to determine 'self' is to check the DB record made at
2679 * the time the principal was presented to the KDC.
2681 krb5_error_code
2682 samba_kdc_check_client_matches_target_service(krb5_context context,
2683 struct samba_kdc_entry *skdc_entry_client,
2684 struct samba_kdc_entry *skdc_entry_server_target)
2686 struct dom_sid *orig_sid;
2687 struct dom_sid *target_sid;
2688 TALLOC_CTX *frame = talloc_stackframe();
2690 orig_sid = samdb_result_dom_sid(frame,
2691 skdc_entry_client->msg,
2692 "objectSid");
2693 target_sid = samdb_result_dom_sid(frame,
2694 skdc_entry_server_target->msg,
2695 "objectSid");
2698 * Allow delegation to the same record (representing a
2699 * principal), even if by a different name. The easy and safe
2700 * way to prove this is by SID comparison
2702 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2703 talloc_free(frame);
2704 return KRB5KRB_AP_ERR_BADMATCH;
2707 talloc_free(frame);
2708 return 0;
2711 /* Certificates printed by a the Certificate Authority might have a
2712 * slightly different form of the user principal name to that in the
2713 * database. Allow a mismatch where they both refer to the same
2714 * SID */
2716 krb5_error_code
2717 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
2718 struct samba_kdc_db_context *kdc_db_ctx,
2719 struct samba_kdc_entry *skdc_entry,
2720 krb5_const_principal certificate_principal)
2722 krb5_error_code ret;
2723 struct ldb_dn *realm_dn;
2724 struct ldb_message *msg;
2725 struct dom_sid *orig_sid;
2726 struct dom_sid *target_sid;
2727 const char *ms_upn_check_attrs[] = {
2728 "objectSid", NULL
2731 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
2733 if (!mem_ctx) {
2734 ret = ENOMEM;
2735 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2736 return ret;
2739 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2740 mem_ctx, certificate_principal,
2741 ms_upn_check_attrs, &realm_dn, &msg);
2743 if (ret != 0) {
2744 talloc_free(mem_ctx);
2745 return ret;
2748 orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2749 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2751 /* Consider these to be the same principal, even if by a different
2752 * name. The easy and safe way to prove this is by SID
2753 * comparison */
2754 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2755 talloc_free(mem_ctx);
2756 #if defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
2757 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
2758 #else /* Heimdal (where this is an enum) */
2759 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
2760 #endif
2763 talloc_free(mem_ctx);
2764 return ret;
2768 * Check if a given entry may delegate to this target principal
2769 * with S4U2Proxy.
2771 krb5_error_code
2772 samba_kdc_check_s4u2proxy(krb5_context context,
2773 struct samba_kdc_db_context *kdc_db_ctx,
2774 struct samba_kdc_entry *skdc_entry,
2775 krb5_const_principal target_principal)
2777 krb5_error_code ret;
2778 char *tmp = NULL;
2779 const char *client_dn = NULL;
2780 const char *target_principal_name = NULL;
2781 struct ldb_message_element *el;
2782 struct ldb_val val;
2783 unsigned int i;
2784 bool found = false;
2786 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
2788 if (!mem_ctx) {
2789 ret = ENOMEM;
2790 krb5_set_error_message(context, ret,
2791 "samba_kdc_check_s4u2proxy:"
2792 " talloc_named() failed!");
2793 return ret;
2796 client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
2797 if (!client_dn) {
2798 if (errno == 0) {
2799 errno = ENOMEM;
2801 ret = errno;
2802 krb5_set_error_message(context, ret,
2803 "samba_kdc_check_s4u2proxy:"
2804 " ldb_dn_get_linearized() failed!");
2805 return ret;
2808 el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
2809 if (el == NULL) {
2810 ret = ENOENT;
2811 goto bad_option;
2813 SMB_ASSERT(el->num_values != 0);
2816 * This is the Microsoft forwardable flag behavior.
2818 * If the proxy (target) principal is NULL, and we have any authorized
2819 * delegation target, allow to forward.
2821 if (target_principal == NULL) {
2822 return 0;
2827 * The main heimdal code already checked that the target_principal
2828 * belongs to the same realm as the client.
2830 * So we just need the principal without the realm,
2831 * as that is what is configured in the "msDS-AllowedToDelegateTo"
2832 * attribute.
2834 ret = krb5_unparse_name_flags(context, target_principal,
2835 KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
2836 if (ret) {
2837 talloc_free(mem_ctx);
2838 krb5_set_error_message(context, ret,
2839 "samba_kdc_check_s4u2proxy:"
2840 " krb5_unparse_name() failed!");
2841 return ret;
2843 DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
2844 client_dn, tmp));
2846 target_principal_name = talloc_strdup(mem_ctx, tmp);
2847 SAFE_FREE(tmp);
2848 if (target_principal_name == NULL) {
2849 ret = ENOMEM;
2850 krb5_set_error_message(context, ret,
2851 "samba_kdc_check_s4u2proxy:"
2852 " talloc_strdup() failed!");
2853 return ret;
2856 val = data_blob_string_const(target_principal_name);
2858 for (i=0; i<el->num_values; i++) {
2859 struct ldb_val *val1 = &val;
2860 struct ldb_val *val2 = &el->values[i];
2861 int cmp;
2863 if (val1->length != val2->length) {
2864 continue;
2867 cmp = strncasecmp((const char *)val1->data,
2868 (const char *)val2->data,
2869 val1->length);
2870 if (cmp != 0) {
2871 continue;
2874 found = true;
2875 break;
2878 if (!found) {
2879 ret = ENOENT;
2880 goto bad_option;
2883 DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
2884 client_dn, tmp));
2885 talloc_free(mem_ctx);
2886 return 0;
2888 bad_option:
2889 krb5_set_error_message(context, ret,
2890 "samba_kdc_check_s4u2proxy: client[%s] "
2891 "not allowed for delegation to target[%s]",
2892 client_dn,
2893 target_principal_name);
2894 talloc_free(mem_ctx);
2895 return KRB5KDC_ERR_BADOPTION;
2899 * This method is called for S4U2Proxy requests and implements the
2900 * resource-based constrained delegation variant, which can support
2901 * cross-realm delegation.
2903 krb5_error_code samba_kdc_check_s4u2proxy_rbcd(
2904 krb5_context context,
2905 struct samba_kdc_db_context *kdc_db_ctx,
2906 krb5_const_principal client_principal,
2907 krb5_const_principal server_principal,
2908 krb5_pac header_pac,
2909 struct samba_kdc_entry *proxy_skdc_entry)
2911 krb5_error_code code;
2912 enum ndr_err_code ndr_err;
2913 char *client_name = NULL;
2914 char *server_name = NULL;
2915 const char *proxy_dn = NULL;
2916 const DATA_BLOB *data = NULL;
2917 struct security_descriptor *rbcd_security_descriptor = NULL;
2918 struct auth_user_info_dc *user_info_dc = NULL;
2919 struct auth_session_info *session_info = NULL;
2920 uint32_t session_info_flags = AUTH_SESSION_INFO_SIMPLE_PRIVILEGES;
2921 uint32_t access_desired = SEC_ADS_GENERIC_ALL; /* => 0x000f01ff */
2922 uint32_t access_granted = 0;
2923 NTSTATUS nt_status;
2924 TALLOC_CTX *mem_ctx = NULL;
2926 mem_ctx = talloc_named(kdc_db_ctx,
2928 "samba_kdc_check_s4u2proxy_rbcd");
2929 if (mem_ctx == NULL) {
2930 errno = ENOMEM;
2931 code = errno;
2933 return code;
2936 proxy_dn = ldb_dn_get_linearized(proxy_skdc_entry->msg->dn);
2937 if (proxy_dn == NULL) {
2938 DBG_ERR("ldb_dn_get_linearized failed for proxy_dn!\n");
2939 TALLOC_FREE(mem_ctx);
2940 if (errno == 0) {
2941 errno = ENOMEM;
2943 code = errno;
2945 goto out;
2948 rbcd_security_descriptor = talloc_zero(mem_ctx,
2949 struct security_descriptor);
2950 if (rbcd_security_descriptor == NULL) {
2951 errno = ENOMEM;
2952 code = errno;
2954 goto out;
2957 code = krb5_unparse_name_flags(context,
2958 client_principal,
2959 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2960 &client_name);
2961 if (code != 0) {
2962 DBG_ERR("Unable to parse client_principal!\n");
2963 goto out;
2966 code = krb5_unparse_name_flags(context,
2967 server_principal,
2968 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2969 &server_name);
2970 if (code != 0) {
2971 DBG_ERR("Unable to parse server_principal!\n");
2972 SAFE_FREE(client_name);
2973 goto out;
2976 DBG_INFO("Check delegation from client[%s] to server[%s] via "
2977 "proxy[%s]\n",
2978 client_name,
2979 server_name,
2980 proxy_dn);
2982 code = kerberos_pac_to_user_info_dc(mem_ctx,
2983 header_pac,
2984 context,
2985 &user_info_dc,
2986 NULL,
2987 NULL);
2988 if (code != 0) {
2989 goto out;
2992 if (user_info_dc->info->authenticated) {
2993 session_info_flags |= AUTH_SESSION_INFO_AUTHENTICATED;
2996 nt_status = auth_generate_session_info(mem_ctx,
2997 kdc_db_ctx->lp_ctx,
2998 kdc_db_ctx->samdb,
2999 user_info_dc,
3000 session_info_flags,
3001 &session_info);
3002 if (!NT_STATUS_IS_OK(nt_status)) {
3003 code = map_errno_from_nt_status(nt_status);
3004 goto out;
3007 data = ldb_msg_find_ldb_val(proxy_skdc_entry->msg,
3008 "msDS-AllowedToActOnBehalfOfOtherIdentity");
3009 if (data == NULL) {
3010 DBG_ERR("Could not find security descriptor"
3011 "msDS-AllowedToActOnBehalfOfOtherIdentity in "
3012 "proxy[%s]\n",
3013 proxy_dn);
3014 code = KRB5KDC_ERR_BADOPTION;
3015 goto out;
3018 ndr_err = ndr_pull_struct_blob(
3019 data,
3020 mem_ctx,
3021 rbcd_security_descriptor,
3022 (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
3023 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3024 errno = ndr_map_error2errno(ndr_err);
3025 DBG_ERR("Failed to unmarshall "
3026 "msDS-AllowedToActOnBehalfOfOtherIdentity "
3027 "security descriptor of proxy[%s]\n",
3028 proxy_dn);
3029 code = KRB5KDC_ERR_BADOPTION;
3030 goto out;
3033 if (DEBUGLEVEL >= 10) {
3034 NDR_PRINT_DEBUG(security_token, session_info->security_token);
3035 NDR_PRINT_DEBUG(security_descriptor, rbcd_security_descriptor);
3038 nt_status = sec_access_check_ds(rbcd_security_descriptor,
3039 session_info->security_token,
3040 access_desired,
3041 &access_granted,
3042 NULL,
3043 NULL);
3045 if (!NT_STATUS_IS_OK(nt_status)) {
3046 DBG_WARNING("RBCD: sec_access_check_ds(access_desired=%#08x, "
3047 "access_granted:%#08x) failed with: %s\n",
3048 access_desired,
3049 access_granted,
3050 nt_errstr(nt_status));
3052 code = KRB5KDC_ERR_BADOPTION;
3053 goto out;
3056 DBG_NOTICE("RBCD: Access granted for client[%s]\n", client_name);
3058 code = 0;
3059 out:
3060 SAFE_FREE(client_name);
3061 SAFE_FREE(server_name);
3063 TALLOC_FREE(mem_ctx);
3064 return code;
3067 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
3068 struct samba_kdc_db_context **kdc_db_ctx_out)
3070 int ldb_ret;
3071 struct ldb_message *msg;
3072 struct auth_session_info *session_info;
3073 struct samba_kdc_db_context *kdc_db_ctx;
3074 /* The idea here is very simple. Using Kerberos to
3075 * authenticate the KDC to the LDAP server is higly likely to
3076 * be circular.
3078 * In future we may set this up to use EXERNAL and SSL
3079 * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
3082 kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
3083 if (kdc_db_ctx == NULL) {
3084 return NT_STATUS_NO_MEMORY;
3086 kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
3087 kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
3088 kdc_db_ctx->msg_ctx = base_ctx->msg_ctx;
3090 /* get default kdc policy */
3091 lpcfg_default_kdc_policy(mem_ctx,
3092 base_ctx->lp_ctx,
3093 &kdc_db_ctx->policy.svc_tkt_lifetime,
3094 &kdc_db_ctx->policy.usr_tkt_lifetime,
3095 &kdc_db_ctx->policy.renewal_lifetime);
3097 session_info = system_session(kdc_db_ctx->lp_ctx);
3098 if (session_info == NULL) {
3099 return NT_STATUS_INTERNAL_ERROR;
3102 /* Setup the link to secrets.ldb */
3104 kdc_db_ctx->secrets_db = secrets_db_connect(kdc_db_ctx,
3105 base_ctx->lp_ctx);
3106 if (kdc_db_ctx->secrets_db == NULL) {
3107 DEBUG(1, ("samba_kdc_setup_db_ctx: "
3108 "Cannot open secrets.ldb for KDC backend!"));
3109 talloc_free(kdc_db_ctx);
3110 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3113 kdc_db_ctx->fx_cookie_dn = ldb_dn_new(kdc_db_ctx,
3114 kdc_db_ctx->secrets_db,
3115 "CN=FX Cookie");
3117 /* Setup the link to LDB */
3118 kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx,
3119 base_ctx->ev_ctx,
3120 base_ctx->lp_ctx,
3121 session_info,
3122 NULL,
3124 if (kdc_db_ctx->samdb == NULL) {
3125 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
3126 talloc_free(kdc_db_ctx);
3127 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3130 /* Find out our own krbtgt kvno */
3131 ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
3132 if (ldb_ret != LDB_SUCCESS) {
3133 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
3134 ldb_errstring(kdc_db_ctx->samdb)));
3135 talloc_free(kdc_db_ctx);
3136 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3138 if (kdc_db_ctx->rodc) {
3139 int my_krbtgt_number;
3140 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
3141 struct ldb_dn *account_dn;
3142 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
3143 if (!server_dn) {
3144 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
3145 ldb_errstring(kdc_db_ctx->samdb)));
3146 talloc_free(kdc_db_ctx);
3147 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3150 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
3151 "serverReference", &account_dn);
3152 if (ldb_ret != LDB_SUCCESS) {
3153 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
3154 ldb_errstring(kdc_db_ctx->samdb)));
3155 talloc_free(kdc_db_ctx);
3156 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3159 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
3160 "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
3161 talloc_free(account_dn);
3162 if (ldb_ret != LDB_SUCCESS) {
3163 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
3164 ldb_errstring(kdc_db_ctx->samdb)));
3165 talloc_free(kdc_db_ctx);
3166 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3169 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3170 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
3171 secondary_keytab,
3172 DSDB_SEARCH_NO_GLOBAL_CATALOG,
3173 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
3174 if (ldb_ret != LDB_SUCCESS) {
3175 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
3176 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3177 ldb_errstring(kdc_db_ctx->samdb),
3178 ldb_strerror(ldb_ret)));
3179 talloc_free(kdc_db_ctx);
3180 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3182 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
3183 if (my_krbtgt_number == -1) {
3184 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
3185 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3186 my_krbtgt_number));
3187 talloc_free(kdc_db_ctx);
3188 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3190 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
3192 } else {
3193 kdc_db_ctx->my_krbtgt_number = 0;
3194 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3195 &msg,
3196 ldb_get_default_basedn(kdc_db_ctx->samdb),
3197 LDB_SCOPE_SUBTREE,
3198 krbtgt_attrs,
3199 DSDB_SEARCH_NO_GLOBAL_CATALOG,
3200 "(&(objectClass=user)(samAccountName=krbtgt))");
3202 if (ldb_ret != LDB_SUCCESS) {
3203 DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
3204 talloc_free(kdc_db_ctx);
3205 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3207 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
3208 kdc_db_ctx->my_krbtgt_number = 0;
3209 talloc_free(msg);
3211 *kdc_db_ctx_out = kdc_db_ctx;
3212 return NT_STATUS_OK;