tests/krb5: Allow specifying options and expected flags when obtaining a ticket
[Samba.git] / source4 / kdc / db-glue.c
blob5fd0f431cdfefb4b06bf2e7d2f6109076830722f
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 "auth/auth.h"
27 #include "auth/auth_sam.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "dsdb/common/util.h"
30 #include "librpc/gen_ndr/ndr_drsblobs.h"
31 #include "param/param.h"
32 #include "../lib/crypto/md4.h"
33 #include "system/kerberos.h"
34 #include "auth/kerberos/kerberos.h"
35 #include "kdc/sdb.h"
36 #include "kdc/samba_kdc.h"
37 #include "kdc/db-glue.h"
38 #include "librpc/gen_ndr/ndr_irpc_c.h"
39 #include "lib/messaging/irpc.h"
42 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
43 ((uint16_t)(((uint32_t)kvno) >> 16))
45 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
46 ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
47 ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
49 enum samba_kdc_ent_type
50 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
51 SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
53 enum trust_direction {
54 UNKNOWN = 0,
55 INBOUND = LSA_TRUST_DIRECTION_INBOUND,
56 OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
59 static const char *trust_attrs[] = {
60 "securityIdentifier",
61 "flatName",
62 "trustPartner",
63 "trustAttributes",
64 "trustDirection",
65 "trustType",
66 "msDS-TrustForestTrustInfo",
67 "trustAuthIncoming",
68 "trustAuthOutgoing",
69 "whenCreated",
70 "msDS-SupportedEncryptionTypes",
71 NULL
75 send a message to the drepl server telling it to initiate a
76 REPL_SECRET getncchanges extended op to fetch the users secrets
78 static void auth_sam_trigger_repl_secret(TALLOC_CTX *mem_ctx,
79 struct imessaging_context *msg_ctx,
80 struct tevent_context *event_ctx,
81 struct ldb_dn *user_dn)
83 struct dcerpc_binding_handle *irpc_handle;
84 struct drepl_trigger_repl_secret r;
85 struct tevent_req *req;
86 TALLOC_CTX *tmp_ctx;
88 tmp_ctx = talloc_new(mem_ctx);
89 if (tmp_ctx == NULL) {
90 return;
93 irpc_handle = irpc_binding_handle_by_name(tmp_ctx, msg_ctx,
94 "dreplsrv",
95 &ndr_table_irpc);
96 if (irpc_handle == NULL) {
97 DEBUG(1,(__location__ ": Unable to get binding handle for dreplsrv\n"));
98 TALLOC_FREE(tmp_ctx);
99 return;
102 r.in.user_dn = ldb_dn_get_linearized(user_dn);
105 * This seem to rely on the current IRPC implementation,
106 * which delivers the message in the _send function.
108 * TODO: we need a ONE_WAY IRPC handle and register
109 * a callback and wait for it to be triggered!
111 req = dcerpc_drepl_trigger_repl_secret_r_send(tmp_ctx,
112 event_ctx,
113 irpc_handle,
114 &r);
116 /* we aren't interested in a reply */
117 talloc_free(req);
118 TALLOC_FREE(tmp_ctx);
121 static time_t ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, time_t default_val)
123 const char *tmp;
124 const char *gentime;
125 struct tm tm;
127 gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
128 if (!gentime)
129 return default_val;
131 tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
132 if (tmp == NULL) {
133 return default_val;
136 return timegm(&tm);
139 static struct SDBFlags uf2SDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
141 struct SDBFlags flags = int2SDBFlags(0);
143 /* we don't allow kadmin deletes */
144 flags.immutable = 1;
146 /* mark the principal as invalid to start with */
147 flags.invalid = 1;
149 flags.renewable = 1;
151 /* All accounts are servers, but this may be disabled again in the caller */
152 flags.server = 1;
154 /* Account types - clear the invalid bit if it turns out to be valid */
155 if (userAccountControl & UF_NORMAL_ACCOUNT) {
156 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
157 flags.client = 1;
159 flags.invalid = 0;
162 if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
163 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
164 flags.client = 1;
166 flags.invalid = 0;
168 if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
169 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
170 flags.client = 1;
172 flags.invalid = 0;
174 if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
175 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
176 flags.client = 1;
178 flags.invalid = 0;
181 /* Not permitted to act as a client if disabled */
182 if (userAccountControl & UF_ACCOUNTDISABLE) {
183 flags.client = 0;
185 if (userAccountControl & UF_LOCKOUT) {
186 flags.locked_out = 1;
189 if (userAccountControl & UF_PASSWORD_NOTREQD) {
190 flags.invalid = 1;
194 UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
196 if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
197 flags.invalid = 1;
200 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
203 if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
204 flags.invalid = 1;
207 if (userAccountControl & UF_SMARTCARD_REQUIRED) {
208 flags.require_hwauth = 1;
210 if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
211 flags.ok_as_delegate = 1;
213 if (userAccountControl & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
215 * this is confusing...
217 * UF_TRUSTED_FOR_DELEGATION
218 * => ok_as_delegate
220 * and
222 * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
223 * => trusted_for_delegation
225 flags.trusted_for_delegation = 1;
227 if (!(userAccountControl & UF_NOT_DELEGATED)) {
228 flags.forwardable = 1;
229 flags.proxiable = 1;
232 if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
233 flags.require_preauth = 0;
234 } else {
235 flags.require_preauth = 1;
238 return flags;
241 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
243 if (p->entry_ex != NULL) {
244 struct sdb_entry_ex *entry_ex = p->entry_ex;
245 free_sdb_entry(&entry_ex->entry);
248 return 0;
252 * Sort keys in descending order of strength.
254 * Explanaton from Greg Hudson:
256 * To encrypt tickets only the first returned key is used by the MIT KDC. The
257 * other keys just communicate support for session key enctypes, and aren't
258 * really used. The encryption key for the ticket enc part doesn't have
259 * to be of a type requested by the client. The session key enctype is chosen
260 * based on the client preference order, limited by the set of enctypes present
261 * in the server keys (unless the string attribute is set on the server
262 * principal overriding that set).
264 static int samba_kdc_sort_encryption_keys(struct sdb_entry_ex *entry_ex)
266 unsigned int i, j, idx = 0;
267 static const krb5_enctype etype_list[] = {
268 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
269 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
270 ENCTYPE_DES3_CBC_SHA1,
271 ENCTYPE_ARCFOUR_HMAC,
272 ENCTYPE_DES_CBC_MD5,
273 ENCTYPE_DES_CBC_MD4,
274 ENCTYPE_DES_CBC_CRC,
275 ENCTYPE_NULL
277 size_t etype_len = ARRAY_SIZE(etype_list);
278 size_t keys_size = entry_ex->entry.keys.len;
279 struct sdb_key *keys = entry_ex->entry.keys.val;
280 struct sdb_key *sorted_keys;
282 sorted_keys = calloc(keys_size, sizeof(struct sdb_key));
283 if (sorted_keys == NULL) {
284 return -1;
287 for (i = 0; i < etype_len; i++) {
288 for (j = 0; j < keys_size; j++) {
289 const struct sdb_key skey = keys[j];
291 if (idx == keys_size) {
292 break;
295 if (KRB5_KEY_TYPE(&skey.key) == etype_list[i]) {
296 sorted_keys[idx] = skey;
297 idx++;
302 /* Paranoia: Something went wrong during data copy */
303 if (idx != keys_size) {
304 free(sorted_keys);
305 return -1;
308 free(entry_ex->entry.keys.val);
309 entry_ex->entry.keys.val = sorted_keys;
311 return 0;
314 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
315 struct samba_kdc_db_context *kdc_db_ctx,
316 TALLOC_CTX *mem_ctx,
317 struct ldb_message *msg,
318 uint32_t rid,
319 bool is_rodc,
320 uint32_t userAccountControl,
321 enum samba_kdc_ent_type ent_type,
322 struct sdb_entry_ex *entry_ex)
324 krb5_error_code ret = 0;
325 enum ndr_err_code ndr_err;
326 struct samr_Password *hash;
327 const struct ldb_val *sc_val;
328 struct supplementalCredentialsBlob scb;
329 struct supplementalCredentialsPackage *scpk = NULL;
330 bool newer_keys = false;
331 struct package_PrimaryKerberosBlob _pkb;
332 struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
333 struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
334 uint16_t i;
335 uint16_t allocated_keys = 0;
336 int rodc_krbtgt_number = 0;
337 int kvno = 0;
338 uint32_t supported_enctypes
339 = ldb_msg_find_attr_as_uint(msg,
340 "msDS-SupportedEncryptionTypes",
343 if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
344 /* KDCs (and KDCs on RODCs) use AES */
345 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
346 } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
347 /* DCs and RODCs comptuer accounts use AES */
348 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
349 } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
350 (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
351 /* for AS-REQ the client chooses the enc types it
352 * supports, and this will vary between computers a
353 * user logs in from.
355 * likewise for 'any' return as much as is supported,
356 * to export into a keytab */
357 supported_enctypes = ENC_ALL_TYPES;
360 /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
361 if (userAccountControl & UF_USE_DES_KEY_ONLY) {
362 supported_enctypes = 0;
363 } else {
364 /* Otherwise, add in the default enc types */
365 supported_enctypes |= ENC_RC4_HMAC_MD5;
368 /* Is this the krbtgt or a RODC krbtgt */
369 if (is_rodc) {
370 rodc_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
372 if (rodc_krbtgt_number == -1) {
373 return EINVAL;
377 entry_ex->entry.keys.val = NULL;
378 entry_ex->entry.keys.len = 0;
379 entry_ex->entry.kvno = 0;
381 if ((ent_type == SAMBA_KDC_ENT_TYPE_CLIENT)
382 && (userAccountControl & UF_SMARTCARD_REQUIRED)) {
383 uint8_t secretbuffer[32];
386 * Fake keys until we have a better way to reject
387 * non-pkinit requests.
389 * We just need to indicate which encryption types are
390 * supported.
392 generate_secret_buffer(secretbuffer, sizeof(secretbuffer));
394 allocated_keys = 3;
395 entry_ex->entry.keys.len = 0;
396 entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(struct sdb_key));
397 if (entry_ex->entry.keys.val == NULL) {
398 ZERO_STRUCT(secretbuffer);
399 ret = ENOMEM;
400 goto out;
403 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
404 struct sdb_key key = {};
406 ret = smb_krb5_keyblock_init_contents(context,
407 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
408 secretbuffer, 32,
409 &key.key);
410 if (ret) {
411 ZERO_STRUCT(secretbuffer);
412 goto out;
415 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
416 entry_ex->entry.keys.len++;
419 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
420 struct sdb_key key = {};
422 ret = smb_krb5_keyblock_init_contents(context,
423 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
424 secretbuffer, 16,
425 &key.key);
426 if (ret) {
427 ZERO_STRUCT(secretbuffer);
428 goto out;
431 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
432 entry_ex->entry.keys.len++;
435 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
436 struct sdb_key key = {};
438 ret = smb_krb5_keyblock_init_contents(context,
439 ENCTYPE_ARCFOUR_HMAC,
440 secretbuffer, 16,
441 &key.key);
442 if (ret) {
443 ZERO_STRUCT(secretbuffer);
444 goto out;
447 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
448 entry_ex->entry.keys.len++;
451 ret = 0;
452 goto out;
455 kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
456 if (is_rodc) {
457 kvno = SAMBA_KVNO_AND_KRBTGT(kvno, rodc_krbtgt_number);
459 entry_ex->entry.kvno = kvno;
461 /* Get keys from the db */
463 hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
464 sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
466 /* unicodePwd for enctype 0x17 (23) if present */
467 if (hash) {
468 allocated_keys++;
471 /* supplementalCredentials if present */
472 if (sc_val) {
473 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
474 (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
475 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
476 dump_data(0, sc_val->data, sc_val->length);
477 ret = EINVAL;
478 goto out;
481 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
482 if (scb.sub.num_packages != 0) {
483 NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
484 ret = EINVAL;
485 goto out;
489 for (i=0; i < scb.sub.num_packages; i++) {
490 if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
491 scpk = &scb.sub.packages[i];
492 if (!scpk->data || !scpk->data[0]) {
493 scpk = NULL;
494 continue;
496 newer_keys = true;
497 break;
498 } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
499 scpk = &scb.sub.packages[i];
500 if (!scpk->data || !scpk->data[0]) {
501 scpk = NULL;
504 * we don't break here in hope to find
505 * a Kerberos-Newer-Keys package
511 * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
512 * of supplementalCredentials
514 if (scpk) {
515 DATA_BLOB blob;
517 blob = strhex_to_data_blob(mem_ctx, scpk->data);
518 if (!blob.data) {
519 ret = ENOMEM;
520 goto out;
523 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
524 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
525 (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
526 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
527 ret = EINVAL;
528 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
529 krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
530 goto out;
533 if (newer_keys && _pkb.version != 4) {
534 ret = EINVAL;
535 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
536 krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
537 goto out;
540 if (!newer_keys && _pkb.version != 3) {
541 ret = EINVAL;
542 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
543 krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
544 goto out;
547 if (_pkb.version == 4) {
548 pkb4 = &_pkb.ctr.ctr4;
549 allocated_keys += pkb4->num_keys;
550 } else if (_pkb.version == 3) {
551 pkb3 = &_pkb.ctr.ctr3;
552 allocated_keys += pkb3->num_keys;
556 if (allocated_keys == 0) {
557 if (kdc_db_ctx->rodc) {
558 /* We are on an RODC, but don't have keys for this account. Signal this to the caller */
559 auth_sam_trigger_repl_secret(kdc_db_ctx, kdc_db_ctx->msg_ctx,
560 kdc_db_ctx->ev_ctx, msg->dn);
561 return SDB_ERR_NOT_FOUND_HERE;
564 /* oh, no password. Apparently (comment in
565 * hdb-ldap.c) this violates the ASN.1, but this
566 * allows an entry with no keys (yet). */
567 return 0;
570 /* allocate space to decode into */
571 entry_ex->entry.keys.len = 0;
572 entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(struct sdb_key));
573 if (entry_ex->entry.keys.val == NULL) {
574 ret = ENOMEM;
575 goto out;
578 if (hash && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
579 struct sdb_key key = {};
581 ret = smb_krb5_keyblock_init_contents(context,
582 ENCTYPE_ARCFOUR_HMAC,
583 hash->hash,
584 sizeof(hash->hash),
585 &key.key);
586 if (ret) {
587 goto out;
590 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
591 entry_ex->entry.keys.len++;
594 if (pkb4) {
595 for (i=0; i < pkb4->num_keys; i++) {
596 struct sdb_key key = {};
598 if (!pkb4->keys[i].value) continue;
600 if (!(kerberos_enctype_to_bitmap(pkb4->keys[i].keytype) & supported_enctypes)) {
601 continue;
604 if (pkb4->salt.string) {
605 DATA_BLOB salt;
607 salt = data_blob_string_const(pkb4->salt.string);
609 key.salt = calloc(1, sizeof(*key.salt));
610 if (key.salt == NULL) {
611 ret = ENOMEM;
612 goto out;
615 key.salt->type = KRB5_PW_SALT;
617 ret = smb_krb5_copy_data_contents(&key.salt->salt,
618 salt.data,
619 salt.length);
620 if (ret) {
621 free(key.salt);
622 key.salt = NULL;
623 goto out;
627 /* TODO: maybe pass the iteration_count somehow... */
629 ret = smb_krb5_keyblock_init_contents(context,
630 pkb4->keys[i].keytype,
631 pkb4->keys[i].value->data,
632 pkb4->keys[i].value->length,
633 &key.key);
634 if (ret) {
635 if (key.salt) {
636 smb_krb5_free_data_contents(context, &key.salt->salt);
637 free(key.salt);
638 key.salt = NULL;
640 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
641 DEBUG(2,("Unsupported keytype ignored - type %u\n",
642 pkb4->keys[i].keytype));
643 ret = 0;
644 continue;
646 goto out;
649 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
650 entry_ex->entry.keys.len++;
652 } else if (pkb3) {
653 for (i=0; i < pkb3->num_keys; i++) {
654 struct sdb_key key = {};
656 if (!pkb3->keys[i].value) continue;
658 if (!(kerberos_enctype_to_bitmap(pkb3->keys[i].keytype) & supported_enctypes)) {
659 continue;
662 if (pkb3->salt.string) {
663 DATA_BLOB salt;
665 salt = data_blob_string_const(pkb3->salt.string);
667 key.salt = calloc(1, sizeof(*key.salt));
668 if (key.salt == NULL) {
669 ret = ENOMEM;
670 goto out;
673 key.salt->type = KRB5_PW_SALT;
675 ret = smb_krb5_copy_data_contents(&key.salt->salt,
676 salt.data,
677 salt.length);
678 if (ret) {
679 free(key.salt);
680 key.salt = NULL;
681 goto out;
685 ret = smb_krb5_keyblock_init_contents(context,
686 pkb3->keys[i].keytype,
687 pkb3->keys[i].value->data,
688 pkb3->keys[i].value->length,
689 &key.key);
690 if (ret) {
691 if (key.salt) {
692 smb_krb5_free_data_contents(context, &key.salt->salt);
693 free(key.salt);
694 key.salt = NULL;
696 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
697 DEBUG(2,("Unsupported keytype ignored - type %u\n",
698 pkb3->keys[i].keytype));
699 ret = 0;
700 continue;
702 goto out;
705 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
706 entry_ex->entry.keys.len++;
710 out:
711 if (ret != 0) {
712 entry_ex->entry.keys.len = 0;
713 } else if (entry_ex->entry.keys.len > 0 &&
714 entry_ex->entry.keys.val != NULL) {
715 ret = samba_kdc_sort_encryption_keys(entry_ex);
716 if (ret != 0) {
717 entry_ex->entry.keys.len = 0;
718 ret = ENOMEM;
721 if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
722 free(entry_ex->entry.keys.val);
723 entry_ex->entry.keys.val = NULL;
725 return ret;
728 static int principal_comp_strcmp_int(krb5_context context,
729 krb5_const_principal principal,
730 unsigned int component,
731 const char *string,
732 bool do_strcasecmp)
734 const char *p;
735 size_t len;
737 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
738 p = krb5_principal_get_comp_string(context, principal, component);
739 if (p == NULL) {
740 return -1;
742 len = strlen(p);
743 #else
744 krb5_data *d;
745 if (component >= krb5_princ_size(context, principal)) {
746 return -1;
749 d = krb5_princ_component(context, principal, component);
750 if (d == NULL) {
751 return -1;
754 p = d->data;
755 len = d->length;
756 #endif
757 if (do_strcasecmp) {
758 return strncasecmp(p, string, len);
759 } else {
760 return strncmp(p, string, len);
764 static int principal_comp_strcasecmp(krb5_context context,
765 krb5_const_principal principal,
766 unsigned int component,
767 const char *string)
769 return principal_comp_strcmp_int(context, principal,
770 component, string, true);
773 static int principal_comp_strcmp(krb5_context context,
774 krb5_const_principal principal,
775 unsigned int component,
776 const char *string)
778 return principal_comp_strcmp_int(context, principal,
779 component, string, false);
783 * Construct an hdb_entry from a directory entry.
785 static krb5_error_code samba_kdc_message2entry(krb5_context context,
786 struct samba_kdc_db_context *kdc_db_ctx,
787 TALLOC_CTX *mem_ctx,
788 krb5_const_principal principal,
789 enum samba_kdc_ent_type ent_type,
790 unsigned flags,
791 struct ldb_dn *realm_dn,
792 struct ldb_message *msg,
793 struct sdb_entry_ex *entry_ex)
795 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
796 uint32_t userAccountControl;
797 uint32_t msDS_User_Account_Control_Computed;
798 krb5_error_code ret = 0;
799 krb5_boolean is_computer = FALSE;
801 struct samba_kdc_entry *p;
802 NTTIME acct_expiry;
803 NTSTATUS status;
805 uint32_t rid;
806 bool is_rodc = false;
807 struct ldb_message_element *objectclasses;
808 struct ldb_val computer_val;
809 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
810 computer_val.data = discard_const_p(uint8_t,"computer");
811 computer_val.length = strlen((const char *)computer_val.data);
813 if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
814 is_rodc = true;
817 if (!samAccountName) {
818 ret = ENOENT;
819 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
820 goto out;
823 objectclasses = ldb_msg_find_element(msg, "objectClass");
825 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
826 is_computer = TRUE;
829 ZERO_STRUCTP(entry_ex);
831 p = talloc_zero(mem_ctx, struct samba_kdc_entry);
832 if (!p) {
833 ret = ENOMEM;
834 goto out;
837 p->is_rodc = is_rodc;
838 p->kdc_db_ctx = kdc_db_ctx;
839 p->realm_dn = talloc_reference(p, realm_dn);
840 if (!p->realm_dn) {
841 ret = ENOMEM;
842 goto out;
845 talloc_set_destructor(p, samba_kdc_entry_destructor);
847 entry_ex->ctx = p;
849 userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
851 msDS_User_Account_Control_Computed
852 = ldb_msg_find_attr_as_uint(msg,
853 "msDS-User-Account-Control-Computed",
854 UF_ACCOUNTDISABLE);
857 * This brings in the lockout flag, block the account if not
858 * found. We need the weird UF_ACCOUNTDISABLE check because
859 * we do not want to fail open if the value is not returned,
860 * but 0 is a valid value (all OK)
862 if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
863 ret = EINVAL;
864 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
865 "no msDS-User-Account-Control-Computed present");
866 goto out;
867 } else {
868 userAccountControl |= msDS_User_Account_Control_Computed;
872 * If we are set to canonicalize, we get back the fixed UPPER
873 * case realm, and the real username (ie matching LDAP
874 * samAccountName)
876 * Otherwise, if we are set to enterprise, we
877 * get back the whole principal as-sent
879 * Finally, if we are not set to canonicalize, we get back the
880 * fixed UPPER case realm, but the as-sent username
883 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
884 p->is_krbtgt = true;
886 if (flags & (SDB_F_CANON)) {
888 * When requested to do so, ensure that the
889 * both realm values in the principal are set
890 * to the upper case, canonical realm
892 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal,
893 lpcfg_realm(lp_ctx), "krbtgt",
894 lpcfg_realm(lp_ctx), NULL);
895 if (ret) {
896 krb5_clear_error_message(context);
897 goto out;
899 smb_krb5_principal_set_type(context, entry_ex->entry.principal, KRB5_NT_SRV_INST);
900 } else {
901 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
902 if (ret) {
903 krb5_clear_error_message(context);
904 goto out;
907 * this appears to be required regardless of
908 * the canonicalize flag from the client
910 ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
911 if (ret) {
912 krb5_clear_error_message(context);
913 goto out;
917 } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
918 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
919 if (ret) {
920 krb5_clear_error_message(context);
921 goto out;
923 } else if ((flags & SDB_F_CANON) && (flags & SDB_F_FOR_AS_REQ)) {
925 * SDB_F_CANON maps from the canonicalize flag in the
926 * packet, and has a different meaning between AS-REQ
927 * and TGS-REQ. We only change the principal in the AS-REQ case
929 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
930 if (ret) {
931 krb5_clear_error_message(context);
932 goto out;
934 } else {
935 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
936 if (ret) {
937 krb5_clear_error_message(context);
938 goto out;
941 if (smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL) {
942 /* While we have copied the client principal, tests
943 * show that Win2k3 returns the 'corrected' realm, not
944 * the client-specified realm. This code attempts to
945 * replace the client principal's realm with the one
946 * we determine from our records */
948 /* this has to be with malloc() */
949 ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
950 if (ret) {
951 krb5_clear_error_message(context);
952 goto out;
957 /* First try and figure out the flags based on the userAccountControl */
958 entry_ex->entry.flags = uf2SDBFlags(context, userAccountControl, ent_type);
960 /* Windows 2008 seems to enforce this (very sensible) rule by
961 * default - don't allow offline attacks on a user's password
962 * by asking for a ticket to them as a service (encrypted with
963 * their probably patheticly insecure password) */
965 if (entry_ex->entry.flags.server
966 && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
967 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
968 entry_ex->entry.flags.server = 0;
972 * To give the correct type of error to the client, we must
973 * not just return the entry without .server set, we must
974 * pretend the principal does not exist. Otherwise we may
975 * return ERR_POLICY instead of
976 * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
978 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry_ex->entry.flags.server == 0) {
979 ret = SDB_ERR_NOENTRY;
980 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
981 goto out;
983 if (flags & SDB_F_ADMIN_DATA) {
984 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
985 * of the Heimdal KDC. They are stored in a the traditional
986 * DB for audit purposes, and still form part of the structure
987 * we must return */
989 /* use 'whenCreated' */
990 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
991 /* use 'kadmin' for now (needed by mit_samba) */
993 ret = smb_krb5_make_principal(context,
994 &entry_ex->entry.created_by.principal,
995 lpcfg_realm(lp_ctx), "kadmin", NULL);
996 if (ret) {
997 krb5_clear_error_message(context);
998 goto out;
1001 entry_ex->entry.modified_by = (struct sdb_event *) malloc(sizeof(struct sdb_event));
1002 if (entry_ex->entry.modified_by == NULL) {
1003 ret = ENOMEM;
1004 krb5_set_error_message(context, ret, "malloc: out of memory");
1005 goto out;
1008 /* use 'whenChanged' */
1009 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
1010 /* use 'kadmin' for now (needed by mit_samba) */
1011 ret = smb_krb5_make_principal(context,
1012 &entry_ex->entry.modified_by->principal,
1013 lpcfg_realm(lp_ctx), "kadmin", NULL);
1014 if (ret) {
1015 krb5_clear_error_message(context);
1016 goto out;
1021 /* The lack of password controls etc applies to krbtgt by
1022 * virtue of being that particular RID */
1023 status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
1025 if (!NT_STATUS_IS_OK(status)) {
1026 ret = EINVAL;
1027 goto out;
1030 if (rid == DOMAIN_RID_KRBTGT) {
1031 char *realm = NULL;
1033 entry_ex->entry.valid_end = NULL;
1034 entry_ex->entry.pw_end = NULL;
1036 entry_ex->entry.flags.invalid = 0;
1037 entry_ex->entry.flags.server = 1;
1039 realm = smb_krb5_principal_get_realm(
1040 mem_ctx, context, principal);
1041 if (realm == NULL) {
1042 ret = ENOMEM;
1043 goto out;
1046 /* Don't mark all requests for the krbtgt/realm as
1047 * 'change password', as otherwise we could get into
1048 * trouble, and not enforce the password expirty.
1049 * Instead, only do it when request is for the kpasswd service */
1050 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
1051 && krb5_princ_size(context, principal) == 2
1052 && (principal_comp_strcmp(context, principal, 0, "kadmin") == 0)
1053 && (principal_comp_strcmp(context, principal, 1, "changepw") == 0)
1054 && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
1055 entry_ex->entry.flags.change_pw = 1;
1058 TALLOC_FREE(realm);
1060 entry_ex->entry.flags.client = 0;
1061 entry_ex->entry.flags.forwardable = 1;
1062 entry_ex->entry.flags.ok_as_delegate = 1;
1063 } else if (is_rodc) {
1064 /* The RODC krbtgt account is like the main krbtgt,
1065 * but it does not have a changepw or kadmin
1066 * service */
1068 entry_ex->entry.valid_end = NULL;
1069 entry_ex->entry.pw_end = NULL;
1071 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
1072 entry_ex->entry.flags.client = 0;
1073 entry_ex->entry.flags.invalid = 0;
1074 entry_ex->entry.flags.server = 1;
1076 entry_ex->entry.flags.client = 0;
1077 entry_ex->entry.flags.forwardable = 1;
1078 entry_ex->entry.flags.ok_as_delegate = 0;
1079 } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1080 /* The account/password expiry only applies when the account is used as a
1081 * client (ie password login), not when used as a server */
1083 /* Make very well sure we don't use this for a client,
1084 * it could bypass the password restrictions */
1085 entry_ex->entry.flags.client = 0;
1087 entry_ex->entry.valid_end = NULL;
1088 entry_ex->entry.pw_end = NULL;
1090 } else {
1091 NTTIME must_change_time
1092 = samdb_result_nttime(msg,
1093 "msDS-UserPasswordExpiryTimeComputed",
1095 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
1096 entry_ex->entry.pw_end = NULL;
1097 } else {
1098 entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
1099 if (entry_ex->entry.pw_end == NULL) {
1100 ret = ENOMEM;
1101 goto out;
1103 *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
1106 acct_expiry = samdb_result_account_expires(msg);
1107 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
1108 entry_ex->entry.valid_end = NULL;
1109 } else {
1110 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
1111 if (entry_ex->entry.valid_end == NULL) {
1112 ret = ENOMEM;
1113 goto out;
1115 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
1119 entry_ex->entry.valid_start = NULL;
1121 entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life));
1122 if (entry_ex->entry.max_life == NULL) {
1123 ret = ENOMEM;
1124 goto out;
1127 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1128 *entry_ex->entry.max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
1129 } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
1130 *entry_ex->entry.max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
1131 } else {
1132 *entry_ex->entry.max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
1133 kdc_db_ctx->policy.usr_tkt_lifetime);
1136 entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_life));
1137 if (entry_ex->entry.max_renew == NULL) {
1138 ret = ENOMEM;
1139 goto out;
1142 *entry_ex->entry.max_renew = kdc_db_ctx->policy.renewal_lifetime;
1144 /* Get keys from the db */
1145 ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
1146 rid, is_rodc, userAccountControl,
1147 ent_type, entry_ex);
1148 if (ret) {
1149 /* Could be bogus data in the entry, or out of memory */
1150 goto out;
1153 p->msg = talloc_steal(p, msg);
1155 out:
1156 if (ret != 0) {
1157 /* This doesn't free ent itself, that is for the eventual caller to do */
1158 sdb_free_entry(entry_ex);
1159 ZERO_STRUCTP(entry_ex);
1160 } else {
1161 talloc_steal(kdc_db_ctx, entry_ex->ctx);
1164 return ret;
1168 * Construct an hdb_entry from a directory entry.
1169 * The kvno is what the remote client asked for
1171 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
1172 struct samba_kdc_db_context *kdc_db_ctx,
1173 TALLOC_CTX *mem_ctx, krb5_const_principal principal,
1174 enum trust_direction direction,
1175 struct ldb_dn *realm_dn,
1176 unsigned flags,
1177 uint32_t kvno,
1178 struct ldb_message *msg,
1179 struct sdb_entry_ex *entry_ex)
1181 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1182 const char *our_realm = lpcfg_realm(lp_ctx);
1183 char *partner_realm = NULL;
1184 const char *realm = NULL;
1185 const char *krbtgt_realm = NULL;
1186 DATA_BLOB password_utf16 = data_blob_null;
1187 DATA_BLOB password_utf8 = data_blob_null;
1188 struct samr_Password _password_hash;
1189 const struct samr_Password *password_hash = NULL;
1190 const struct ldb_val *password_val;
1191 struct trustAuthInOutBlob password_blob;
1192 struct samba_kdc_entry *p;
1193 bool use_previous = false;
1194 uint32_t current_kvno;
1195 uint32_t previous_kvno;
1196 uint32_t num_keys = 0;
1197 enum ndr_err_code ndr_err;
1198 int ret;
1199 unsigned int i;
1200 struct AuthenticationInformationArray *auth_array;
1201 struct timeval tv;
1202 NTTIME an_hour_ago;
1203 uint32_t *auth_kvno;
1204 bool preferr_current = false;
1205 uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
1206 struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
1207 NTSTATUS status;
1209 if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1210 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
1211 "msDS-SupportedEncryptionTypes",
1212 supported_enctypes);
1215 status = dsdb_trust_parse_tdo_info(mem_ctx, msg, &tdo);
1216 if (!NT_STATUS_IS_OK(status)) {
1217 krb5_clear_error_message(context);
1218 ret = ENOMEM;
1219 goto out;
1222 if (!(tdo->trust_direction & direction)) {
1223 krb5_clear_error_message(context);
1224 ret = SDB_ERR_NOENTRY;
1225 goto out;
1228 if (tdo->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
1230 * Only UPLEVEL domains support kerberos here,
1231 * as we don't support LSA_TRUST_TYPE_MIT.
1233 krb5_clear_error_message(context);
1234 ret = SDB_ERR_NOENTRY;
1235 goto out;
1238 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_CROSS_ORGANIZATION) {
1240 * We don't support selective authentication yet.
1242 krb5_clear_error_message(context);
1243 ret = SDB_ERR_NOENTRY;
1244 goto out;
1247 if (tdo->domain_name.string == NULL) {
1248 krb5_clear_error_message(context);
1249 ret = SDB_ERR_NOENTRY;
1250 goto out;
1252 partner_realm = strupper_talloc(mem_ctx, tdo->domain_name.string);
1253 if (partner_realm == NULL) {
1254 krb5_clear_error_message(context);
1255 ret = ENOMEM;
1256 goto out;
1259 if (direction == INBOUND) {
1260 realm = our_realm;
1261 krbtgt_realm = partner_realm;
1263 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
1264 } else { /* OUTBOUND */
1265 realm = partner_realm;
1266 krbtgt_realm = our_realm;
1268 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
1271 if (password_val == NULL) {
1272 krb5_clear_error_message(context);
1273 ret = SDB_ERR_NOENTRY;
1274 goto out;
1277 ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
1278 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1279 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1280 krb5_clear_error_message(context);
1281 ret = EINVAL;
1282 goto out;
1285 p = talloc_zero(mem_ctx, struct samba_kdc_entry);
1286 if (!p) {
1287 ret = ENOMEM;
1288 goto out;
1291 p->is_trust = true;
1292 p->kdc_db_ctx = kdc_db_ctx;
1293 p->realm_dn = realm_dn;
1295 talloc_set_destructor(p, samba_kdc_entry_destructor);
1297 /* make sure we do not have bogus data in there */
1298 memset(&entry_ex->entry, 0, sizeof(struct sdb_entry));
1300 entry_ex->ctx = p;
1302 /* use 'whenCreated' */
1303 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1304 /* use 'kadmin' for now (needed by mit_samba) */
1305 ret = smb_krb5_make_principal(context,
1306 &entry_ex->entry.created_by.principal,
1307 realm, "kadmin", NULL);
1308 if (ret) {
1309 krb5_clear_error_message(context);
1310 goto out;
1314 * We always need to generate the canonicalized principal
1315 * with the values of our database.
1317 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, realm,
1318 "krbtgt", krbtgt_realm, NULL);
1319 if (ret) {
1320 krb5_clear_error_message(context);
1321 goto out;
1323 smb_krb5_principal_set_type(context, entry_ex->entry.principal,
1324 KRB5_NT_SRV_INST);
1326 entry_ex->entry.valid_start = NULL;
1328 /* we need to work out if we are going to use the current or
1329 * the previous password hash.
1330 * We base this on the kvno the client passes in. If the kvno
1331 * passed in is equal to the current kvno in our database then
1332 * we use the current structure. If it is the current kvno-1,
1333 * then we use the previous substrucure.
1337 * Windows preferrs the previous key for one hour.
1339 tv = timeval_current();
1340 if (tv.tv_sec > 3600) {
1341 tv.tv_sec -= 3600;
1343 an_hour_ago = timeval_to_nttime(&tv);
1345 /* first work out the current kvno */
1346 current_kvno = 0;
1347 for (i=0; i < password_blob.count; i++) {
1348 struct AuthenticationInformation *a =
1349 &password_blob.current.array[i];
1351 if (a->LastUpdateTime <= an_hour_ago) {
1352 preferr_current = true;
1355 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1356 current_kvno = a->AuthInfo.version.version;
1359 if (current_kvno == 0) {
1360 previous_kvno = 255;
1361 } else {
1362 previous_kvno = current_kvno - 1;
1364 for (i=0; i < password_blob.count; i++) {
1365 struct AuthenticationInformation *a =
1366 &password_blob.previous.array[i];
1368 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1369 previous_kvno = a->AuthInfo.version.version;
1373 /* work out whether we will use the previous or current
1374 password */
1375 if (password_blob.previous.count == 0) {
1376 /* there is no previous password */
1377 use_previous = false;
1378 } else if (!(flags & SDB_F_KVNO_SPECIFIED)) {
1380 * If not specified we use the lowest kvno
1381 * for the first hour after an update.
1383 if (preferr_current) {
1384 use_previous = false;
1385 } else if (previous_kvno < current_kvno) {
1386 use_previous = true;
1387 } else {
1388 use_previous = false;
1390 } else if (kvno == current_kvno) {
1392 * Exact match ...
1394 use_previous = false;
1395 } else if (kvno == previous_kvno) {
1397 * Exact match ...
1399 use_previous = true;
1400 } else {
1402 * Fallback to the current one for anything else
1404 use_previous = false;
1407 if (use_previous) {
1408 auth_array = &password_blob.previous;
1409 auth_kvno = &previous_kvno;
1410 } else {
1411 auth_array = &password_blob.current;
1412 auth_kvno = &current_kvno;
1415 /* use the kvno the client specified, if available */
1416 if (flags & SDB_F_KVNO_SPECIFIED) {
1417 entry_ex->entry.kvno = kvno;
1418 } else {
1419 entry_ex->entry.kvno = *auth_kvno;
1422 for (i=0; i < auth_array->count; i++) {
1423 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1424 bool ok;
1426 password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
1427 auth_array->array[i].AuthInfo.clear.size);
1428 if (password_utf16.length == 0) {
1429 break;
1432 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1433 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
1434 if (password_hash == NULL) {
1435 num_keys += 1;
1437 password_hash = &_password_hash;
1440 if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1441 break;
1444 ok = convert_string_talloc(mem_ctx,
1445 CH_UTF16MUNGED, CH_UTF8,
1446 password_utf16.data,
1447 password_utf16.length,
1448 (void *)&password_utf8.data,
1449 &password_utf8.length);
1450 if (!ok) {
1451 krb5_clear_error_message(context);
1452 ret = ENOMEM;
1453 goto out;
1456 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1457 num_keys += 1;
1459 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1460 num_keys += 1;
1462 break;
1463 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
1464 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1465 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
1466 num_keys += 1;
1471 /* Must have found a cleartext or MD4 password */
1472 if (num_keys == 0) {
1473 DEBUG(1,(__location__ ": no usable key found\n"));
1474 krb5_clear_error_message(context);
1475 ret = SDB_ERR_NOENTRY;
1476 goto out;
1479 entry_ex->entry.keys.val = calloc(num_keys, sizeof(struct sdb_key));
1480 if (entry_ex->entry.keys.val == NULL) {
1481 krb5_clear_error_message(context);
1482 ret = ENOMEM;
1483 goto out;
1486 if (password_utf8.length != 0) {
1487 struct sdb_key key = {};
1488 krb5_const_principal salt_principal = entry_ex->entry.principal;
1489 krb5_data salt;
1490 krb5_data cleartext_data;
1492 cleartext_data.data = discard_const_p(char, password_utf8.data);
1493 cleartext_data.length = password_utf8.length;
1495 ret = smb_krb5_get_pw_salt(context,
1496 salt_principal,
1497 &salt);
1498 if (ret != 0) {
1499 goto out;
1502 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1503 ret = smb_krb5_create_key_from_string(context,
1504 salt_principal,
1505 &salt,
1506 &cleartext_data,
1507 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
1508 &key.key);
1509 if (ret != 0) {
1510 smb_krb5_free_data_contents(context, &salt);
1511 goto out;
1514 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1515 entry_ex->entry.keys.len++;
1518 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1519 ret = smb_krb5_create_key_from_string(context,
1520 salt_principal,
1521 &salt,
1522 &cleartext_data,
1523 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
1524 &key.key);
1525 if (ret != 0) {
1526 smb_krb5_free_data_contents(context, &salt);
1527 goto out;
1530 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1531 entry_ex->entry.keys.len++;
1534 smb_krb5_free_data_contents(context, &salt);
1537 if (password_hash != NULL) {
1538 struct sdb_key key = {};
1540 ret = smb_krb5_keyblock_init_contents(context,
1541 ENCTYPE_ARCFOUR_HMAC,
1542 password_hash->hash,
1543 sizeof(password_hash->hash),
1544 &key.key);
1545 if (ret != 0) {
1546 goto out;
1549 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1550 entry_ex->entry.keys.len++;
1553 entry_ex->entry.flags = int2SDBFlags(0);
1554 entry_ex->entry.flags.immutable = 1;
1555 entry_ex->entry.flags.invalid = 0;
1556 entry_ex->entry.flags.server = 1;
1557 entry_ex->entry.flags.require_preauth = 1;
1559 entry_ex->entry.pw_end = NULL;
1561 entry_ex->entry.max_life = NULL;
1563 entry_ex->entry.max_renew = NULL;
1565 /* Match Windows behavior and allow forwardable flag in cross-realm. */
1566 entry_ex->entry.flags.forwardable = 1;
1568 ret = samba_kdc_sort_encryption_keys(entry_ex);
1569 if (ret != 0) {
1570 krb5_clear_error_message(context);
1571 ret = ENOMEM;
1572 goto out;
1575 p->msg = talloc_steal(p, msg);
1577 out:
1578 TALLOC_FREE(partner_realm);
1580 if (ret != 0) {
1581 /* This doesn't free ent itself, that is for the eventual caller to do */
1582 sdb_free_entry(entry_ex);
1583 } else {
1584 talloc_steal(kdc_db_ctx, entry_ex->ctx);
1587 return ret;
1591 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
1592 TALLOC_CTX *mem_ctx,
1593 const char *realm,
1594 struct ldb_dn *realm_dn,
1595 struct ldb_message **pmsg)
1597 NTSTATUS status;
1598 const char * const *attrs = trust_attrs;
1600 status = dsdb_trust_search_tdo(ldb_ctx, realm, realm,
1601 attrs, mem_ctx, pmsg);
1602 if (NT_STATUS_IS_OK(status)) {
1603 return 0;
1604 } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1605 return SDB_ERR_NOENTRY;
1606 } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1607 int ret = ENOMEM;
1608 krb5_set_error_message(context, ret, "get_sam_result_trust: out of memory");
1609 return ret;
1610 } else {
1611 int ret = EINVAL;
1612 krb5_set_error_message(context, ret, "get_sam_result_trust: %s", nt_errstr(status));
1613 return ret;
1617 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1618 struct samba_kdc_db_context *kdc_db_ctx,
1619 TALLOC_CTX *mem_ctx,
1620 krb5_const_principal principal,
1621 const char **attrs,
1622 struct ldb_dn **realm_dn,
1623 struct ldb_message **msg)
1625 NTSTATUS nt_status;
1626 char *principal_string = NULL;
1628 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1629 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
1630 principal, 0);
1631 if (principal_string == NULL) {
1632 return ENOMEM;
1634 } else {
1635 char *principal_string_m = NULL;
1636 krb5_error_code ret;
1638 ret = krb5_unparse_name(context, principal, &principal_string_m);
1639 if (ret != 0) {
1640 return ret;
1643 principal_string = talloc_strdup(mem_ctx, principal_string_m);
1644 SAFE_FREE(principal_string_m);
1645 if (principal_string == NULL) {
1646 return ENOMEM;
1650 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1651 mem_ctx, principal_string, attrs,
1652 realm_dn, msg);
1653 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1654 krb5_principal fallback_principal = NULL;
1655 unsigned int num_comp;
1656 char *fallback_realm = NULL;
1657 char *fallback_account = NULL;
1658 krb5_error_code ret;
1660 ret = krb5_parse_name(context, principal_string,
1661 &fallback_principal);
1662 TALLOC_FREE(principal_string);
1663 if (ret != 0) {
1664 return ret;
1667 num_comp = krb5_princ_size(context, fallback_principal);
1668 fallback_realm = smb_krb5_principal_get_realm(
1669 mem_ctx, context, fallback_principal);
1670 if (fallback_realm == NULL) {
1671 krb5_free_principal(context, fallback_principal);
1672 return ENOMEM;
1675 if (num_comp == 1) {
1676 size_t len;
1678 fallback_account = smb_krb5_principal_get_comp_string(mem_ctx,
1679 context, fallback_principal, 0);
1680 if (fallback_account == NULL) {
1681 krb5_free_principal(context, fallback_principal);
1682 TALLOC_FREE(fallback_realm);
1683 return ENOMEM;
1686 len = strlen(fallback_account);
1687 if (len >= 2 && fallback_account[len - 1] == '$') {
1688 TALLOC_FREE(fallback_account);
1691 krb5_free_principal(context, fallback_principal);
1692 fallback_principal = NULL;
1694 if (fallback_account != NULL) {
1695 char *with_dollar;
1697 with_dollar = talloc_asprintf(mem_ctx, "%s$",
1698 fallback_account);
1699 if (with_dollar == NULL) {
1700 TALLOC_FREE(fallback_realm);
1701 return ENOMEM;
1703 TALLOC_FREE(fallback_account);
1705 ret = smb_krb5_make_principal(context,
1706 &fallback_principal,
1707 fallback_realm,
1708 with_dollar, NULL);
1709 TALLOC_FREE(with_dollar);
1710 if (ret != 0) {
1711 TALLOC_FREE(fallback_realm);
1712 return ret;
1715 TALLOC_FREE(fallback_realm);
1717 if (fallback_principal != NULL) {
1718 char *fallback_string = NULL;
1720 ret = krb5_unparse_name(context,
1721 fallback_principal,
1722 &fallback_string);
1723 if (ret != 0) {
1724 krb5_free_principal(context, fallback_principal);
1725 return ret;
1728 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1729 mem_ctx,
1730 fallback_string,
1731 attrs,
1732 realm_dn, msg);
1733 SAFE_FREE(fallback_string);
1735 krb5_free_principal(context, fallback_principal);
1736 fallback_principal = NULL;
1738 TALLOC_FREE(principal_string);
1740 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1741 return SDB_ERR_NOENTRY;
1742 } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1743 return ENOMEM;
1744 } else if (!NT_STATUS_IS_OK(nt_status)) {
1745 return EINVAL;
1748 return 0;
1751 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1752 struct samba_kdc_db_context *kdc_db_ctx,
1753 TALLOC_CTX *mem_ctx,
1754 krb5_const_principal principal,
1755 unsigned flags,
1756 struct sdb_entry_ex *entry_ex) {
1757 struct ldb_dn *realm_dn;
1758 krb5_error_code ret;
1759 struct ldb_message *msg = NULL;
1761 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1762 mem_ctx, principal, user_attrs,
1763 &realm_dn, &msg);
1764 if (ret != 0) {
1765 return ret;
1768 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1769 principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1770 flags,
1771 realm_dn, msg, entry_ex);
1772 return ret;
1775 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1776 struct samba_kdc_db_context *kdc_db_ctx,
1777 TALLOC_CTX *mem_ctx,
1778 krb5_const_principal principal,
1779 unsigned flags,
1780 uint32_t kvno,
1781 struct sdb_entry_ex *entry_ex)
1783 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1784 krb5_error_code ret;
1785 struct ldb_message *msg = NULL;
1786 struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1787 char *realm_from_princ;
1788 char *realm_princ_comp = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 1);
1790 realm_from_princ = smb_krb5_principal_get_realm(
1791 mem_ctx, context, principal);
1792 if (realm_from_princ == NULL) {
1793 /* can't happen */
1794 return SDB_ERR_NOENTRY;
1797 if (krb5_princ_size(context, principal) != 2
1798 || (principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME) != 0)) {
1799 /* Not a krbtgt */
1800 return SDB_ERR_NOENTRY;
1803 /* krbtgt case. Either us or a trusted realm */
1805 if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
1806 && lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp)) {
1807 /* us, or someone quite like us */
1808 /* Cludge, cludge cludge. If the realm part of krbtgt/realm,
1809 * is in our db, then direct the caller at our primary
1810 * krbtgt */
1812 int lret;
1813 unsigned int krbtgt_number;
1814 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
1815 trust tickets. We don't yet know what this means, but we do
1816 seem to need to treat it as unspecified */
1817 if (flags & SDB_F_KVNO_SPECIFIED) {
1818 krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
1819 if (kdc_db_ctx->rodc) {
1820 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1821 return SDB_ERR_NOT_FOUND_HERE;
1824 } else {
1825 krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1828 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1829 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1830 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1831 krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
1832 "(objectClass=user)");
1833 } else {
1834 /* We need to look up an RODC krbtgt (perhaps
1835 * ours, if we are an RODC, perhaps another
1836 * RODC if we are a read-write DC */
1837 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1838 &msg, realm_dn, LDB_SCOPE_SUBTREE,
1839 krbtgt_attrs,
1840 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1841 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1844 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1845 krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1846 (unsigned)(krbtgt_number));
1847 krb5_set_error_message(context, SDB_ERR_NOENTRY,
1848 "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1849 (unsigned)(krbtgt_number));
1850 return SDB_ERR_NOENTRY;
1851 } else if (lret != LDB_SUCCESS) {
1852 krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1853 (unsigned)(krbtgt_number));
1854 krb5_set_error_message(context, SDB_ERR_NOENTRY,
1855 "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1856 (unsigned)(krbtgt_number));
1857 return SDB_ERR_NOENTRY;
1860 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1861 principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1862 flags, realm_dn, msg, entry_ex);
1863 if (ret != 0) {
1864 krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1866 return ret;
1868 } else {
1869 enum trust_direction direction = UNKNOWN;
1870 const char *realm = NULL;
1872 /* Either an inbound or outbound trust */
1874 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
1875 /* look for inbound trust */
1876 direction = INBOUND;
1877 realm = realm_princ_comp;
1878 } else if (principal_comp_strcasecmp(context, principal, 1, lpcfg_realm(lp_ctx)) == 0) {
1879 /* look for outbound trust */
1880 direction = OUTBOUND;
1881 realm = realm_from_princ;
1882 } else {
1883 krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1884 realm_from_princ,
1885 realm_princ_comp);
1886 krb5_set_error_message(context, SDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1887 realm_from_princ,
1888 realm_princ_comp);
1889 return SDB_ERR_NOENTRY;
1892 /* Trusted domains are under CN=system */
1894 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1895 mem_ctx,
1896 realm, realm_dn, &msg);
1898 if (ret != 0) {
1899 krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1900 krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1901 return ret;
1904 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1905 principal, direction,
1906 realm_dn, flags, kvno, msg, entry_ex);
1907 if (ret != 0) {
1908 krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed for %s",
1909 ldb_dn_get_linearized(msg->dn));
1910 krb5_set_error_message(context, ret, "samba_kdc_fetch: "
1911 "trust_message2entry failed for %s",
1912 ldb_dn_get_linearized(msg->dn));
1914 return ret;
1919 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1920 struct samba_kdc_db_context *kdc_db_ctx,
1921 TALLOC_CTX *mem_ctx,
1922 krb5_const_principal principal,
1923 unsigned flags,
1924 const char **attrs,
1925 struct ldb_dn **realm_dn,
1926 struct ldb_message **msg)
1928 krb5_error_code ret;
1929 if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
1930 && krb5_princ_size(context, principal) >= 2) {
1931 /* 'normal server' case */
1932 int ldb_ret;
1933 NTSTATUS nt_status;
1934 struct ldb_dn *user_dn;
1935 char *principal_string;
1937 ret = krb5_unparse_name_flags(context, principal,
1938 KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1939 &principal_string);
1940 if (ret != 0) {
1941 return ret;
1944 /* At this point we may find the host is known to be
1945 * in a different realm, so we should generate a
1946 * referral instead */
1947 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1948 mem_ctx, principal_string,
1949 &user_dn, realm_dn);
1950 free(principal_string);
1952 if (!NT_STATUS_IS_OK(nt_status)) {
1953 return SDB_ERR_NOENTRY;
1956 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1957 mem_ctx,
1958 msg, user_dn, LDB_SCOPE_BASE,
1959 attrs,
1960 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1961 "(objectClass=*)");
1962 if (ldb_ret != LDB_SUCCESS) {
1963 return SDB_ERR_NOENTRY;
1965 return 0;
1966 } else if (!(flags & SDB_F_FOR_AS_REQ)
1967 && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1969 * The behaviour of accepting an
1970 * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
1971 * containing a UPN only applies to TGS-REQ packets,
1972 * not AS-REQ packets.
1974 return samba_kdc_lookup_client(context, kdc_db_ctx,
1975 mem_ctx, principal, attrs,
1976 realm_dn, msg);
1977 } else {
1979 * This case is for:
1980 * - the AS-REQ, where we only accept
1981 * samAccountName based lookups for the server, no
1982 * matter if the name is an
1983 * KRB5_NT_ENTERPRISE_PRINCIPAL or not
1984 * - for the TGS-REQ when we are not given an
1985 * KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
1986 * only lookup samAccountName based names.
1988 int lret;
1989 char *short_princ;
1990 krb5_principal enterprise_principal = NULL;
1991 krb5_const_principal used_principal = NULL;
1992 char *name1 = NULL;
1993 size_t len1 = 0;
1994 char *filter = NULL;
1996 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1997 char *str = NULL;
1998 /* Need to reparse the enterprise principal to find the real target */
1999 if (krb5_princ_size(context, principal) != 1) {
2000 ret = KRB5_PARSE_MALFORMED;
2001 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
2002 "enterprise principal with wrong (%d) number of components",
2003 krb5_princ_size(context, principal));
2004 return ret;
2006 str = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0);
2007 if (str == NULL) {
2008 return KRB5_PARSE_MALFORMED;
2010 ret = krb5_parse_name(context, str,
2011 &enterprise_principal);
2012 talloc_free(str);
2013 if (ret) {
2014 return ret;
2016 used_principal = enterprise_principal;
2017 } else {
2018 used_principal = principal;
2021 /* server as client principal case, but we must not lookup userPrincipalNames */
2022 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2024 /* TODO: Check if it is our realm, otherwise give referral */
2026 ret = krb5_unparse_name_flags(context, used_principal,
2027 KRB5_PRINCIPAL_UNPARSE_NO_REALM |
2028 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2029 &short_princ);
2030 used_principal = NULL;
2031 krb5_free_principal(context, enterprise_principal);
2032 enterprise_principal = NULL;
2034 if (ret != 0) {
2035 krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
2036 krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
2037 return ret;
2040 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
2041 SAFE_FREE(short_princ);
2042 if (name1 == NULL) {
2043 return ENOMEM;
2045 len1 = strlen(name1);
2046 if (len1 >= 1 && name1[len1 - 1] != '$') {
2047 filter = talloc_asprintf(mem_ctx,
2048 "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
2049 name1, name1);
2050 if (filter == NULL) {
2051 return ENOMEM;
2053 } else {
2054 filter = talloc_asprintf(mem_ctx,
2055 "(&(objectClass=user)(samAccountName=%s))",
2056 name1);
2057 if (filter == NULL) {
2058 return ENOMEM;
2062 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
2063 *realm_dn, LDB_SCOPE_SUBTREE,
2064 attrs,
2065 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2066 "%s", filter);
2067 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2068 DEBUG(10, ("Failed to find an entry for %s filter:%s\n",
2069 name1, filter));
2070 return SDB_ERR_NOENTRY;
2072 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
2073 DEBUG(10, ("Failed to find unique entry for %s filter:%s\n",
2074 name1, filter));
2075 return SDB_ERR_NOENTRY;
2077 if (lret != LDB_SUCCESS) {
2078 DEBUG(0, ("Failed single search for %s - %s\n",
2079 name1, ldb_errstring(kdc_db_ctx->samdb)));
2080 return SDB_ERR_NOENTRY;
2082 return 0;
2084 return SDB_ERR_NOENTRY;
2089 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
2090 struct samba_kdc_db_context *kdc_db_ctx,
2091 TALLOC_CTX *mem_ctx,
2092 krb5_const_principal principal,
2093 unsigned flags,
2094 struct sdb_entry_ex *entry_ex)
2096 krb5_error_code ret;
2097 struct ldb_dn *realm_dn;
2098 struct ldb_message *msg;
2100 ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
2101 flags, server_attrs, &realm_dn, &msg);
2102 if (ret != 0) {
2103 return ret;
2106 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2107 principal, SAMBA_KDC_ENT_TYPE_SERVER,
2108 flags,
2109 realm_dn, msg, entry_ex);
2110 if (ret != 0) {
2111 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
2114 return ret;
2117 static krb5_error_code samba_kdc_lookup_realm(krb5_context context,
2118 struct samba_kdc_db_context *kdc_db_ctx,
2119 TALLOC_CTX *mem_ctx,
2120 krb5_const_principal principal,
2121 unsigned flags,
2122 struct sdb_entry_ex *entry_ex)
2124 TALLOC_CTX *frame = talloc_stackframe();
2125 NTSTATUS status;
2126 krb5_error_code ret;
2127 bool check_realm = false;
2128 const char *realm = NULL;
2129 struct dsdb_trust_routing_table *trt = NULL;
2130 const struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
2131 unsigned int num_comp;
2132 bool ok;
2133 char *upper = NULL;
2135 num_comp = krb5_princ_size(context, principal);
2137 if (flags & SDB_F_GET_CLIENT) {
2138 if (flags & SDB_F_FOR_AS_REQ) {
2139 check_realm = true;
2142 if (flags & SDB_F_GET_SERVER) {
2143 if (flags & SDB_F_FOR_TGS_REQ) {
2144 check_realm = true;
2148 if (!check_realm) {
2149 TALLOC_FREE(frame);
2150 return 0;
2153 realm = smb_krb5_principal_get_realm(frame, context, principal);
2154 if (realm == NULL) {
2155 TALLOC_FREE(frame);
2156 return ENOMEM;
2160 * The requested realm needs to be our own
2162 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2163 if (!ok) {
2165 * The request is not for us...
2167 TALLOC_FREE(frame);
2168 return SDB_ERR_NOENTRY;
2171 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2172 char *principal_string = NULL;
2173 krb5_principal enterprise_principal = NULL;
2174 char *enterprise_realm = NULL;
2176 if (num_comp != 1) {
2177 TALLOC_FREE(frame);
2178 return SDB_ERR_NOENTRY;
2181 principal_string = smb_krb5_principal_get_comp_string(frame, context,
2182 principal, 0);
2183 if (principal_string == NULL) {
2184 TALLOC_FREE(frame);
2185 return ENOMEM;
2188 ret = krb5_parse_name(context, principal_string,
2189 &enterprise_principal);
2190 TALLOC_FREE(principal_string);
2191 if (ret) {
2192 TALLOC_FREE(frame);
2193 return ret;
2196 enterprise_realm = smb_krb5_principal_get_realm(
2197 frame, context, enterprise_principal);
2198 krb5_free_principal(context, enterprise_principal);
2199 if (enterprise_realm != NULL) {
2200 realm = enterprise_realm;
2204 if (flags & SDB_F_GET_SERVER) {
2205 char *service_realm = NULL;
2207 ret = principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME);
2208 if (ret == 0) {
2210 * we need to search krbtgt/ locally
2212 TALLOC_FREE(frame);
2213 return 0;
2217 * We need to check the last component against the routing table.
2219 * Note this works only with 2 or 3 component principals, e.g:
2221 * servicePrincipalName: ldap/W2K8R2-219.bla.base
2222 * servicePrincipalName: ldap/W2K8R2-219.bla.base/bla.base
2223 * servicePrincipalName: ldap/W2K8R2-219.bla.base/ForestDnsZones.bla.base
2224 * servicePrincipalName: ldap/W2K8R2-219.bla.base/DomainDnsZones.bla.base
2227 if (num_comp == 2 || num_comp == 3) {
2228 service_realm = smb_krb5_principal_get_comp_string(frame,
2229 context,
2230 principal,
2231 num_comp - 1);
2234 if (service_realm != NULL) {
2235 realm = service_realm;
2239 ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2240 if (ok) {
2242 * skip the expensive routing lookup
2244 TALLOC_FREE(frame);
2245 return 0;
2248 status = dsdb_trust_routing_table_load(kdc_db_ctx->samdb,
2249 frame, &trt);
2250 if (!NT_STATUS_IS_OK(status)) {
2251 TALLOC_FREE(frame);
2252 return EINVAL;
2255 tdo = dsdb_trust_routing_by_name(trt, realm);
2256 if (tdo == NULL) {
2258 * This principal has to be local
2260 TALLOC_FREE(frame);
2261 return 0;
2264 if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
2266 * TODO: handle the routing within the forest
2268 * This should likely be handled in
2269 * samba_kdc_message2entry() in case we're
2270 * a global catalog. We'd need to check
2271 * if realm_dn is our own domain and derive
2272 * the dns domain name from realm_dn and check that
2273 * against the routing table or fallback to
2274 * the tdo we found here.
2276 * But for now we don't support multiple domains
2277 * in our forest correctly anyway.
2279 * Just search in our local database.
2281 TALLOC_FREE(frame);
2282 return 0;
2285 ZERO_STRUCT(entry_ex->entry);
2287 ret = krb5_copy_principal(context, principal,
2288 &entry_ex->entry.principal);
2289 if (ret) {
2290 TALLOC_FREE(frame);
2291 return ret;
2294 upper = strupper_talloc(frame, tdo->domain_name.string);
2295 if (upper == NULL) {
2296 TALLOC_FREE(frame);
2297 return ENOMEM;
2300 ret = smb_krb5_principal_set_realm(context,
2301 entry_ex->entry.principal,
2302 upper);
2303 if (ret) {
2304 TALLOC_FREE(frame);
2305 return ret;
2308 TALLOC_FREE(frame);
2309 return SDB_ERR_WRONG_REALM;
2312 krb5_error_code samba_kdc_fetch(krb5_context context,
2313 struct samba_kdc_db_context *kdc_db_ctx,
2314 krb5_const_principal principal,
2315 unsigned flags,
2316 krb5_kvno kvno,
2317 struct sdb_entry_ex *entry_ex)
2319 krb5_error_code ret = SDB_ERR_NOENTRY;
2320 TALLOC_CTX *mem_ctx;
2322 mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
2323 if (!mem_ctx) {
2324 ret = ENOMEM;
2325 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2326 return ret;
2329 ret = samba_kdc_lookup_realm(context, kdc_db_ctx, mem_ctx,
2330 principal, flags, entry_ex);
2331 if (ret != 0) {
2332 goto done;
2335 ret = SDB_ERR_NOENTRY;
2337 if (flags & SDB_F_GET_CLIENT) {
2338 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2339 if (ret != SDB_ERR_NOENTRY) goto done;
2341 if (flags & SDB_F_GET_SERVER) {
2342 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
2343 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2344 if (ret != SDB_ERR_NOENTRY) goto done;
2346 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
2347 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2348 if (ret != SDB_ERR_NOENTRY) goto done;
2350 if (flags & SDB_F_GET_KRBTGT) {
2351 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2352 if (ret != SDB_ERR_NOENTRY) goto done;
2355 done:
2356 talloc_free(mem_ctx);
2357 return ret;
2360 struct samba_kdc_seq {
2361 unsigned int index;
2362 unsigned int count;
2363 struct ldb_message **msgs;
2364 struct ldb_dn *realm_dn;
2367 static krb5_error_code samba_kdc_seq(krb5_context context,
2368 struct samba_kdc_db_context *kdc_db_ctx,
2369 struct sdb_entry_ex *entry)
2371 krb5_error_code ret;
2372 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2373 const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
2374 struct ldb_message *msg = NULL;
2375 const char *sAMAccountName = NULL;
2376 krb5_principal principal = NULL;
2377 TALLOC_CTX *mem_ctx;
2379 if (!priv) {
2380 return SDB_ERR_NOENTRY;
2383 mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
2385 if (!mem_ctx) {
2386 ret = ENOMEM;
2387 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
2388 return ret;
2391 while (priv->index < priv->count) {
2392 msg = priv->msgs[priv->index++];
2394 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
2395 if (sAMAccountName != NULL) {
2396 break;
2400 if (sAMAccountName == NULL) {
2401 ret = SDB_ERR_NOENTRY;
2402 goto out;
2405 ret = smb_krb5_make_principal(context, &principal,
2406 realm, sAMAccountName, NULL);
2407 if (ret != 0) {
2408 goto out;
2411 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2412 principal, SAMBA_KDC_ENT_TYPE_ANY,
2413 SDB_F_ADMIN_DATA|SDB_F_GET_ANY,
2414 priv->realm_dn, msg, entry);
2416 out:
2417 if (principal != NULL) {
2418 krb5_free_principal(context, principal);
2421 if (ret != 0) {
2422 TALLOC_FREE(priv);
2423 kdc_db_ctx->seq_ctx = NULL;
2424 } else {
2425 talloc_free(mem_ctx);
2428 return ret;
2431 krb5_error_code samba_kdc_firstkey(krb5_context context,
2432 struct samba_kdc_db_context *kdc_db_ctx,
2433 struct sdb_entry_ex *entry)
2435 struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
2436 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2437 char *realm;
2438 struct ldb_result *res = NULL;
2439 krb5_error_code ret;
2440 TALLOC_CTX *mem_ctx;
2441 int lret;
2443 if (priv) {
2444 TALLOC_FREE(priv);
2445 kdc_db_ctx->seq_ctx = NULL;
2448 priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
2449 if (!priv) {
2450 ret = ENOMEM;
2451 krb5_set_error_message(context, ret, "talloc: out of memory");
2452 return ret;
2455 priv->index = 0;
2456 priv->msgs = NULL;
2457 priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
2458 priv->count = 0;
2460 mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
2462 if (!mem_ctx) {
2463 ret = ENOMEM;
2464 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
2465 return ret;
2468 ret = krb5_get_default_realm(context, &realm);
2469 if (ret != 0) {
2470 TALLOC_FREE(priv);
2471 return ret;
2473 krb5_free_default_realm(context, realm);
2475 lret = dsdb_search(ldb_ctx, priv, &res,
2476 priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
2477 DSDB_SEARCH_NO_GLOBAL_CATALOG,
2478 "(objectClass=user)");
2480 if (lret != LDB_SUCCESS) {
2481 TALLOC_FREE(priv);
2482 return SDB_ERR_NOENTRY;
2485 priv->count = res->count;
2486 priv->msgs = talloc_steal(priv, res->msgs);
2487 talloc_free(res);
2489 kdc_db_ctx->seq_ctx = priv;
2491 ret = samba_kdc_seq(context, kdc_db_ctx, entry);
2493 if (ret != 0) {
2494 TALLOC_FREE(priv);
2495 kdc_db_ctx->seq_ctx = NULL;
2496 } else {
2497 talloc_free(mem_ctx);
2499 return ret;
2502 krb5_error_code samba_kdc_nextkey(krb5_context context,
2503 struct samba_kdc_db_context *kdc_db_ctx,
2504 struct sdb_entry_ex *entry)
2506 return samba_kdc_seq(context, kdc_db_ctx, entry);
2509 /* Check if a given entry may delegate or do s4u2self to this target principal
2511 * This is currently a very nasty hack - allowing only delegation to itself.
2513 krb5_error_code
2514 samba_kdc_check_s4u2self(krb5_context context,
2515 struct samba_kdc_db_context *kdc_db_ctx,
2516 struct samba_kdc_entry *skdc_entry,
2517 krb5_const_principal target_principal)
2519 krb5_error_code ret;
2520 struct ldb_dn *realm_dn;
2521 struct ldb_message *msg;
2522 struct dom_sid *orig_sid;
2523 struct dom_sid *target_sid;
2524 const char *delegation_check_attrs[] = {
2525 "objectSid", NULL
2528 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2self");
2530 if (!mem_ctx) {
2531 ret = ENOMEM;
2532 krb5_set_error_message(context, ret, "samba_kdc_check_s4u2self: talloc_named() failed!");
2533 return ret;
2536 ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
2537 SDB_F_GET_CLIENT|SDB_F_GET_SERVER,
2538 delegation_check_attrs, &realm_dn, &msg);
2540 if (ret != 0) {
2541 talloc_free(mem_ctx);
2542 return ret;
2545 orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2546 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2548 /* Allow delegation to the same principal, even if by a different
2549 * name. The easy and safe way to prove this is by SID
2550 * comparison */
2551 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2552 talloc_free(mem_ctx);
2553 return KRB5KDC_ERR_BADOPTION;
2556 talloc_free(mem_ctx);
2557 return ret;
2560 /* Certificates printed by a the Certificate Authority might have a
2561 * slightly different form of the user principal name to that in the
2562 * database. Allow a mismatch where they both refer to the same
2563 * SID */
2565 krb5_error_code
2566 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
2567 struct samba_kdc_db_context *kdc_db_ctx,
2568 struct samba_kdc_entry *skdc_entry,
2569 krb5_const_principal certificate_principal)
2571 krb5_error_code ret;
2572 struct ldb_dn *realm_dn;
2573 struct ldb_message *msg;
2574 struct dom_sid *orig_sid;
2575 struct dom_sid *target_sid;
2576 const char *ms_upn_check_attrs[] = {
2577 "objectSid", NULL
2580 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
2582 if (!mem_ctx) {
2583 ret = ENOMEM;
2584 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2585 return ret;
2588 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2589 mem_ctx, certificate_principal,
2590 ms_upn_check_attrs, &realm_dn, &msg);
2592 if (ret != 0) {
2593 talloc_free(mem_ctx);
2594 return ret;
2597 orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2598 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2600 /* Consider these to be the same principal, even if by a different
2601 * name. The easy and safe way to prove this is by SID
2602 * comparison */
2603 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2604 talloc_free(mem_ctx);
2605 #if defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
2606 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
2607 #else /* Heimdal (where this is an enum) */
2608 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
2609 #endif
2612 talloc_free(mem_ctx);
2613 return ret;
2617 * Check if a given entry may delegate to this target principal
2618 * with S4U2Proxy.
2620 krb5_error_code
2621 samba_kdc_check_s4u2proxy(krb5_context context,
2622 struct samba_kdc_db_context *kdc_db_ctx,
2623 struct samba_kdc_entry *skdc_entry,
2624 krb5_const_principal target_principal)
2626 krb5_error_code ret;
2627 char *tmp = NULL;
2628 const char *client_dn = NULL;
2629 const char *target_principal_name = NULL;
2630 struct ldb_message_element *el;
2631 struct ldb_val val;
2632 unsigned int i;
2633 bool found = false;
2635 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
2637 if (!mem_ctx) {
2638 ret = ENOMEM;
2639 krb5_set_error_message(context, ret,
2640 "samba_kdc_check_s4u2proxy:"
2641 " talloc_named() failed!");
2642 return ret;
2645 client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
2646 if (!client_dn) {
2647 if (errno == 0) {
2648 errno = ENOMEM;
2650 ret = errno;
2651 krb5_set_error_message(context, ret,
2652 "samba_kdc_check_s4u2proxy:"
2653 " ldb_dn_get_linearized() failed!");
2654 return ret;
2658 * The main heimdal code already checked that the target_principal
2659 * belongs to the same realm as the client.
2661 * So we just need the principal without the realm,
2662 * as that is what is configured in the "msDS-AllowedToDelegateTo"
2663 * attribute.
2665 ret = krb5_unparse_name_flags(context, target_principal,
2666 KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
2667 if (ret) {
2668 talloc_free(mem_ctx);
2669 krb5_set_error_message(context, ret,
2670 "samba_kdc_check_s4u2proxy:"
2671 " krb5_unparse_name() failed!");
2672 return ret;
2674 DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
2675 client_dn, tmp));
2677 target_principal_name = talloc_strdup(mem_ctx, tmp);
2678 SAFE_FREE(tmp);
2679 if (target_principal_name == NULL) {
2680 ret = ENOMEM;
2681 krb5_set_error_message(context, ret,
2682 "samba_kdc_check_s4u2proxy:"
2683 " talloc_strdup() failed!");
2684 return ret;
2687 el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
2688 if (el == NULL) {
2689 goto bad_option;
2692 val = data_blob_string_const(target_principal_name);
2694 for (i=0; i<el->num_values; i++) {
2695 struct ldb_val *val1 = &val;
2696 struct ldb_val *val2 = &el->values[i];
2697 int cmp;
2699 if (val1->length != val2->length) {
2700 continue;
2703 cmp = strncasecmp((const char *)val1->data,
2704 (const char *)val2->data,
2705 val1->length);
2706 if (cmp != 0) {
2707 continue;
2710 found = true;
2711 break;
2714 if (!found) {
2715 goto bad_option;
2718 DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
2719 client_dn, tmp));
2720 talloc_free(mem_ctx);
2721 return 0;
2723 bad_option:
2724 krb5_set_error_message(context, ret,
2725 "samba_kdc_check_s4u2proxy: client[%s] "
2726 "not allowed for delegation to target[%s]",
2727 client_dn,
2728 target_principal_name);
2729 talloc_free(mem_ctx);
2730 return KRB5KDC_ERR_BADOPTION;
2733 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
2734 struct samba_kdc_db_context **kdc_db_ctx_out)
2736 int ldb_ret;
2737 struct ldb_message *msg;
2738 struct auth_session_info *session_info;
2739 struct samba_kdc_db_context *kdc_db_ctx;
2740 /* The idea here is very simple. Using Kerberos to
2741 * authenticate the KDC to the LDAP server is higly likely to
2742 * be circular.
2744 * In future we may set this up to use EXERNAL and SSL
2745 * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
2748 kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
2749 if (kdc_db_ctx == NULL) {
2750 return NT_STATUS_NO_MEMORY;
2752 kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
2753 kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
2754 kdc_db_ctx->msg_ctx = base_ctx->msg_ctx;
2756 /* get default kdc policy */
2757 lpcfg_default_kdc_policy(mem_ctx,
2758 base_ctx->lp_ctx,
2759 &kdc_db_ctx->policy.svc_tkt_lifetime,
2760 &kdc_db_ctx->policy.usr_tkt_lifetime,
2761 &kdc_db_ctx->policy.renewal_lifetime);
2763 session_info = system_session(kdc_db_ctx->lp_ctx);
2764 if (session_info == NULL) {
2765 return NT_STATUS_INTERNAL_ERROR;
2768 /* Setup the link to LDB */
2769 kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx,
2770 base_ctx->ev_ctx,
2771 base_ctx->lp_ctx,
2772 session_info,
2773 NULL,
2775 if (kdc_db_ctx->samdb == NULL) {
2776 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
2777 talloc_free(kdc_db_ctx);
2778 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2781 /* Find out our own krbtgt kvno */
2782 ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
2783 if (ldb_ret != LDB_SUCCESS) {
2784 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
2785 ldb_errstring(kdc_db_ctx->samdb)));
2786 talloc_free(kdc_db_ctx);
2787 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2789 if (kdc_db_ctx->rodc) {
2790 int my_krbtgt_number;
2791 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
2792 struct ldb_dn *account_dn;
2793 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
2794 if (!server_dn) {
2795 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
2796 ldb_errstring(kdc_db_ctx->samdb)));
2797 talloc_free(kdc_db_ctx);
2798 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2801 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
2802 "serverReference", &account_dn);
2803 if (ldb_ret != LDB_SUCCESS) {
2804 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
2805 ldb_errstring(kdc_db_ctx->samdb)));
2806 talloc_free(kdc_db_ctx);
2807 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2810 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
2811 "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
2812 talloc_free(account_dn);
2813 if (ldb_ret != LDB_SUCCESS) {
2814 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
2815 ldb_errstring(kdc_db_ctx->samdb)));
2816 talloc_free(kdc_db_ctx);
2817 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2820 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2821 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
2822 secondary_keytab,
2823 DSDB_SEARCH_NO_GLOBAL_CATALOG,
2824 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
2825 if (ldb_ret != LDB_SUCCESS) {
2826 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
2827 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2828 ldb_errstring(kdc_db_ctx->samdb),
2829 ldb_strerror(ldb_ret)));
2830 talloc_free(kdc_db_ctx);
2831 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2833 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
2834 if (my_krbtgt_number == -1) {
2835 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
2836 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2837 my_krbtgt_number));
2838 talloc_free(kdc_db_ctx);
2839 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2841 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
2843 } else {
2844 kdc_db_ctx->my_krbtgt_number = 0;
2845 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2846 &msg,
2847 ldb_get_default_basedn(kdc_db_ctx->samdb),
2848 LDB_SCOPE_SUBTREE,
2849 krbtgt_attrs,
2850 DSDB_SEARCH_NO_GLOBAL_CATALOG,
2851 "(&(objectClass=user)(samAccountName=krbtgt))");
2853 if (ldb_ret != LDB_SUCCESS) {
2854 DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
2855 talloc_free(kdc_db_ctx);
2856 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2858 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
2859 kdc_db_ctx->my_krbtgt_number = 0;
2860 talloc_free(msg);
2862 *kdc_db_ctx_out = kdc_db_ctx;
2863 return NT_STATUS_OK;