s4:kdc/db-glue: allow invalid kvno numbers in samba_kdc_trust_message2entry()
[Samba.git] / source4 / kdc / db-glue.c
blob20c73c8b11b6be475093f9985e07e2851489dc53
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 <hdb.h>
36 #include "kdc/samba_kdc.h"
37 #include "kdc/db-glue.h"
39 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
40 ((uint16_t)(((uint32_t)kvno) >> 16))
42 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
43 ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
44 ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
46 enum samba_kdc_ent_type
47 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
48 SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
50 enum trust_direction {
51 UNKNOWN = 0,
52 INBOUND = LSA_TRUST_DIRECTION_INBOUND,
53 OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
56 static const char *trust_attrs[] = {
57 "trustPartner",
58 "trustAuthIncoming",
59 "trustAuthOutgoing",
60 "whenCreated",
61 "msDS-SupportedEncryptionTypes",
62 "trustAttributes",
63 "trustDirection",
64 "trustType",
65 NULL
69 static time_t ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, time_t default_val)
71 const char *tmp;
72 const char *gentime;
73 struct tm tm;
75 gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
76 if (!gentime)
77 return default_val;
79 tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
80 if (tmp == NULL) {
81 return default_val;
84 return timegm(&tm);
87 static HDBFlags uf2HDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
89 HDBFlags flags = int2HDBFlags(0);
91 /* we don't allow kadmin deletes */
92 flags.immutable = 1;
94 /* mark the principal as invalid to start with */
95 flags.invalid = 1;
97 flags.renewable = 1;
99 /* All accounts are servers, but this may be disabled again in the caller */
100 flags.server = 1;
102 /* Account types - clear the invalid bit if it turns out to be valid */
103 if (userAccountControl & UF_NORMAL_ACCOUNT) {
104 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
105 flags.client = 1;
107 flags.invalid = 0;
110 if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
111 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
112 flags.client = 1;
114 flags.invalid = 0;
116 if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
117 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
118 flags.client = 1;
120 flags.invalid = 0;
122 if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
123 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
124 flags.client = 1;
126 flags.invalid = 0;
129 /* Not permitted to act as a client if disabled */
130 if (userAccountControl & UF_ACCOUNTDISABLE) {
131 flags.client = 0;
133 if (userAccountControl & UF_LOCKOUT) {
134 flags.locked_out = 1;
137 if (userAccountControl & UF_PASSWORD_NOTREQD) {
138 flags.invalid = 1;
142 UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
144 if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
145 flags.invalid = 1;
148 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
151 if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
152 flags.invalid = 1;
155 if (userAccountControl & UF_SMARTCARD_REQUIRED) {
156 flags.require_hwauth = 1;
158 if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
159 flags.ok_as_delegate = 1;
161 if (userAccountControl & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
163 * this is confusing...
165 * UF_TRUSTED_FOR_DELEGATION
166 * => ok_as_delegate
168 * and
170 * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
171 * => trusted_for_delegation
173 flags.trusted_for_delegation = 1;
175 if (!(userAccountControl & UF_NOT_DELEGATED)) {
176 flags.forwardable = 1;
177 flags.proxiable = 1;
180 if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
181 flags.require_preauth = 0;
182 } else {
183 flags.require_preauth = 1;
186 return flags;
189 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
191 if (p->entry_ex != NULL) {
192 hdb_entry_ex *entry_ex = p->entry_ex;
193 free_hdb_entry(&entry_ex->entry);
196 return 0;
199 static void samba_kdc_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
201 /* this function is called only from hdb_free_entry().
202 * Make sure we neutralize the destructor or we will
203 * get a double free later when hdb_free_entry() will
204 * try to call free_hdb_entry() */
205 talloc_set_destructor(entry_ex->ctx, NULL);
207 /* now proceed to free the talloc part */
208 talloc_free(entry_ex->ctx);
211 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
212 struct samba_kdc_db_context *kdc_db_ctx,
213 TALLOC_CTX *mem_ctx,
214 struct ldb_message *msg,
215 uint32_t rid,
216 bool is_rodc,
217 uint32_t userAccountControl,
218 enum samba_kdc_ent_type ent_type,
219 hdb_entry_ex *entry_ex)
221 krb5_error_code ret = 0;
222 enum ndr_err_code ndr_err;
223 struct samr_Password *hash;
224 const struct ldb_val *sc_val;
225 struct supplementalCredentialsBlob scb;
226 struct supplementalCredentialsPackage *scpk = NULL;
227 bool newer_keys = false;
228 struct package_PrimaryKerberosBlob _pkb;
229 struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
230 struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
231 uint16_t i;
232 uint16_t allocated_keys = 0;
233 int rodc_krbtgt_number = 0;
234 int kvno = 0;
235 uint32_t supported_enctypes
236 = ldb_msg_find_attr_as_uint(msg,
237 "msDS-SupportedEncryptionTypes",
240 if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
241 /* KDCs (and KDCs on RODCs) use AES */
242 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
243 } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
244 /* DCs and RODCs comptuer accounts use AES */
245 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
246 } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
247 (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
248 /* for AS-REQ the client chooses the enc types it
249 * supports, and this will vary between computers a
250 * user logs in from.
252 * likewise for 'any' return as much as is supported,
253 * to export into a keytab */
254 supported_enctypes = ENC_ALL_TYPES;
257 /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
258 if (userAccountControl & UF_USE_DES_KEY_ONLY) {
259 supported_enctypes = ENC_CRC32|ENC_RSA_MD5;
260 } else {
261 /* Otherwise, add in the default enc types */
262 supported_enctypes |= ENC_CRC32 | ENC_RSA_MD5 | ENC_RC4_HMAC_MD5;
265 /* Is this the krbtgt or a RODC krbtgt */
266 if (is_rodc) {
267 rodc_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
269 if (rodc_krbtgt_number == -1) {
270 return EINVAL;
274 entry_ex->entry.keys.val = NULL;
275 entry_ex->entry.keys.len = 0;
277 kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
278 if (is_rodc) {
279 kvno = SAMBA_KVNO_AND_KRBTGT(kvno, rodc_krbtgt_number);
281 entry_ex->entry.kvno = kvno;
283 /* Get keys from the db */
285 hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
286 sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
288 /* unicodePwd for enctype 0x17 (23) if present */
289 if (hash) {
290 allocated_keys++;
293 /* supplementalCredentials if present */
294 if (sc_val) {
295 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
296 (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
297 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
298 dump_data(0, sc_val->data, sc_val->length);
299 ret = EINVAL;
300 goto out;
303 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
304 NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
305 ret = EINVAL;
306 goto out;
309 for (i=0; i < scb.sub.num_packages; i++) {
310 if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
311 scpk = &scb.sub.packages[i];
312 if (!scpk->data || !scpk->data[0]) {
313 scpk = NULL;
314 continue;
316 newer_keys = true;
317 break;
318 } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
319 scpk = &scb.sub.packages[i];
320 if (!scpk->data || !scpk->data[0]) {
321 scpk = NULL;
324 * we don't break here in hope to find
325 * a Kerberos-Newer-Keys package
331 * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
332 * of supplementalCredentials
334 if (scpk) {
335 DATA_BLOB blob;
337 blob = strhex_to_data_blob(mem_ctx, scpk->data);
338 if (!blob.data) {
339 ret = ENOMEM;
340 goto out;
343 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
344 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
345 (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
346 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
347 ret = EINVAL;
348 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
349 krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
350 goto out;
353 if (newer_keys && _pkb.version != 4) {
354 ret = EINVAL;
355 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
356 krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
357 goto out;
360 if (!newer_keys && _pkb.version != 3) {
361 ret = EINVAL;
362 krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
363 krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
364 goto out;
367 if (_pkb.version == 4) {
368 pkb4 = &_pkb.ctr.ctr4;
369 allocated_keys += pkb4->num_keys;
370 } else if (_pkb.version == 3) {
371 pkb3 = &_pkb.ctr.ctr3;
372 allocated_keys += pkb3->num_keys;
376 if (allocated_keys == 0) {
377 if (kdc_db_ctx->rodc) {
378 /* We are on an RODC, but don't have keys for this account. Signal this to the caller */
379 /* TODO: We need to call a generalised version of auth_sam_trigger_repl_secret from here */
380 return HDB_ERR_NOT_FOUND_HERE;
383 /* oh, no password. Apparently (comment in
384 * hdb-ldap.c) this violates the ASN.1, but this
385 * allows an entry with no keys (yet). */
386 return 0;
389 /* allocate space to decode into */
390 entry_ex->entry.keys.len = 0;
391 entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
392 if (entry_ex->entry.keys.val == NULL) {
393 ret = ENOMEM;
394 goto out;
397 if (hash && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
398 Key key;
400 key.mkvno = 0;
401 key.salt = NULL; /* No salt for this enc type */
403 ret = smb_krb5_keyblock_init_contents(context,
404 ENCTYPE_ARCFOUR_HMAC,
405 hash->hash,
406 sizeof(hash->hash),
407 &key.key);
408 if (ret) {
409 goto out;
412 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
413 entry_ex->entry.keys.len++;
416 if (pkb4) {
417 for (i=0; i < pkb4->num_keys; i++) {
418 Key key;
420 if (!pkb4->keys[i].value) continue;
422 if (!(kerberos_enctype_to_bitmap(pkb4->keys[i].keytype) & supported_enctypes)) {
423 continue;
426 key.mkvno = 0;
427 key.salt = NULL;
429 if (pkb4->salt.string) {
430 DATA_BLOB salt;
432 salt = data_blob_string_const(pkb4->salt.string);
434 key.salt = calloc(1, sizeof(*key.salt));
435 if (key.salt == NULL) {
436 ret = ENOMEM;
437 goto out;
440 key.salt->type = KRB5_PW_SALT;
442 ret = krb5_copy_data_contents(&key.salt->salt,
443 salt.data,
444 salt.length);
445 if (ret) {
446 free(key.salt);
447 key.salt = NULL;
448 goto out;
452 /* TODO: maybe pass the iteration_count somehow... */
454 ret = smb_krb5_keyblock_init_contents(context,
455 pkb4->keys[i].keytype,
456 pkb4->keys[i].value->data,
457 pkb4->keys[i].value->length,
458 &key.key);
459 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
460 DEBUG(2,("Unsupported keytype ignored - type %u\n",
461 pkb4->keys[i].keytype));
462 ret = 0;
463 continue;
465 if (ret) {
466 if (key.salt) {
467 free_Salt(key.salt);
468 free(key.salt);
469 key.salt = NULL;
471 goto out;
474 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
475 entry_ex->entry.keys.len++;
477 } else if (pkb3) {
478 for (i=0; i < pkb3->num_keys; i++) {
479 Key key;
481 if (!pkb3->keys[i].value) continue;
483 if (!(kerberos_enctype_to_bitmap(pkb3->keys[i].keytype) & supported_enctypes)) {
484 continue;
487 key.mkvno = 0;
488 key.salt = NULL;
490 if (pkb3->salt.string) {
491 DATA_BLOB salt;
493 salt = data_blob_string_const(pkb3->salt.string);
495 key.salt = calloc(1, sizeof(*key.salt));
496 if (key.salt == NULL) {
497 ret = ENOMEM;
498 goto out;
501 key.salt->type = KRB5_PW_SALT;
503 ret = krb5_copy_data_contents(&key.salt->salt,
504 salt.data,
505 salt.length);
506 if (ret) {
507 free(key.salt);
508 key.salt = NULL;
509 goto out;
513 ret = smb_krb5_keyblock_init_contents(context,
514 pkb3->keys[i].keytype,
515 pkb3->keys[i].value->data,
516 pkb3->keys[i].value->length,
517 &key.key);
518 if (ret) {
519 if (key.salt) {
520 free_Salt(key.salt);
521 free(key.salt);
522 key.salt = NULL;
524 goto out;
527 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
528 entry_ex->entry.keys.len++;
532 out:
533 if (ret != 0) {
534 entry_ex->entry.keys.len = 0;
536 if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
537 free(entry_ex->entry.keys.val);
538 entry_ex->entry.keys.val = NULL;
540 return ret;
543 static int principal_comp_strcmp_int(krb5_context context,
544 krb5_const_principal principal,
545 unsigned int component,
546 const char *string,
547 bool do_strcasecmp)
549 const char *p;
550 size_t len;
552 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
553 p = krb5_principal_get_comp_string(context, principal, component);
554 if (p == NULL) {
555 return -1;
557 len = strlen(p);
558 #else
559 krb5_data *d;
560 if (component >= krb5_princ_size(context, principal)) {
561 return -1;
564 d = krb5_princ_component(context, principal, component);
565 if (d == NULL) {
566 return -1;
569 p = d->data;
570 len = d->length;
571 #endif
572 if (do_strcasecmp) {
573 return strncasecmp(p, string, len);
574 } else {
575 return strncmp(p, string, len);
579 static int principal_comp_strcasecmp(krb5_context context,
580 krb5_const_principal principal,
581 unsigned int component,
582 const char *string)
584 return principal_comp_strcmp_int(context, principal,
585 component, string, true);
588 static int principal_comp_strcmp(krb5_context context,
589 krb5_const_principal principal,
590 unsigned int component,
591 const char *string)
593 return principal_comp_strcmp_int(context, principal,
594 component, string, false);
598 * Construct an hdb_entry from a directory entry.
600 static krb5_error_code samba_kdc_message2entry(krb5_context context,
601 struct samba_kdc_db_context *kdc_db_ctx,
602 TALLOC_CTX *mem_ctx,
603 krb5_const_principal principal,
604 enum samba_kdc_ent_type ent_type,
605 unsigned flags,
606 struct ldb_dn *realm_dn,
607 struct ldb_message *msg,
608 hdb_entry_ex *entry_ex)
610 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
611 uint32_t userAccountControl;
612 uint32_t msDS_User_Account_Control_Computed;
613 unsigned int i;
614 krb5_error_code ret = 0;
615 krb5_boolean is_computer = FALSE;
617 struct samba_kdc_entry *p;
618 NTTIME acct_expiry;
619 NTSTATUS status;
621 uint32_t rid;
622 bool is_rodc = false;
623 struct ldb_message_element *objectclasses;
624 struct ldb_val computer_val;
625 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
626 computer_val.data = discard_const_p(uint8_t,"computer");
627 computer_val.length = strlen((const char *)computer_val.data);
629 if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
630 is_rodc = true;
633 if (!samAccountName) {
634 ret = ENOENT;
635 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
636 goto out;
639 objectclasses = ldb_msg_find_element(msg, "objectClass");
641 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
642 is_computer = TRUE;
645 ZERO_STRUCTP(entry_ex);
647 p = talloc_zero(mem_ctx, struct samba_kdc_entry);
648 if (!p) {
649 ret = ENOMEM;
650 goto out;
653 p->kdc_db_ctx = kdc_db_ctx;
654 p->entry_ex = entry_ex;
655 p->realm_dn = talloc_reference(p, realm_dn);
656 if (!p->realm_dn) {
657 ret = ENOMEM;
658 goto out;
661 talloc_set_destructor(p, samba_kdc_entry_destructor);
663 /* make sure we do not have bogus data in there */
664 memset(&entry_ex->entry, 0, sizeof(hdb_entry));
666 entry_ex->ctx = p;
667 entry_ex->free_entry = samba_kdc_free_entry;
669 userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
671 msDS_User_Account_Control_Computed
672 = ldb_msg_find_attr_as_uint(msg,
673 "msDS-User-Account-Control-Computed",
674 UF_ACCOUNTDISABLE);
677 * This brings in the lockout flag, block the account if not
678 * found. We need the weird UF_ACCOUNTDISABLE check because
679 * we do not want to fail open if the value is not returned,
680 * but 0 is a valid value (all OK)
682 if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
683 ret = EINVAL;
684 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
685 "no msDS-User-Account-Control-Computed present");
686 goto out;
687 } else {
688 userAccountControl |= msDS_User_Account_Control_Computed;
692 * If we are set to canonicalize, we get back the fixed UPPER
693 * case realm, and the real username (ie matching LDAP
694 * samAccountName)
696 * Otherwise, if we are set to enterprise, we
697 * get back the whole principal as-sent
699 * Finally, if we are not set to canonicalize, we get back the
700 * fixed UPPER case realm, but the as-sent username
703 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
704 if (flags & (HDB_F_CANON)) {
706 * When requested to do so, ensure that the
707 * both realm values in the principal are set
708 * to the upper case, canonical realm
710 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal,
711 lpcfg_realm(lp_ctx), "krbtgt",
712 lpcfg_realm(lp_ctx), NULL);
713 if (ret) {
714 krb5_clear_error_message(context);
715 goto out;
717 smb_krb5_principal_set_type(context, entry_ex->entry.principal, KRB5_NT_SRV_INST);
718 } else {
719 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
720 if (ret) {
721 krb5_clear_error_message(context);
722 goto out;
725 * this appears to be required regardless of
726 * the canonicalize flag from the client
728 ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
729 if (ret) {
730 krb5_clear_error_message(context);
731 goto out;
735 } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
736 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
737 if (ret) {
738 krb5_clear_error_message(context);
739 goto out;
741 } else if (flags & HDB_F_CANON && flags & HDB_F_FOR_AS_REQ) {
743 * HDB_F_CANON maps from the canonicalize flag in the
744 * packet, and has a different meaning between AS-REQ
745 * and TGS-REQ. We only change the principal in the AS-REQ case
747 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
748 if (ret) {
749 krb5_clear_error_message(context);
750 goto out;
752 } else {
753 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
754 if (ret) {
755 krb5_clear_error_message(context);
756 goto out;
759 if (smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL) {
760 /* While we have copied the client principal, tests
761 * show that Win2k3 returns the 'corrected' realm, not
762 * the client-specified realm. This code attempts to
763 * replace the client principal's realm with the one
764 * we determine from our records */
766 /* this has to be with malloc() */
767 ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
768 if (ret) {
769 krb5_clear_error_message(context);
770 goto out;
775 /* First try and figure out the flags based on the userAccountControl */
776 entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
778 /* Windows 2008 seems to enforce this (very sensible) rule by
779 * default - don't allow offline attacks on a user's password
780 * by asking for a ticket to them as a service (encrypted with
781 * their probably patheticly insecure password) */
783 if (entry_ex->entry.flags.server
784 && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
785 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
786 entry_ex->entry.flags.server = 0;
790 * To give the correct type of error to the client, we must
791 * not just return the entry without .server set, we must
792 * pretend the principal does not exist. Otherwise we may
793 * return ERR_POLICY instead of
794 * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
796 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry_ex->entry.flags.server == 0) {
797 ret = HDB_ERR_NOENTRY;
798 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
799 goto out;
801 if (flags & HDB_F_ADMIN_DATA) {
802 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
803 * of the Heimdal KDC. They are stored in a the traditional
804 * DB for audit purposes, and still form part of the structure
805 * we must return */
807 /* use 'whenCreated' */
808 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
809 /* use 'kadmin' for now (needed by mit_samba) */
811 ret = smb_krb5_make_principal(context,
812 &entry_ex->entry.created_by.principal,
813 lpcfg_realm(lp_ctx), "kadmin", NULL);
814 if (ret) {
815 krb5_clear_error_message(context);
816 goto out;
819 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
820 if (entry_ex->entry.modified_by == NULL) {
821 ret = ENOMEM;
822 krb5_set_error_message(context, ret, "malloc: out of memory");
823 goto out;
826 /* use 'whenChanged' */
827 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
828 /* use 'kadmin' for now (needed by mit_samba) */
829 ret = smb_krb5_make_principal(context,
830 &entry_ex->entry.modified_by->principal,
831 lpcfg_realm(lp_ctx), "kadmin", NULL);
832 if (ret) {
833 krb5_clear_error_message(context);
834 goto out;
839 /* The lack of password controls etc applies to krbtgt by
840 * virtue of being that particular RID */
841 status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
843 if (!NT_STATUS_IS_OK(status)) {
844 ret = EINVAL;
845 goto out;
848 if (rid == DOMAIN_RID_KRBTGT) {
849 char *realm = NULL;
851 entry_ex->entry.valid_end = NULL;
852 entry_ex->entry.pw_end = NULL;
854 entry_ex->entry.flags.invalid = 0;
855 entry_ex->entry.flags.server = 1;
857 realm = smb_krb5_principal_get_realm(context, principal);
858 if (realm == NULL) {
859 ret = ENOMEM;
860 goto out;
863 /* Don't mark all requests for the krbtgt/realm as
864 * 'change password', as otherwise we could get into
865 * trouble, and not enforce the password expirty.
866 * Instead, only do it when request is for the kpasswd service */
867 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
868 && krb5_princ_size(context, principal) == 2
869 && (principal_comp_strcmp(context, principal, 0, "kadmin") == 0)
870 && (principal_comp_strcmp(context, principal, 1, "changepw") == 0)
871 && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
872 entry_ex->entry.flags.change_pw = 1;
875 SAFE_FREE(realm);
877 entry_ex->entry.flags.client = 0;
878 entry_ex->entry.flags.forwardable = 1;
879 entry_ex->entry.flags.ok_as_delegate = 1;
880 } else if (is_rodc) {
881 /* The RODC krbtgt account is like the main krbtgt,
882 * but it does not have a changepw or kadmin
883 * service */
885 entry_ex->entry.valid_end = NULL;
886 entry_ex->entry.pw_end = NULL;
888 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
889 entry_ex->entry.flags.client = 0;
890 entry_ex->entry.flags.invalid = 0;
891 entry_ex->entry.flags.server = 1;
893 entry_ex->entry.flags.client = 0;
894 entry_ex->entry.flags.forwardable = 1;
895 entry_ex->entry.flags.ok_as_delegate = 0;
896 } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
897 /* The account/password expiry only applies when the account is used as a
898 * client (ie password login), not when used as a server */
900 /* Make very well sure we don't use this for a client,
901 * it could bypass the password restrictions */
902 entry_ex->entry.flags.client = 0;
904 entry_ex->entry.valid_end = NULL;
905 entry_ex->entry.pw_end = NULL;
907 } else {
908 NTTIME must_change_time
909 = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
910 realm_dn, msg);
911 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
912 entry_ex->entry.pw_end = NULL;
913 } else {
914 entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
915 if (entry_ex->entry.pw_end == NULL) {
916 ret = ENOMEM;
917 goto out;
919 *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
922 acct_expiry = samdb_result_account_expires(msg);
923 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
924 entry_ex->entry.valid_end = NULL;
925 } else {
926 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
927 if (entry_ex->entry.valid_end == NULL) {
928 ret = ENOMEM;
929 goto out;
931 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
935 entry_ex->entry.valid_start = NULL;
937 entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life));
938 if (entry_ex->entry.max_life == NULL) {
939 ret = ENOMEM;
940 goto out;
943 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
944 *entry_ex->entry.max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
945 } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
946 *entry_ex->entry.max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
947 } else {
948 *entry_ex->entry.max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
949 kdc_db_ctx->policy.usr_tkt_lifetime);
952 entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_life));
953 if (entry_ex->entry.max_renew == NULL) {
954 ret = ENOMEM;
955 goto out;
958 *entry_ex->entry.max_renew = kdc_db_ctx->policy.renewal_lifetime;
960 /* Get keys from the db */
961 ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
962 rid, is_rodc, userAccountControl,
963 ent_type, entry_ex);
964 if (ret) {
965 /* Could be bougus data in the entry, or out of memory */
966 goto out;
969 entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
970 if (entry_ex->entry.etypes == NULL) {
971 krb5_clear_error_message(context);
972 ret = ENOMEM;
973 goto out;
975 entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
976 entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
977 if (entry_ex->entry.etypes->val == NULL) {
978 krb5_clear_error_message(context);
979 ret = ENOMEM;
980 goto out;
982 for (i=0; i < entry_ex->entry.etypes->len; i++) {
983 entry_ex->entry.etypes->val[i] = KRB5_KEY_TYPE(&entry_ex->entry.keys.val[i].key);
987 p->msg = talloc_steal(p, msg);
989 out:
990 if (ret != 0) {
991 /* This doesn't free ent itself, that is for the eventual caller to do */
992 hdb_free_entry(context, entry_ex);
993 ZERO_STRUCTP(entry_ex);
994 } else {
995 talloc_steal(kdc_db_ctx, entry_ex->ctx);
998 return ret;
1002 * Construct an hdb_entry from a directory entry.
1003 * The kvno is what the remote client asked for
1005 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
1006 struct samba_kdc_db_context *kdc_db_ctx,
1007 TALLOC_CTX *mem_ctx, krb5_const_principal principal,
1008 enum trust_direction direction,
1009 struct ldb_dn *realm_dn,
1010 unsigned flags,
1011 uint32_t kvno,
1012 struct ldb_message *msg,
1013 hdb_entry_ex *entry_ex)
1015 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1016 const char *dnsdomain;
1017 const char *realm = lpcfg_realm(lp_ctx);
1018 DATA_BLOB password_utf16 = data_blob_null;
1019 DATA_BLOB password_utf8 = data_blob_null;
1020 struct samr_Password _password_hash;
1021 const struct samr_Password *password_hash = NULL;
1022 const struct ldb_val *password_val;
1023 struct trustAuthInOutBlob password_blob;
1024 struct samba_kdc_entry *p;
1025 bool use_previous = false;
1026 uint32_t current_kvno;
1027 uint32_t previous_kvno;
1028 uint32_t num_keys = 0;
1029 enum ndr_err_code ndr_err;
1030 int ret, trust_direction_flags;
1031 unsigned int i;
1032 struct AuthenticationInformationArray *auth_array;
1033 uint32_t *auth_kvno;
1034 uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
1036 if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1037 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
1038 "msDS-SupportedEncryptionTypes",
1039 supported_enctypes);
1042 trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
1044 if (direction == INBOUND) {
1045 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
1047 } else { /* OUTBOUND */
1048 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
1049 /* replace realm */
1050 realm = strupper_talloc(mem_ctx, dnsdomain);
1051 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
1054 if (!password_val || !(trust_direction_flags & direction)) {
1055 krb5_clear_error_message(context);
1056 ret = HDB_ERR_NOENTRY;
1057 goto out;
1060 ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
1061 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1062 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1063 krb5_clear_error_message(context);
1064 ret = EINVAL;
1065 goto out;
1068 p = talloc(mem_ctx, struct samba_kdc_entry);
1069 if (!p) {
1070 ret = ENOMEM;
1071 goto out;
1074 p->kdc_db_ctx = kdc_db_ctx;
1075 p->entry_ex = entry_ex;
1076 p->realm_dn = realm_dn;
1078 talloc_set_destructor(p, samba_kdc_entry_destructor);
1080 /* make sure we do not have bogus data in there */
1081 memset(&entry_ex->entry, 0, sizeof(hdb_entry));
1083 entry_ex->ctx = p;
1084 entry_ex->free_entry = samba_kdc_free_entry;
1086 /* use 'whenCreated' */
1087 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1088 /* use 'kadmin' for now (needed by mit_samba) */
1089 ret = smb_krb5_make_principal(context,
1090 &entry_ex->entry.created_by.principal,
1091 realm, "kadmin", NULL);
1092 if (ret) {
1093 krb5_clear_error_message(context);
1094 goto out;
1097 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
1098 if (ret) {
1099 krb5_clear_error_message(context);
1100 goto out;
1104 * While we have copied the client principal, tests
1105 * show that Win2k3 returns the 'corrected' realm, not
1106 * the client-specified realm. This code attempts to
1107 * replace the client principal's realm with the one
1108 * we determine from our records
1111 ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
1112 if (ret) {
1113 krb5_clear_error_message(context);
1114 goto out;
1117 entry_ex->entry.valid_start = NULL;
1119 /* we need to work out if we are going to use the current or
1120 * the previous password hash.
1121 * We base this on the kvno the client passes in. If the kvno
1122 * passed in is equal to the current kvno in our database then
1123 * we use the current structure. If it is the current kvno-1,
1124 * then we use the previous substrucure.
1127 /* first work out the current kvno */
1128 current_kvno = 0;
1129 for (i=0; i < password_blob.count; i++) {
1130 struct AuthenticationInformation *a =
1131 &password_blob.current.array[i];
1133 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1134 current_kvno = a->AuthInfo.version.version;
1137 if (current_kvno == 0) {
1138 previous_kvno = 255;
1139 } else {
1140 previous_kvno = current_kvno - 1;
1142 for (i=0; i < password_blob.count; i++) {
1143 struct AuthenticationInformation *a =
1144 &password_blob.previous.array[i];
1146 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1147 previous_kvno = a->AuthInfo.version.version;
1151 /* work out whether we will use the previous or current
1152 password */
1153 if (password_blob.previous.count == 0) {
1154 /* there is no previous password */
1155 use_previous = false;
1156 } else if (!(flags & HDB_F_KVNO_SPECIFIED)) {
1158 * If not specified we use the current one.
1160 use_previous = false;
1161 } else if (kvno == current_kvno) {
1163 * Exact match ...
1165 use_previous = false;
1166 } else if (kvno == previous_kvno) {
1168 * Exact match ...
1170 use_previous = true;
1171 } else {
1173 * Fallback to the current one for anything else
1175 use_previous = false;
1178 if (use_previous) {
1179 auth_array = &password_blob.previous;
1180 auth_kvno = &previous_kvno;
1181 } else {
1182 auth_array = &password_blob.current;
1183 auth_kvno = &current_kvno;
1186 /* use the kvno the client specified, if available */
1187 if (flags & HDB_F_KVNO_SPECIFIED) {
1188 entry_ex->entry.kvno = kvno;
1189 } else {
1190 entry_ex->entry.kvno = *auth_kvno;
1193 for (i=0; i < auth_array->count; i++) {
1194 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1195 bool ok;
1197 password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
1198 auth_array->array[i].AuthInfo.clear.size);
1199 if (password_utf16.length == 0) {
1200 break;
1203 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1204 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
1205 if (password_hash == NULL) {
1206 num_keys += 1;
1208 password_hash = &_password_hash;
1211 if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1212 break;
1215 ok = convert_string_talloc(mem_ctx,
1216 CH_UTF16MUNGED, CH_UTF8,
1217 password_utf16.data,
1218 password_utf16.length,
1219 (void *)&password_utf8.data,
1220 &password_utf8.length);
1221 if (!ok) {
1222 krb5_clear_error_message(context);
1223 ret = ENOMEM;
1224 goto out;
1227 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1228 num_keys += 1;
1230 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1231 num_keys += 1;
1233 break;
1234 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
1235 if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1236 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
1237 num_keys += 1;
1242 /* Must have found a cleartext or MD4 password */
1243 if (num_keys == 0) {
1244 DEBUG(1,(__location__ ": no usable key found\n"));
1245 krb5_clear_error_message(context);
1246 ret = HDB_ERR_NOENTRY;
1247 goto out;
1250 entry_ex->entry.keys.val = calloc(num_keys, sizeof(Key));
1251 if (entry_ex->entry.keys.val == NULL) {
1252 krb5_clear_error_message(context);
1253 ret = ENOMEM;
1254 goto out;
1257 if (password_utf8.length != 0) {
1258 Key key = {};
1259 krb5_const_principal salt_principal = entry_ex->entry.principal;
1260 krb5_data salt;
1261 krb5_data cleartext_data;
1263 cleartext_data.data = password_utf8.data;
1264 cleartext_data.length = password_utf8.length;
1266 ret = smb_krb5_get_pw_salt(context,
1267 salt_principal,
1268 &salt);
1269 if (ret != 0) {
1270 goto out;
1273 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1274 ret = smb_krb5_create_key_from_string(context,
1275 salt_principal,
1276 &salt,
1277 &cleartext_data,
1278 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
1279 &key.key);
1280 if (ret != 0) {
1281 kerberos_free_data_contents(context, &salt);
1282 goto out;
1285 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1286 entry_ex->entry.keys.len++;
1289 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1290 ret = smb_krb5_create_key_from_string(context,
1291 salt_principal,
1292 &salt,
1293 &cleartext_data,
1294 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
1295 &key.key);
1296 if (ret != 0) {
1297 kerberos_free_data_contents(context, &salt);
1298 goto out;
1301 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1302 entry_ex->entry.keys.len++;
1305 kerberos_free_data_contents(context, &salt);
1308 if (password_hash != NULL) {
1309 Key key = {};
1311 ret = smb_krb5_keyblock_init_contents(context,
1312 ENCTYPE_ARCFOUR_HMAC,
1313 password_hash->hash,
1314 sizeof(password_hash->hash),
1315 &key.key);
1316 if (ret != 0) {
1317 goto out;
1320 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1321 entry_ex->entry.keys.len++;
1324 entry_ex->entry.flags = int2HDBFlags(0);
1325 entry_ex->entry.flags.immutable = 1;
1326 entry_ex->entry.flags.invalid = 0;
1327 entry_ex->entry.flags.server = 1;
1328 entry_ex->entry.flags.require_preauth = 1;
1330 entry_ex->entry.pw_end = NULL;
1332 entry_ex->entry.max_life = NULL;
1334 entry_ex->entry.max_renew = NULL;
1336 entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
1337 if (entry_ex->entry.etypes == NULL) {
1338 krb5_clear_error_message(context);
1339 ret = ENOMEM;
1340 goto out;
1342 entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
1343 entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
1344 if (entry_ex->entry.etypes->val == NULL) {
1345 krb5_clear_error_message(context);
1346 ret = ENOMEM;
1347 goto out;
1349 for (i=0; i < entry_ex->entry.etypes->len; i++) {
1350 entry_ex->entry.etypes->val[i] = KRB5_KEY_TYPE(&entry_ex->entry.keys.val[i].key);
1354 p->msg = talloc_steal(p, msg);
1356 out:
1357 if (ret != 0) {
1358 /* This doesn't free ent itself, that is for the eventual caller to do */
1359 hdb_free_entry(context, entry_ex);
1360 } else {
1361 talloc_steal(kdc_db_ctx, entry_ex->ctx);
1364 return ret;
1368 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
1369 TALLOC_CTX *mem_ctx,
1370 const char *realm,
1371 struct ldb_dn *realm_dn,
1372 struct ldb_message **pmsg)
1374 NTSTATUS status;
1375 const char * const *attrs = trust_attrs;
1377 status = sam_get_results_trust(ldb_ctx,
1378 mem_ctx, realm, realm, attrs,
1379 pmsg);
1380 if (NT_STATUS_IS_OK(status)) {
1381 return 0;
1382 } else if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1383 return HDB_ERR_NOENTRY;
1384 } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1385 int ret = ENOMEM;
1386 krb5_set_error_message(context, ret, "get_sam_result_trust: out of memory");
1387 return ret;
1388 } else {
1389 int ret = EINVAL;
1390 krb5_set_error_message(context, ret, "get_sam_result_trust: %s", nt_errstr(status));
1391 return ret;
1395 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1396 struct samba_kdc_db_context *kdc_db_ctx,
1397 TALLOC_CTX *mem_ctx,
1398 krb5_const_principal principal,
1399 const char **attrs,
1400 struct ldb_dn **realm_dn,
1401 struct ldb_message **msg)
1403 NTSTATUS nt_status;
1404 char *principal_string = NULL;
1406 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1407 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
1408 principal, 0);
1409 if (principal_string == NULL) {
1410 return ENOMEM;
1412 } else {
1413 char *principal_string_m = NULL;
1414 krb5_error_code ret;
1416 ret = krb5_unparse_name(context, principal, &principal_string_m);
1417 if (ret != 0) {
1418 return ret;
1421 principal_string = talloc_strdup(mem_ctx, principal_string_m);
1422 SAFE_FREE(principal_string_m);
1423 if (principal_string == NULL) {
1424 return ENOMEM;
1428 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1429 mem_ctx, principal_string, attrs,
1430 realm_dn, msg);
1431 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1432 krb5_principal fallback_principal = NULL;
1433 unsigned int num_comp;
1434 char *fallback_realm = NULL;
1435 char *fallback_account = NULL;
1436 krb5_error_code ret;
1438 ret = krb5_parse_name(context, principal_string,
1439 &fallback_principal);
1440 TALLOC_FREE(principal_string);
1441 if (ret != 0) {
1442 return ret;
1445 num_comp = krb5_princ_size(context, fallback_principal);
1446 fallback_realm = smb_krb5_principal_get_realm(context,
1447 fallback_principal);
1448 if (fallback_realm == NULL) {
1449 krb5_free_principal(context, fallback_principal);
1450 return ENOMEM;
1453 if (num_comp == 1) {
1454 size_t len;
1456 fallback_account = smb_krb5_principal_get_comp_string(mem_ctx,
1457 context, fallback_principal, 0);
1458 if (fallback_account == NULL) {
1459 krb5_free_principal(context, fallback_principal);
1460 SAFE_FREE(fallback_realm);
1461 return ENOMEM;
1464 len = strlen(fallback_account);
1465 if (len >= 2 && fallback_account[len - 1] == '$') {
1466 TALLOC_FREE(fallback_account);
1469 krb5_free_principal(context, fallback_principal);
1470 fallback_principal = NULL;
1472 if (fallback_account != NULL) {
1473 char *with_dollar;
1475 with_dollar = talloc_asprintf(mem_ctx, "%s$",
1476 fallback_account);
1477 if (with_dollar == NULL) {
1478 SAFE_FREE(fallback_realm);
1479 return ENOMEM;
1481 TALLOC_FREE(fallback_account);
1483 ret = smb_krb5_make_principal(context,
1484 &fallback_principal,
1485 fallback_realm,
1486 with_dollar, NULL);
1487 TALLOC_FREE(with_dollar);
1488 if (ret != 0) {
1489 SAFE_FREE(fallback_realm);
1490 return ret;
1493 SAFE_FREE(fallback_realm);
1495 if (fallback_principal != NULL) {
1496 char *fallback_string = NULL;
1498 ret = krb5_unparse_name(context,
1499 fallback_principal,
1500 &fallback_string);
1501 if (ret != 0) {
1502 krb5_free_principal(context, fallback_principal);
1503 return ret;
1506 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1507 mem_ctx,
1508 fallback_string,
1509 attrs,
1510 realm_dn, msg);
1511 SAFE_FREE(fallback_string);
1513 krb5_free_principal(context, fallback_principal);
1514 fallback_principal = NULL;
1516 TALLOC_FREE(principal_string);
1518 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1519 return HDB_ERR_NOENTRY;
1520 } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1521 return ENOMEM;
1522 } else if (!NT_STATUS_IS_OK(nt_status)) {
1523 return EINVAL;
1526 return 0;
1529 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1530 struct samba_kdc_db_context *kdc_db_ctx,
1531 TALLOC_CTX *mem_ctx,
1532 krb5_const_principal principal,
1533 unsigned flags,
1534 hdb_entry_ex *entry_ex) {
1535 struct ldb_dn *realm_dn;
1536 krb5_error_code ret;
1537 struct ldb_message *msg = NULL;
1539 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1540 mem_ctx, principal, user_attrs,
1541 &realm_dn, &msg);
1542 if (ret != 0) {
1543 return ret;
1546 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1547 principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1548 flags,
1549 realm_dn, msg, entry_ex);
1550 return ret;
1553 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1554 struct samba_kdc_db_context *kdc_db_ctx,
1555 TALLOC_CTX *mem_ctx,
1556 krb5_const_principal principal,
1557 unsigned flags,
1558 uint32_t kvno,
1559 hdb_entry_ex *entry_ex)
1561 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1562 krb5_error_code ret;
1563 struct ldb_message *msg = NULL;
1564 struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1565 char *realm_from_princ, *realm_from_princ_malloc;
1566 char *realm_princ_comp = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 1);
1568 realm_from_princ_malloc = smb_krb5_principal_get_realm(context, principal);
1569 if (realm_from_princ_malloc == NULL) {
1570 /* can't happen */
1571 return HDB_ERR_NOENTRY;
1573 realm_from_princ = talloc_strdup(mem_ctx, realm_from_princ_malloc);
1574 free(realm_from_princ_malloc);
1575 if (realm_from_princ == NULL) {
1576 return HDB_ERR_NOENTRY;
1579 if (krb5_princ_size(context, principal) != 2
1580 || (principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME) != 0)) {
1581 /* Not a krbtgt */
1582 return HDB_ERR_NOENTRY;
1585 /* krbtgt case. Either us or a trusted realm */
1587 if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
1588 && lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp)) {
1589 /* us, or someone quite like us */
1590 /* Cludge, cludge cludge. If the realm part of krbtgt/realm,
1591 * is in our db, then direct the caller at our primary
1592 * krbtgt */
1594 int lret;
1595 unsigned int krbtgt_number;
1596 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
1597 trust tickets. We don't yet know what this means, but we do
1598 seem to need to treat it as unspecified */
1599 if (flags & HDB_F_KVNO_SPECIFIED) {
1600 krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
1601 if (kdc_db_ctx->rodc) {
1602 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1603 return HDB_ERR_NOT_FOUND_HERE;
1606 } else {
1607 krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1610 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1611 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1612 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1613 krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
1614 "(objectClass=user)");
1615 } else {
1616 /* We need to look up an RODC krbtgt (perhaps
1617 * ours, if we are an RODC, perhaps another
1618 * RODC if we are a read-write DC */
1619 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1620 &msg, realm_dn, LDB_SCOPE_SUBTREE,
1621 krbtgt_attrs,
1622 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1623 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1626 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1627 krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1628 (unsigned)(krbtgt_number));
1629 krb5_set_error_message(context, HDB_ERR_NOENTRY,
1630 "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1631 (unsigned)(krbtgt_number));
1632 return HDB_ERR_NOENTRY;
1633 } else if (lret != LDB_SUCCESS) {
1634 krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1635 (unsigned)(krbtgt_number));
1636 krb5_set_error_message(context, HDB_ERR_NOENTRY,
1637 "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1638 (unsigned)(krbtgt_number));
1639 return HDB_ERR_NOENTRY;
1642 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1643 principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1644 flags, realm_dn, msg, entry_ex);
1645 if (ret != 0) {
1646 krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1648 return ret;
1650 } else {
1651 enum trust_direction direction = UNKNOWN;
1652 const char *realm = NULL;
1654 /* Either an inbound or outbound trust */
1656 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
1657 /* look for inbound trust */
1658 direction = INBOUND;
1659 realm = realm_princ_comp;
1660 } else if (principal_comp_strcasecmp(context, principal, 1, lpcfg_realm(lp_ctx)) == 0) {
1661 /* look for outbound trust */
1662 direction = OUTBOUND;
1663 realm = realm_from_princ;
1664 } else {
1665 krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1666 realm_from_princ,
1667 realm_princ_comp);
1668 krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1669 realm_from_princ,
1670 realm_princ_comp);
1671 return HDB_ERR_NOENTRY;
1674 /* Trusted domains are under CN=system */
1676 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1677 mem_ctx,
1678 realm, realm_dn, &msg);
1680 if (ret != 0) {
1681 krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1682 krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1683 return ret;
1686 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1687 principal, direction,
1688 realm_dn, flags, kvno, msg, entry_ex);
1689 if (ret != 0) {
1690 krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed for %s",
1691 ldb_dn_get_linearized(msg->dn));
1692 krb5_set_error_message(context, ret, "samba_kdc_fetch: "
1693 "trust_message2entry failed for %s",
1694 ldb_dn_get_linearized(msg->dn));
1696 return ret;
1701 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1702 struct samba_kdc_db_context *kdc_db_ctx,
1703 TALLOC_CTX *mem_ctx,
1704 krb5_const_principal principal,
1705 unsigned flags,
1706 const char **attrs,
1707 struct ldb_dn **realm_dn,
1708 struct ldb_message **msg)
1710 krb5_error_code ret;
1711 if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
1712 && krb5_princ_size(context, principal) >= 2) {
1713 /* 'normal server' case */
1714 int ldb_ret;
1715 NTSTATUS nt_status;
1716 struct ldb_dn *user_dn;
1717 char *principal_string;
1719 ret = krb5_unparse_name_flags(context, principal,
1720 KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1721 &principal_string);
1722 if (ret != 0) {
1723 return ret;
1726 /* At this point we may find the host is known to be
1727 * in a different realm, so we should generate a
1728 * referral instead */
1729 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1730 mem_ctx, principal_string,
1731 &user_dn, realm_dn);
1732 free(principal_string);
1734 if (!NT_STATUS_IS_OK(nt_status)) {
1735 return HDB_ERR_NOENTRY;
1738 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1739 mem_ctx,
1740 msg, user_dn, LDB_SCOPE_BASE,
1741 attrs,
1742 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1743 "(objectClass=*)");
1744 if (ldb_ret != LDB_SUCCESS) {
1745 return HDB_ERR_NOENTRY;
1747 return 0;
1748 } else if (!(flags & HDB_F_FOR_AS_REQ)
1749 && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1751 * The behaviour of accepting an
1752 * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
1753 * containing a UPN only applies to TGS-REQ packets,
1754 * not AS-REQ packets.
1756 return samba_kdc_lookup_client(context, kdc_db_ctx,
1757 mem_ctx, principal, attrs,
1758 realm_dn, msg);
1759 } else {
1761 * This case is for:
1762 * - the AS-REQ, where we only accept
1763 * samAccountName based lookups for the server, no
1764 * matter if the name is an
1765 * KRB5_NT_ENTERPRISE_PRINCIPAL or not
1766 * - for the TGS-REQ when we are not given an
1767 * KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
1768 * only lookup samAccountName based names.
1770 int lret;
1771 char *short_princ;
1772 krb5_principal enterprise_principal = NULL;
1773 krb5_const_principal used_principal = NULL;
1774 char *name1 = NULL;
1775 size_t len1 = 0;
1776 char *filter = NULL;
1778 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1779 char *str = NULL;
1780 /* Need to reparse the enterprise principal to find the real target */
1781 if (krb5_princ_size(context, principal) != 1) {
1782 ret = KRB5_PARSE_MALFORMED;
1783 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
1784 "enterprise principal with wrong (%d) number of components",
1785 krb5_princ_size(context, principal));
1786 return ret;
1788 str = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0);
1789 if (str == NULL) {
1790 return KRB5_PARSE_MALFORMED;
1792 ret = krb5_parse_name(context, str,
1793 &enterprise_principal);
1794 talloc_free(str);
1795 if (ret) {
1796 return ret;
1798 used_principal = enterprise_principal;
1799 } else {
1800 used_principal = principal;
1803 /* server as client principal case, but we must not lookup userPrincipalNames */
1804 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1806 /* TODO: Check if it is our realm, otherwise give referral */
1808 ret = krb5_unparse_name_flags(context, used_principal,
1809 KRB5_PRINCIPAL_UNPARSE_NO_REALM |
1810 KRB5_PRINCIPAL_UNPARSE_DISPLAY,
1811 &short_princ);
1812 used_principal = NULL;
1813 krb5_free_principal(context, enterprise_principal);
1814 enterprise_principal = NULL;
1816 if (ret != 0) {
1817 krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
1818 krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
1819 return ret;
1822 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
1823 SAFE_FREE(short_princ);
1824 if (name1 == NULL) {
1825 return ENOMEM;
1827 len1 = strlen(name1);
1828 if (len1 >= 1 && name1[len1 - 1] != '$') {
1829 filter = talloc_asprintf(mem_ctx,
1830 "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
1831 name1, name1);
1832 if (filter == NULL) {
1833 return ENOMEM;
1835 } else {
1836 filter = talloc_asprintf(mem_ctx,
1837 "(&(objectClass=user)(samAccountName=%s))",
1838 name1);
1839 if (filter == NULL) {
1840 return ENOMEM;
1844 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
1845 *realm_dn, LDB_SCOPE_SUBTREE,
1846 attrs,
1847 DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1848 "%s", filter);
1849 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1850 DEBUG(10, ("Failed to find an entry for %s filter:%s\n",
1851 name1, filter));
1852 return HDB_ERR_NOENTRY;
1854 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
1855 DEBUG(10, ("Failed to find unique entry for %s filter:%s\n",
1856 name1, filter));
1857 return HDB_ERR_NOENTRY;
1859 if (lret != LDB_SUCCESS) {
1860 DEBUG(0, ("Failed single search for %s - %s\n",
1861 name1, ldb_errstring(kdc_db_ctx->samdb)));
1862 return HDB_ERR_NOENTRY;
1864 return 0;
1866 return HDB_ERR_NOENTRY;
1871 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
1872 struct samba_kdc_db_context *kdc_db_ctx,
1873 TALLOC_CTX *mem_ctx,
1874 krb5_const_principal principal,
1875 unsigned flags,
1876 hdb_entry_ex *entry_ex)
1878 krb5_error_code ret;
1879 struct ldb_dn *realm_dn;
1880 struct ldb_message *msg;
1882 ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
1883 flags, server_attrs, &realm_dn, &msg);
1884 if (ret != 0) {
1885 return ret;
1888 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1889 principal, SAMBA_KDC_ENT_TYPE_SERVER,
1890 flags,
1891 realm_dn, msg, entry_ex);
1892 if (ret != 0) {
1893 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
1896 return ret;
1899 krb5_error_code samba_kdc_fetch(krb5_context context,
1900 struct samba_kdc_db_context *kdc_db_ctx,
1901 krb5_const_principal principal,
1902 unsigned flags,
1903 krb5_kvno kvno,
1904 hdb_entry_ex *entry_ex)
1906 krb5_error_code ret = HDB_ERR_NOENTRY;
1907 TALLOC_CTX *mem_ctx;
1909 mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
1910 if (!mem_ctx) {
1911 ret = ENOMEM;
1912 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1913 return ret;
1916 if (flags & HDB_F_GET_CLIENT) {
1917 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1918 if (ret != HDB_ERR_NOENTRY) goto done;
1920 if (flags & HDB_F_GET_SERVER) {
1921 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1922 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
1923 if (ret != HDB_ERR_NOENTRY) goto done;
1925 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1926 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1927 if (ret != HDB_ERR_NOENTRY) goto done;
1929 if (flags & HDB_F_GET_KRBTGT) {
1930 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
1931 if (ret != HDB_ERR_NOENTRY) goto done;
1934 done:
1935 talloc_free(mem_ctx);
1936 return ret;
1939 struct samba_kdc_seq {
1940 unsigned int index;
1941 unsigned int count;
1942 struct ldb_message **msgs;
1943 struct ldb_dn *realm_dn;
1946 static krb5_error_code samba_kdc_seq(krb5_context context,
1947 struct samba_kdc_db_context *kdc_db_ctx,
1948 hdb_entry_ex *entry)
1950 krb5_error_code ret;
1951 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1952 const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
1953 struct ldb_message *msg = NULL;
1954 const char *sAMAccountName = NULL;
1955 krb5_principal principal = NULL;
1956 TALLOC_CTX *mem_ctx;
1958 if (!priv) {
1959 return HDB_ERR_NOENTRY;
1962 mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
1964 if (!mem_ctx) {
1965 ret = ENOMEM;
1966 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
1967 return ret;
1970 while (priv->index < priv->count) {
1971 msg = priv->msgs[priv->index++];
1973 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
1974 if (sAMAccountName != NULL) {
1975 break;
1979 if (sAMAccountName == NULL) {
1980 ret = HDB_ERR_NOENTRY;
1981 goto out;
1984 ret = smb_krb5_make_principal(context, &principal,
1985 realm, sAMAccountName, NULL);
1986 if (ret != 0) {
1987 goto out;
1990 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1991 principal, SAMBA_KDC_ENT_TYPE_ANY,
1992 HDB_F_ADMIN_DATA|HDB_F_GET_ANY,
1993 priv->realm_dn, msg, entry);
1995 out:
1996 if (principal != NULL) {
1997 krb5_free_principal(context, principal);
2000 if (ret != 0) {
2001 TALLOC_FREE(priv);
2002 kdc_db_ctx->seq_ctx = NULL;
2003 } else {
2004 talloc_free(mem_ctx);
2007 return ret;
2010 krb5_error_code samba_kdc_firstkey(krb5_context context,
2011 struct samba_kdc_db_context *kdc_db_ctx,
2012 hdb_entry_ex *entry)
2014 struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
2015 struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2016 char *realm;
2017 struct ldb_result *res = NULL;
2018 krb5_error_code ret;
2019 TALLOC_CTX *mem_ctx;
2020 int lret;
2022 if (priv) {
2023 TALLOC_FREE(priv);
2024 kdc_db_ctx->seq_ctx = NULL;
2027 priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
2028 if (!priv) {
2029 ret = ENOMEM;
2030 krb5_set_error_message(context, ret, "talloc: out of memory");
2031 return ret;
2034 priv->index = 0;
2035 priv->msgs = NULL;
2036 priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
2037 priv->count = 0;
2039 mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
2041 if (!mem_ctx) {
2042 ret = ENOMEM;
2043 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
2044 return ret;
2047 ret = krb5_get_default_realm(context, &realm);
2048 if (ret != 0) {
2049 TALLOC_FREE(priv);
2050 return ret;
2052 krb5_free_default_realm(context, realm);
2054 lret = dsdb_search(ldb_ctx, priv, &res,
2055 priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
2056 DSDB_SEARCH_NO_GLOBAL_CATALOG,
2057 "(objectClass=user)");
2059 if (lret != LDB_SUCCESS) {
2060 TALLOC_FREE(priv);
2061 return HDB_ERR_NOENTRY;
2064 priv->count = res->count;
2065 priv->msgs = talloc_steal(priv, res->msgs);
2066 talloc_free(res);
2068 kdc_db_ctx->seq_ctx = priv;
2070 ret = samba_kdc_seq(context, kdc_db_ctx, entry);
2072 if (ret != 0) {
2073 TALLOC_FREE(priv);
2074 kdc_db_ctx->seq_ctx = NULL;
2075 } else {
2076 talloc_free(mem_ctx);
2078 return ret;
2081 krb5_error_code samba_kdc_nextkey(krb5_context context,
2082 struct samba_kdc_db_context *kdc_db_ctx,
2083 hdb_entry_ex *entry)
2085 return samba_kdc_seq(context, kdc_db_ctx, entry);
2088 /* Check if a given entry may delegate or do s4u2self to this target principal
2090 * This is currently a very nasty hack - allowing only delegation to itself.
2092 krb5_error_code
2093 samba_kdc_check_s4u2self(krb5_context context,
2094 struct samba_kdc_db_context *kdc_db_ctx,
2095 struct samba_kdc_entry *skdc_entry,
2096 krb5_const_principal target_principal)
2098 krb5_error_code ret;
2099 struct ldb_dn *realm_dn;
2100 struct ldb_message *msg;
2101 struct dom_sid *orig_sid;
2102 struct dom_sid *target_sid;
2103 const char *delegation_check_attrs[] = {
2104 "objectSid", NULL
2107 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2self");
2109 if (!mem_ctx) {
2110 ret = ENOMEM;
2111 krb5_set_error_message(context, ret, "samba_kdc_check_s4u2self: talloc_named() failed!");
2112 return ret;
2115 ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
2116 HDB_F_GET_CLIENT|HDB_F_GET_SERVER,
2117 delegation_check_attrs, &realm_dn, &msg);
2119 if (ret != 0) {
2120 talloc_free(mem_ctx);
2121 return ret;
2124 orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2125 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2127 /* Allow delegation to the same principal, even if by a different
2128 * name. The easy and safe way to prove this is by SID
2129 * comparison */
2130 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2131 talloc_free(mem_ctx);
2132 return KRB5KDC_ERR_BADOPTION;
2135 talloc_free(mem_ctx);
2136 return ret;
2139 /* Certificates printed by a the Certificate Authority might have a
2140 * slightly different form of the user principal name to that in the
2141 * database. Allow a mismatch where they both refer to the same
2142 * SID */
2144 krb5_error_code
2145 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
2146 struct samba_kdc_db_context *kdc_db_ctx,
2147 struct samba_kdc_entry *skdc_entry,
2148 krb5_const_principal certificate_principal)
2150 krb5_error_code ret;
2151 struct ldb_dn *realm_dn;
2152 struct ldb_message *msg;
2153 struct dom_sid *orig_sid;
2154 struct dom_sid *target_sid;
2155 const char *ms_upn_check_attrs[] = {
2156 "objectSid", NULL
2159 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
2161 if (!mem_ctx) {
2162 ret = ENOMEM;
2163 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2164 return ret;
2167 ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2168 mem_ctx, certificate_principal,
2169 ms_upn_check_attrs, &realm_dn, &msg);
2171 if (ret != 0) {
2172 talloc_free(mem_ctx);
2173 return ret;
2176 orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2177 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2179 /* Consider these to be the same principal, even if by a different
2180 * name. The easy and safe way to prove this is by SID
2181 * comparison */
2182 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2183 talloc_free(mem_ctx);
2184 #ifdef KRB5_KDC_ERR_CLIENT_NAME_MISMATCH /* Heimdal */
2185 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
2186 #elif defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
2187 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
2188 #endif
2191 talloc_free(mem_ctx);
2192 return ret;
2196 * Check if a given entry may delegate to this target principal
2197 * with S4U2Proxy.
2199 krb5_error_code
2200 samba_kdc_check_s4u2proxy(krb5_context context,
2201 struct samba_kdc_db_context *kdc_db_ctx,
2202 struct samba_kdc_entry *skdc_entry,
2203 krb5_const_principal target_principal)
2205 krb5_error_code ret;
2206 char *tmp = NULL;
2207 const char *client_dn = NULL;
2208 const char *target_principal_name = NULL;
2209 struct ldb_message_element *el;
2210 struct ldb_val val;
2211 unsigned int i;
2212 bool found = false;
2214 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
2216 if (!mem_ctx) {
2217 ret = ENOMEM;
2218 krb5_set_error_message(context, ret,
2219 "samba_kdc_check_s4u2proxy:"
2220 " talloc_named() failed!");
2221 return ret;
2224 client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
2225 if (!client_dn) {
2226 if (errno == 0) {
2227 errno = ENOMEM;
2229 ret = errno;
2230 krb5_set_error_message(context, ret,
2231 "samba_kdc_check_s4u2proxy:"
2232 " ldb_dn_get_linearized() failed!");
2233 return ret;
2237 * The main heimdal code already checked that the target_principal
2238 * belongs to the same realm as the client.
2240 * So we just need the principal without the realm,
2241 * as that is what is configured in the "msDS-AllowedToDelegateTo"
2242 * attribute.
2244 ret = krb5_unparse_name_flags(context, target_principal,
2245 KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
2246 if (ret) {
2247 talloc_free(mem_ctx);
2248 krb5_set_error_message(context, ret,
2249 "samba_kdc_check_s4u2proxy:"
2250 " krb5_unparse_name() failed!");
2251 return ret;
2253 DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
2254 client_dn, tmp));
2256 target_principal_name = talloc_strdup(mem_ctx, tmp);
2257 SAFE_FREE(tmp);
2258 if (target_principal_name == NULL) {
2259 ret = ENOMEM;
2260 krb5_set_error_message(context, ret,
2261 "samba_kdc_check_s4u2proxy:"
2262 " talloc_strdup() failed!");
2263 return ret;
2266 el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
2267 if (el == NULL) {
2268 goto bad_option;
2271 val = data_blob_string_const(target_principal_name);
2273 for (i=0; i<el->num_values; i++) {
2274 struct ldb_val *val1 = &val;
2275 struct ldb_val *val2 = &el->values[i];
2276 int cmp;
2278 if (val1->length != val2->length) {
2279 continue;
2282 cmp = strncasecmp((const char *)val1->data,
2283 (const char *)val2->data,
2284 val1->length);
2285 if (cmp != 0) {
2286 continue;
2289 found = true;
2290 break;
2293 if (!found) {
2294 goto bad_option;
2297 DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
2298 client_dn, tmp));
2299 talloc_free(mem_ctx);
2300 return 0;
2302 bad_option:
2303 krb5_set_error_message(context, ret,
2304 "samba_kdc_check_s4u2proxy: client[%s] "
2305 "not allowed for delegation to target[%s]",
2306 client_dn,
2307 target_principal_name);
2308 talloc_free(mem_ctx);
2309 return KRB5KDC_ERR_BADOPTION;
2312 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
2313 struct samba_kdc_db_context **kdc_db_ctx_out)
2315 int ldb_ret;
2316 struct ldb_message *msg;
2317 struct auth_session_info *session_info;
2318 struct samba_kdc_db_context *kdc_db_ctx;
2319 /* The idea here is very simple. Using Kerberos to
2320 * authenticate the KDC to the LDAP server is higly likely to
2321 * be circular.
2323 * In future we may set this up to use EXERNAL and SSL
2324 * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
2327 kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
2328 if (kdc_db_ctx == NULL) {
2329 return NT_STATUS_NO_MEMORY;
2331 kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
2332 kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
2334 /* get default kdc policy */
2335 lpcfg_default_kdc_policy(base_ctx->lp_ctx,
2336 &kdc_db_ctx->policy.svc_tkt_lifetime,
2337 &kdc_db_ctx->policy.usr_tkt_lifetime,
2338 &kdc_db_ctx->policy.renewal_lifetime);
2340 session_info = system_session(kdc_db_ctx->lp_ctx);
2341 if (session_info == NULL) {
2342 return NT_STATUS_INTERNAL_ERROR;
2345 /* Setup the link to LDB */
2346 kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
2347 base_ctx->lp_ctx, session_info, 0);
2348 if (kdc_db_ctx->samdb == NULL) {
2349 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
2350 talloc_free(kdc_db_ctx);
2351 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2354 /* Find out our own krbtgt kvno */
2355 ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
2356 if (ldb_ret != LDB_SUCCESS) {
2357 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
2358 ldb_errstring(kdc_db_ctx->samdb)));
2359 talloc_free(kdc_db_ctx);
2360 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2362 if (kdc_db_ctx->rodc) {
2363 int my_krbtgt_number;
2364 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
2365 struct ldb_dn *account_dn;
2366 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
2367 if (!server_dn) {
2368 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
2369 ldb_errstring(kdc_db_ctx->samdb)));
2370 talloc_free(kdc_db_ctx);
2371 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2374 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
2375 "serverReference", &account_dn);
2376 if (ldb_ret != LDB_SUCCESS) {
2377 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
2378 ldb_errstring(kdc_db_ctx->samdb)));
2379 talloc_free(kdc_db_ctx);
2380 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2383 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
2384 "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
2385 talloc_free(account_dn);
2386 if (ldb_ret != LDB_SUCCESS) {
2387 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
2388 ldb_errstring(kdc_db_ctx->samdb)));
2389 talloc_free(kdc_db_ctx);
2390 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2393 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2394 &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
2395 secondary_keytab,
2396 DSDB_SEARCH_NO_GLOBAL_CATALOG,
2397 "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
2398 if (ldb_ret != LDB_SUCCESS) {
2399 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
2400 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2401 ldb_errstring(kdc_db_ctx->samdb),
2402 ldb_strerror(ldb_ret)));
2403 talloc_free(kdc_db_ctx);
2404 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2406 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
2407 if (my_krbtgt_number == -1) {
2408 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
2409 ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2410 my_krbtgt_number));
2411 talloc_free(kdc_db_ctx);
2412 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2414 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
2416 } else {
2417 kdc_db_ctx->my_krbtgt_number = 0;
2418 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2419 &msg,
2420 ldb_get_default_basedn(kdc_db_ctx->samdb),
2421 LDB_SCOPE_SUBTREE,
2422 krbtgt_attrs,
2423 DSDB_SEARCH_NO_GLOBAL_CATALOG,
2424 "(&(objectClass=user)(samAccountName=krbtgt))");
2426 if (ldb_ret != LDB_SUCCESS) {
2427 DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
2428 talloc_free(kdc_db_ctx);
2429 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2431 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
2432 kdc_db_ctx->my_krbtgt_number = 0;
2433 talloc_free(msg);
2435 *kdc_db_ctx_out = kdc_db_ctx;
2436 return NT_STATUS_OK;