s4:dsdb: Implement DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS search flag
[Samba.git] / source4 / dsdb / common / util.c
blobd3fb3024db0dc5bf07ec58727591c1a2315df56b
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
5 Copyright (C) Andrew Tridgell 2004
6 Copyright (C) Volker Lendecke 2004
7 Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006
8 Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 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 "ldb.h"
26 #include "ldb_module.h"
27 #include "ldb_errors.h"
28 #include "../lib/util/util_ldb.h"
29 #include "lib/crypto/gmsa.h"
30 #include "dsdb/samdb/samdb.h"
31 #include "librpc/gen_ndr/ndr_security.h"
32 #include "librpc/gen_ndr/ndr_misc.h"
33 #include "../libds/common/flags.h"
34 #include "dsdb/common/proto.h"
35 #include "libcli/ldap/ldap_ndr.h"
36 #include "param/param.h"
37 #include "librpc/gen_ndr/ndr_drsblobs.h"
38 #include "dsdb/common/util.h"
39 #include "dsdb/gmsa/gkdi.h"
40 #include "dsdb/gmsa/util.h"
41 #include "lib/socket/socket.h"
42 #include "librpc/gen_ndr/irpc.h"
43 #include "libds/common/flag_mapping.h"
44 #include "lib/util/access.h"
45 #include "lib/util/data_blob.h"
46 #include "lib/util/debug.h"
47 #include "lib/util/fault.h"
48 #include "lib/util/sys_rw_data.h"
49 #include "libcli/util/ntstatus.h"
50 #include "lib/util/smb_strtox.h"
51 #include "auth/auth.h"
53 #undef strncasecmp
54 #undef strcasecmp
57 * This is included to allow us to handle DSDB_FLAG_REPLICATED_UPDATE in
58 * dsdb_request_add_controls()
60 #include "dsdb/samdb/ldb_modules/util.h"
62 /* default is 30 minutes: -1e7 * 30 * 60 */
63 #define DEFAULT_OBSERVATION_WINDOW (-18000000000)
66 search the sam for the specified attributes in a specific domain, filter on
67 objectSid being in domain_sid.
69 int samdb_search_domain(struct ldb_context *sam_ldb,
70 TALLOC_CTX *mem_ctx,
71 struct ldb_dn *basedn,
72 struct ldb_message ***res,
73 const char * const *attrs,
74 const struct dom_sid *domain_sid,
75 const char *format, ...) _PRINTF_ATTRIBUTE(7,8)
77 va_list ap;
78 int i, count;
80 va_start(ap, format);
81 count = gendb_search_v(sam_ldb, mem_ctx, basedn,
82 res, attrs, format, ap);
83 va_end(ap);
85 i=0;
87 while (i<count) {
88 struct dom_sid *entry_sid;
90 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
92 if ((entry_sid == NULL) ||
93 (!dom_sid_in_domain(domain_sid, entry_sid))) {
94 /* Delete that entry from the result set */
95 (*res)[i] = (*res)[count-1];
96 count -= 1;
97 talloc_free(entry_sid);
98 continue;
100 talloc_free(entry_sid);
101 i += 1;
104 return count;
108 search the sam for a single string attribute in exactly 1 record
110 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
111 TALLOC_CTX *mem_ctx,
112 struct ldb_dn *basedn,
113 const char *attr_name,
114 const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
116 int count;
117 const char *attrs[2] = { NULL, NULL };
118 struct ldb_message **res = NULL;
120 attrs[0] = attr_name;
122 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
123 if (count > 1) {
124 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
125 attr_name, format, count));
127 if (count != 1) {
128 talloc_free(res);
129 return NULL;
132 return ldb_msg_find_attr_as_string(res[0], attr_name, NULL);
136 search the sam for a single string attribute in exactly 1 record
138 const char *samdb_search_string(struct ldb_context *sam_ldb,
139 TALLOC_CTX *mem_ctx,
140 struct ldb_dn *basedn,
141 const char *attr_name,
142 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
144 va_list ap;
145 const char *str;
147 va_start(ap, format);
148 str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
149 va_end(ap);
151 return str;
154 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
155 TALLOC_CTX *mem_ctx,
156 struct ldb_dn *basedn,
157 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
159 va_list ap;
160 struct ldb_dn *ret;
161 struct ldb_message **res = NULL;
162 int count;
164 va_start(ap, format);
165 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
166 va_end(ap);
168 if (count != 1) return NULL;
170 ret = talloc_steal(mem_ctx, res[0]->dn);
171 talloc_free(res);
173 return ret;
177 search the sam for a dom_sid attribute in exactly 1 record
179 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
180 TALLOC_CTX *mem_ctx,
181 struct ldb_dn *basedn,
182 const char *attr_name,
183 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
185 va_list ap;
186 int count;
187 struct ldb_message **res;
188 const char *attrs[2] = { NULL, NULL };
189 struct dom_sid *sid;
191 attrs[0] = attr_name;
193 va_start(ap, format);
194 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
195 va_end(ap);
196 if (count > 1) {
197 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
198 attr_name, format, count));
200 if (count != 1) {
201 talloc_free(res);
202 return NULL;
204 sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
205 talloc_free(res);
206 return sid;
210 search the sam for a single integer attribute in exactly 1 record
212 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
213 TALLOC_CTX *mem_ctx,
214 unsigned int default_value,
215 struct ldb_dn *basedn,
216 const char *attr_name,
217 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
219 va_list ap;
220 int count;
221 struct ldb_message **res;
222 const char *attrs[2] = { NULL, NULL };
224 attrs[0] = attr_name;
226 va_start(ap, format);
227 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
228 va_end(ap);
230 if (count != 1) {
231 return default_value;
234 return ldb_msg_find_attr_as_uint(res[0], attr_name, default_value);
238 search the sam for a single signed 64 bit integer attribute in exactly 1 record
240 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
241 TALLOC_CTX *mem_ctx,
242 int64_t default_value,
243 struct ldb_dn *basedn,
244 const char *attr_name,
245 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
247 va_list ap;
248 int count;
249 struct ldb_message **res;
250 const char *attrs[2] = { NULL, NULL };
252 attrs[0] = attr_name;
254 va_start(ap, format);
255 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
256 va_end(ap);
258 if (count != 1) {
259 return default_value;
262 return ldb_msg_find_attr_as_int64(res[0], attr_name, default_value);
266 search the sam for multiple records each giving a single string attribute
267 return the number of matches, or -1 on error
269 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
270 TALLOC_CTX *mem_ctx,
271 struct ldb_dn *basedn,
272 const char ***strs,
273 const char *attr_name,
274 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
276 va_list ap;
277 int count, i;
278 const char *attrs[2] = { NULL, NULL };
279 struct ldb_message **res = NULL;
281 attrs[0] = attr_name;
283 va_start(ap, format);
284 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
285 va_end(ap);
287 if (count <= 0) {
288 return count;
291 /* make sure its single valued */
292 for (i=0;i<count;i++) {
293 if (res[i]->num_elements != 1) {
294 DEBUG(1,("samdb: search for %s %s not single valued\n",
295 attr_name, format));
296 talloc_free(res);
297 return -1;
301 *strs = talloc_array(mem_ctx, const char *, count+1);
302 if (! *strs) {
303 talloc_free(res);
304 return -1;
307 for (i=0;i<count;i++) {
308 (*strs)[i] = ldb_msg_find_attr_as_string(res[i], attr_name, NULL);
310 (*strs)[count] = NULL;
312 return count;
315 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
316 const char *attr, struct ldb_dn *default_value)
318 struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
319 if (!ret_dn) {
320 return default_value;
322 return ret_dn;
326 pull a rid from a objectSid in a result set.
328 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
329 const char *attr, uint32_t default_value)
331 struct dom_sid *sid;
332 uint32_t rid;
334 sid = samdb_result_dom_sid(mem_ctx, msg, attr);
335 if (sid == NULL) {
336 return default_value;
338 rid = sid->sub_auths[sid->num_auths-1];
339 talloc_free(sid);
340 return rid;
344 pull a dom_sid structure from a objectSid in a result set.
346 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
347 const char *attr)
349 ssize_t ret;
350 const struct ldb_val *v;
351 struct dom_sid *sid;
352 v = ldb_msg_find_ldb_val(msg, attr);
353 if (v == NULL) {
354 return NULL;
356 sid = talloc(mem_ctx, struct dom_sid);
357 if (sid == NULL) {
358 return NULL;
360 ret = sid_parse(v->data, v->length, sid);
361 if (ret == -1) {
362 talloc_free(sid);
363 return NULL;
365 return sid;
370 * Makes an auth_SidAttr structure from a objectSid in a result set and a
371 * supplied attribute value.
373 * @param [in] mem_ctx Talloc memory context on which to allocate the auth_SidAttr.
374 * @param [in] msg The message from which to take the objectSid.
375 * @param [in] attr The attribute name, usually "objectSid".
376 * @param [in] attrs SE_GROUP_* flags to go with the SID.
377 * @returns A pointer to the auth_SidAttr structure, or NULL on failure.
379 struct auth_SidAttr *samdb_result_dom_sid_attrs(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
380 const char *attr, uint32_t attrs)
382 ssize_t ret;
383 const struct ldb_val *v;
384 struct auth_SidAttr *sid;
385 v = ldb_msg_find_ldb_val(msg, attr);
386 if (v == NULL) {
387 return NULL;
389 sid = talloc(mem_ctx, struct auth_SidAttr);
390 if (sid == NULL) {
391 return NULL;
393 ret = sid_parse(v->data, v->length, &sid->sid);
394 if (ret == -1) {
395 talloc_free(sid);
396 return NULL;
398 sid->attrs = attrs;
399 return sid;
403 pull a dom_sid structure from a objectSid in a result set.
405 int samdb_result_dom_sid_buf(const struct ldb_message *msg,
406 const char *attr,
407 struct dom_sid *sid)
409 ssize_t ret;
410 const struct ldb_val *v = NULL;
411 v = ldb_msg_find_ldb_val(msg, attr);
412 if (v == NULL) {
413 return LDB_ERR_NO_SUCH_ATTRIBUTE;
415 ret = sid_parse(v->data, v->length, sid);
416 if (ret == -1) {
417 return LDB_ERR_OPERATIONS_ERROR;
419 return LDB_SUCCESS;
423 pull a guid structure from a objectGUID in a result set.
425 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
427 const struct ldb_val *v;
428 struct GUID guid;
429 NTSTATUS status;
431 v = ldb_msg_find_ldb_val(msg, attr);
432 if (!v) return GUID_zero();
434 status = GUID_from_ndr_blob(v, &guid);
435 if (!NT_STATUS_IS_OK(status)) {
436 return GUID_zero();
439 return guid;
443 pull a sid prefix from a objectSid in a result set.
444 this is used to find the domain sid for a user
446 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
447 const char *attr)
449 struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
450 if (!sid || sid->num_auths < 1) return NULL;
451 sid->num_auths--;
452 return sid;
456 pull a NTTIME in a result set.
458 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
459 NTTIME default_value)
461 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
465 * Windows stores 0 for lastLogoff.
466 * But when a MS DC return the lastLogoff (as Logoff Time)
467 * it returns INT64_MAX, not returning this value in this case
468 * cause windows 2008 and newer version to fail for SMB requests
470 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
472 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
474 if (ret == 0)
475 ret = INT64_MAX;
477 return ret;
481 * Windows uses both 0 and 9223372036854775807 (INT64_MAX) to
482 * indicate an account doesn't expire.
484 * When Windows initially creates an account, it sets
485 * accountExpires = 9223372036854775807 (INT64_MAX). However,
486 * when changing from an account having a specific expiration date to
487 * that account never expiring, it sets accountExpires = 0.
489 * Consolidate that logic here to allow clearer logic for account expiry in
490 * the rest of the code.
492 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
494 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
497 if (ret == 0)
498 ret = INT64_MAX;
500 return ret;
504 construct the allow_password_change field from the PwdLastSet attribute and the
505 domain password settings
507 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb,
508 TALLOC_CTX *mem_ctx,
509 struct ldb_dn *domain_dn,
510 const struct ldb_message *msg,
511 const char *attr)
513 uint64_t attr_time = ldb_msg_find_attr_as_uint64(msg, attr, 0);
514 int64_t minPwdAge;
516 if (attr_time == 0) {
517 return 0;
520 minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
522 /* yes, this is a -= not a += as minPwdAge is stored as the negative
523 of the number of 100-nano-seconds */
524 attr_time -= minPwdAge;
526 return attr_time;
530 pull a samr_Password structure from a result set.
532 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
534 struct samr_Password *hash = NULL;
535 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
536 if (val && (val->length >= sizeof(hash->hash))) {
537 hash = talloc(mem_ctx, struct samr_Password);
538 if (hash == NULL) {
539 return NULL;
541 talloc_keep_secret(hash);
542 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
544 return hash;
548 pull an array of samr_Password structures from a result set.
550 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
551 const char *attr, struct samr_Password **hashes)
553 unsigned int count, i;
554 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
556 *hashes = NULL;
557 if (!val) {
558 return 0;
560 if (val->length % 16 != 0) {
562 * The length is wrong. Don’t try to read beyond the end of the
563 * buffer.
565 return 0;
567 count = val->length / 16;
568 if (count == 0) {
569 return 0;
572 *hashes = talloc_array(mem_ctx, struct samr_Password, count);
573 if (! *hashes) {
574 return 0;
576 talloc_keep_secret(*hashes);
578 for (i=0;i<count;i++) {
579 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
582 return count;
585 NTSTATUS samdb_result_passwords_from_history(TALLOC_CTX *mem_ctx,
586 struct loadparm_context *lp_ctx,
587 const struct ldb_message *msg,
588 unsigned int idx,
589 const struct samr_Password **lm_pwd,
590 const struct samr_Password **nt_pwd)
592 struct samr_Password *lmPwdHash, *ntPwdHash;
594 if (nt_pwd) {
595 unsigned int num_nt;
596 num_nt = samdb_result_hashes(mem_ctx, msg, "ntPwdHistory", &ntPwdHash);
597 if (num_nt <= idx) {
598 *nt_pwd = NULL;
599 } else {
600 *nt_pwd = &ntPwdHash[idx];
603 if (lm_pwd) {
604 /* Ensure that if we have turned off LM
605 * authentication, that we never use the LM hash, even
606 * if we store it */
607 if (lpcfg_lanman_auth(lp_ctx)) {
608 unsigned int num_lm;
609 num_lm = samdb_result_hashes(mem_ctx, msg, "lmPwdHistory", &lmPwdHash);
610 if (num_lm <= idx) {
611 *lm_pwd = NULL;
612 } else {
613 *lm_pwd = &lmPwdHash[idx];
615 } else {
616 *lm_pwd = NULL;
619 return NT_STATUS_OK;
622 NTSTATUS samdb_result_passwords_no_lockout(TALLOC_CTX *mem_ctx,
623 struct loadparm_context *lp_ctx,
624 const struct ldb_message *msg,
625 struct samr_Password **nt_pwd)
627 struct samr_Password *ntPwdHash;
629 if (nt_pwd) {
630 unsigned int num_nt;
631 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
632 if (num_nt == 0) {
633 *nt_pwd = NULL;
634 } else if (num_nt > 1) {
635 return NT_STATUS_INTERNAL_DB_CORRUPTION;
636 } else {
637 *nt_pwd = &ntPwdHash[0];
640 return NT_STATUS_OK;
643 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx,
644 struct loadparm_context *lp_ctx,
645 const struct ldb_message *msg,
646 struct samr_Password **nt_pwd)
648 uint16_t acct_flags;
650 acct_flags = samdb_result_acct_flags(msg,
651 "msDS-User-Account-Control-Computed");
652 /* Quit if the account was locked out. */
653 if (acct_flags & ACB_AUTOLOCK) {
654 DEBUG(3,("samdb_result_passwords: Account for user %s was locked out.\n",
655 ldb_dn_get_linearized(msg->dn)));
656 return NT_STATUS_ACCOUNT_LOCKED_OUT;
659 return samdb_result_passwords_no_lockout(mem_ctx, lp_ctx, msg,
660 nt_pwd);
664 pull a samr_LogonHours structure from a result set.
666 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
668 struct samr_LogonHours hours = {};
669 size_t units_per_week = 168;
670 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
672 if (val) {
673 units_per_week = val->length * 8;
676 hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
677 if (!hours.bits) {
678 return hours;
680 hours.units_per_week = units_per_week;
681 memset(hours.bits, 0xFF, units_per_week/8);
682 if (val) {
683 memcpy(hours.bits, val->data, val->length);
686 return hours;
690 pull a set of account_flags from a result set.
692 Naturally, this requires that userAccountControl and
693 (if not null) the attributes 'attr' be already
694 included in msg
696 uint32_t samdb_result_acct_flags(const struct ldb_message *msg, const char *attr)
698 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
699 uint32_t attr_flags = 0;
700 uint32_t acct_flags = ds_uf2acb(userAccountControl);
701 if (attr) {
702 attr_flags = ldb_msg_find_attr_as_uint(msg, attr, UF_ACCOUNTDISABLE);
703 if (attr_flags == UF_ACCOUNTDISABLE) {
704 DEBUG(0, ("Attribute %s not found, disabling account %s!\n", attr,
705 ldb_dn_get_linearized(msg->dn)));
707 acct_flags |= ds_uf2acb(attr_flags);
710 return acct_flags;
713 NTSTATUS samdb_result_parameters(TALLOC_CTX *mem_ctx,
714 struct ldb_message *msg,
715 const char *attr,
716 struct lsa_BinaryString *s)
718 int i;
719 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
721 ZERO_STRUCTP(s);
723 if (!val) {
724 return NT_STATUS_OK;
727 if ((val->length % 2) != 0) {
729 * If the on-disk data is not even in length, we know
730 * it is corrupt, and can not be safely pushed. We
731 * would either truncate, send an uninitialised
732 * byte or send a forced zero byte
734 return NT_STATUS_INTERNAL_DB_CORRUPTION;
737 s->array = talloc_array(mem_ctx, uint16_t, val->length/2);
738 if (!s->array) {
739 return NT_STATUS_NO_MEMORY;
741 s->length = s->size = val->length;
743 /* The on-disk format is the 'network' format, being UTF16LE (sort of) */
744 for (i = 0; i < s->length / 2; i++) {
745 s->array[i] = SVAL(val->data, i * 2);
748 return NT_STATUS_OK;
751 /* Find an attribute, with a particular value */
753 /* The current callers of this function expect a very specific
754 * behaviour: In particular, objectClass subclass equivalence is not
755 * wanted. This means that we should not lookup the schema for the
756 * comparison function */
757 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
758 const struct ldb_message *msg,
759 const char *name, const char *value)
761 unsigned int i;
762 struct ldb_message_element *el = ldb_msg_find_element(msg, name);
764 if (!el) {
765 return NULL;
768 for (i=0;i<el->num_values;i++) {
769 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
770 return el;
774 return NULL;
777 static int samdb_find_or_add_attribute_ex(struct ldb_context *ldb,
778 struct ldb_message *msg,
779 const char *name,
780 const char *set_value,
781 unsigned attr_flags,
782 bool *added)
784 int ret;
785 struct ldb_message_element *el;
787 SMB_ASSERT(attr_flags != 0);
789 el = ldb_msg_find_element(msg, name);
790 if (el) {
791 if (added != NULL) {
792 *added = false;
795 return LDB_SUCCESS;
798 ret = ldb_msg_add_empty(msg, name,
799 attr_flags,
800 &el);
801 if (ret != LDB_SUCCESS) {
802 return ret;
805 if (set_value != NULL) {
806 ret = ldb_msg_add_string(msg, name, set_value);
807 if (ret != LDB_SUCCESS) {
808 return ret;
812 if (added != NULL) {
813 *added = true;
815 return LDB_SUCCESS;
818 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
820 return samdb_find_or_add_attribute_ex(ldb, msg, name, set_value, LDB_FLAG_MOD_ADD, NULL);
824 add a dom_sid element to a message
826 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
827 const char *attr_name, const struct dom_sid *sid)
829 struct ldb_val v;
830 enum ndr_err_code ndr_err;
832 ndr_err = ndr_push_struct_blob(&v, mem_ctx,
833 sid,
834 (ndr_push_flags_fn_t)ndr_push_dom_sid);
835 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
836 return ldb_operr(sam_ldb);
838 return ldb_msg_add_value(msg, attr_name, &v, NULL);
843 add a delete element operation to a message
845 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
846 const char *attr_name)
848 /* we use an empty replace rather than a delete, as it allows for
849 dsdb_replace() to be used everywhere */
850 return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
854 add an add attribute value to a message or enhance an existing attribute
855 which has the same name and the add flag set.
857 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
858 struct ldb_message *msg, const char *attr_name,
859 const char *value)
861 struct ldb_message_element *el;
862 struct ldb_val val;
863 char *v;
864 unsigned int i;
865 bool found = false;
866 int ret;
868 v = talloc_strdup(mem_ctx, value);
869 if (v == NULL) {
870 return ldb_oom(sam_ldb);
873 val.data = (uint8_t *) v;
874 val.length = strlen(v);
876 if (val.length == 0) {
877 /* allow empty strings as non-existent attributes */
878 return LDB_SUCCESS;
881 for (i = 0; i < msg->num_elements; i++) {
882 el = &msg->elements[i];
883 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
884 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
885 found = true;
886 break;
889 if (!found) {
890 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
891 &el);
892 if (ret != LDB_SUCCESS) {
893 return ret;
897 ret = ldb_msg_element_add_value(msg->elements, el, &val);
898 if (ret != LDB_SUCCESS) {
899 return ldb_oom(sam_ldb);
902 return LDB_SUCCESS;
906 add a delete attribute value to a message or enhance an existing attribute
907 which has the same name and the delete flag set.
909 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
910 struct ldb_message *msg, const char *attr_name,
911 const char *value)
913 struct ldb_message_element *el;
914 struct ldb_val val;
915 char *v;
916 unsigned int i;
917 bool found = false;
918 int ret;
920 v = talloc_strdup(mem_ctx, value);
921 if (v == NULL) {
922 return ldb_oom(sam_ldb);
925 val.data = (uint8_t *) v;
926 val.length = strlen(v);
928 if (val.length == 0) {
929 /* allow empty strings as non-existent attributes */
930 return LDB_SUCCESS;
933 for (i = 0; i < msg->num_elements; i++) {
934 el = &msg->elements[i];
935 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
936 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
937 found = true;
938 break;
941 if (!found) {
942 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
943 &el);
944 if (ret != LDB_SUCCESS) {
945 return ret;
949 ret = ldb_msg_element_add_value(msg->elements, el, &val);
950 if (ret != LDB_SUCCESS) {
951 return ldb_oom(sam_ldb);
954 return LDB_SUCCESS;
958 add a int element to a message
960 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
961 const char *attr_name, int v)
963 const char *s = talloc_asprintf(mem_ctx, "%d", v);
964 if (s == NULL) {
965 return ldb_oom(sam_ldb);
967 return ldb_msg_add_string(msg, attr_name, s);
970 int samdb_msg_add_int_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
971 const char *attr_name, int v, int flags)
973 const char *s = talloc_asprintf(mem_ctx, "%d", v);
974 if (s == NULL) {
975 return ldb_oom(sam_ldb);
977 return ldb_msg_add_string_flags(msg, attr_name, s, flags);
981 * Add an unsigned int element to a message
983 * The issue here is that we have not yet first cast to int32_t explicitly,
984 * before we cast to an signed int to printf() into the %d or cast to a
985 * int64_t before we then cast to a long long to printf into a %lld.
987 * There are *no* unsigned integers in Active Directory LDAP, even the RID
988 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
989 * (See the schema, and the syntax definitions in schema_syntax.c).
992 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
993 const char *attr_name, unsigned int v)
995 return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
998 int samdb_msg_add_uint_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
999 const char *attr_name, unsigned int v, int flags)
1001 return samdb_msg_add_int_flags(sam_ldb, mem_ctx, msg, attr_name, (int)v, flags);
1005 add a (signed) int64_t element to a message
1007 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1008 const char *attr_name, int64_t v)
1010 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
1011 if (s == NULL) {
1012 return ldb_oom(sam_ldb);
1014 return ldb_msg_add_string(msg, attr_name, s);
1018 * Add an unsigned int64_t (uint64_t) element to a message
1020 * The issue here is that we have not yet first cast to int32_t explicitly,
1021 * before we cast to an signed int to printf() into the %d or cast to a
1022 * int64_t before we then cast to a long long to printf into a %lld.
1024 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1025 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1026 * (See the schema, and the syntax definitions in schema_syntax.c).
1029 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1030 const char *attr_name, uint64_t v)
1032 return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
1036 append a int element to a message
1038 int samdb_msg_append_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1039 const char *attr_name, int v, int flags)
1041 const char *s = talloc_asprintf(mem_ctx, "%d", v);
1042 if (s == NULL) {
1043 return ldb_oom(sam_ldb);
1045 return ldb_msg_append_string(msg, attr_name, s, flags);
1049 * Append an unsigned int element to a message
1051 * The issue here is that we have not yet first cast to int32_t explicitly,
1052 * before we cast to an signed int to printf() into the %d or cast to a
1053 * int64_t before we then cast to a long long to printf into a %lld.
1055 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1056 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1057 * (See the schema, and the syntax definitions in schema_syntax.c).
1060 int samdb_msg_append_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1061 const char *attr_name, unsigned int v, int flags)
1063 return samdb_msg_append_int(sam_ldb, mem_ctx, msg, attr_name, (int)v, flags);
1067 append a (signed) int64_t element to a message
1069 int samdb_msg_append_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1070 const char *attr_name, int64_t v, int flags)
1072 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
1073 if (s == NULL) {
1074 return ldb_oom(sam_ldb);
1076 return ldb_msg_append_string(msg, attr_name, s, flags);
1080 * Append an unsigned int64_t (uint64_t) element to a message
1082 * The issue here is that we have not yet first cast to int32_t explicitly,
1083 * before we cast to an signed int to printf() into the %d or cast to a
1084 * int64_t before we then cast to a long long to printf into a %lld.
1086 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1087 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1088 * (See the schema, and the syntax definitions in schema_syntax.c).
1091 int samdb_msg_append_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1092 const char *attr_name, uint64_t v, int flags)
1094 return samdb_msg_append_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v, flags);
1098 add a samr_Password element to a message
1100 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1101 const char *attr_name, const struct samr_Password *hash)
1103 struct ldb_val val;
1104 val.data = talloc_memdup(mem_ctx, hash->hash, 16);
1105 if (!val.data) {
1106 return ldb_oom(sam_ldb);
1108 val.length = 16;
1109 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1113 add a samr_Password array to a message
1115 int samdb_msg_add_hashes(struct ldb_context *ldb,
1116 TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1117 const char *attr_name, struct samr_Password *hashes,
1118 unsigned int count)
1120 struct ldb_val val;
1121 unsigned int i;
1122 val.data = talloc_array_size(mem_ctx, 16, count);
1123 val.length = count*16;
1124 if (!val.data) {
1125 return ldb_oom(ldb);
1127 for (i=0;i<count;i++) {
1128 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
1130 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1134 add a acct_flags element to a message
1136 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1137 const char *attr_name, uint32_t v)
1139 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1143 add a logon_hours element to a message
1145 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1146 const char *attr_name, struct samr_LogonHours *hours)
1148 struct ldb_val val;
1149 val.length = hours->units_per_week / 8;
1150 val.data = hours->bits;
1151 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1155 add a parameters element to a message
1157 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1158 const char *attr_name, struct lsa_BinaryString *parameters)
1160 int i;
1161 struct ldb_val val;
1162 if ((parameters->length % 2) != 0) {
1163 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
1166 val.data = talloc_array(mem_ctx, uint8_t, parameters->length);
1167 if (val.data == NULL) {
1168 return LDB_ERR_OPERATIONS_ERROR;
1170 val.length = parameters->length;
1171 for (i = 0; i < parameters->length / 2; i++) {
1173 * The on-disk format needs to be in the 'network'
1174 * format, parameters->array is a uint16_t array of
1175 * length parameters->length / 2
1177 SSVAL(val.data, i * 2, parameters->array[i]);
1179 return ldb_msg_add_steal_value(msg, attr_name, &val);
1183 * Sets an unsigned int element in a message
1185 * The issue here is that we have not yet first cast to int32_t explicitly,
1186 * before we cast to an signed int to printf() into the %d or cast to a
1187 * int64_t before we then cast to a long long to printf into a %lld.
1189 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1190 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1191 * (See the schema, and the syntax definitions in schema_syntax.c).
1194 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1195 struct ldb_message *msg, const char *attr_name,
1196 unsigned int v)
1198 struct ldb_message_element *el;
1200 el = ldb_msg_find_element(msg, attr_name);
1201 if (el) {
1202 el->num_values = 0;
1204 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1208 * Handle ldb_request in transaction
1210 int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1211 struct ldb_request *req)
1213 int ret;
1215 ret = ldb_transaction_start(sam_ldb);
1216 if (ret != LDB_SUCCESS) {
1217 return ret;
1220 ret = ldb_request(sam_ldb, req);
1221 if (ret == LDB_SUCCESS) {
1222 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1225 if (ret == LDB_SUCCESS) {
1226 return ldb_transaction_commit(sam_ldb);
1228 ldb_transaction_cancel(sam_ldb);
1230 return ret;
1234 return a default security descriptor
1236 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1238 struct security_descriptor *sd;
1240 sd = security_descriptor_initialise(mem_ctx);
1242 return sd;
1245 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1247 struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1248 struct ldb_dn *aggregate_dn;
1249 if (!schema_dn) {
1250 return NULL;
1253 aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1254 if (!aggregate_dn) {
1255 return NULL;
1257 if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1258 return NULL;
1260 return aggregate_dn;
1263 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1265 struct ldb_dn *new_dn;
1267 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1268 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1269 talloc_free(new_dn);
1270 return NULL;
1272 return new_dn;
1275 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1277 struct ldb_dn *new_dn;
1279 new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1280 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1281 talloc_free(new_dn);
1282 return NULL;
1284 return new_dn;
1287 struct ldb_dn *samdb_system_container_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1289 struct ldb_dn *new_dn = NULL;
1290 bool ok;
1292 new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1293 if (new_dn == NULL) {
1294 return NULL;
1297 ok = ldb_dn_add_child_fmt(new_dn, "CN=System");
1298 if (!ok) {
1299 TALLOC_FREE(new_dn);
1300 return NULL;
1303 return new_dn;
1306 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1308 struct ldb_dn *new_dn;
1310 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1311 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1312 talloc_free(new_dn);
1313 return NULL;
1315 return new_dn;
1318 struct ldb_dn *samdb_extended_rights_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1320 struct ldb_dn *new_dn;
1322 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1323 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Extended-Rights")) {
1324 talloc_free(new_dn);
1325 return NULL;
1327 return new_dn;
1330 struct ldb_dn *samdb_configuration_dn(struct ldb_context *sam_ctx,
1331 TALLOC_CTX *mem_ctx,
1332 const char *dn_str)
1334 struct ldb_dn *config_dn = NULL;
1335 struct ldb_dn *child_dn = NULL;
1336 bool ok;
1338 config_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1339 if (config_dn == NULL) {
1340 return NULL;
1343 child_dn = ldb_dn_new(mem_ctx, sam_ctx, dn_str);
1344 if (child_dn == NULL) {
1345 talloc_free(config_dn);
1346 return NULL;
1349 ok = ldb_dn_add_child(config_dn, child_dn);
1350 talloc_free(child_dn);
1351 if (!ok) {
1352 talloc_free(config_dn);
1353 return NULL;
1356 return config_dn;
1359 struct ldb_dn *samdb_gkdi_root_key_container_dn(struct ldb_context *sam_ctx,
1360 TALLOC_CTX *mem_ctx)
1363 * [MS-GKDI] says the root key container is to be found in “CN=Sid Key
1364 * Service,CN=Services”, but that is not correct.
1366 return samdb_configuration_dn(sam_ctx,
1367 mem_ctx,
1368 "CN=Master Root Keys,"
1369 "CN=Group Key Distribution Service,"
1370 "CN=Services");
1373 struct ldb_dn *samdb_gkdi_root_key_dn(struct ldb_context *sam_ctx,
1374 TALLOC_CTX *mem_ctx,
1375 const struct GUID *root_key_id)
1377 struct ldb_dn *root_key_dn = NULL;
1378 struct ldb_dn *child_dn = NULL;
1379 struct GUID_txt_buf guid_buf;
1380 char *root_key_id_string = NULL;
1381 bool ok;
1383 root_key_id_string = GUID_buf_string(root_key_id, &guid_buf);
1384 if (root_key_id_string == NULL) {
1385 return NULL;
1388 root_key_dn = samdb_gkdi_root_key_container_dn(sam_ctx, mem_ctx);
1389 if (root_key_dn == NULL) {
1390 return NULL;
1393 child_dn = ldb_dn_new_fmt(mem_ctx,
1394 sam_ctx,
1395 "CN=%s",
1396 root_key_id_string);
1397 if (child_dn == NULL) {
1398 talloc_free(root_key_dn);
1399 return NULL;
1402 ok = ldb_dn_add_child(root_key_dn, child_dn);
1403 talloc_free(child_dn);
1404 if (!ok) {
1405 talloc_free(root_key_dn);
1406 return NULL;
1409 return root_key_dn;
1413 work out the domain sid for the current open ldb
1415 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1417 TALLOC_CTX *tmp_ctx;
1418 const struct dom_sid *domain_sid;
1419 const char *attrs[] = {
1420 "objectSid",
1421 NULL
1423 struct ldb_result *res;
1424 int ret;
1426 /* see if we have a cached copy */
1427 domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1428 if (domain_sid) {
1429 return domain_sid;
1432 tmp_ctx = talloc_new(ldb);
1433 if (tmp_ctx == NULL) {
1434 goto failed;
1437 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1439 if (ret != LDB_SUCCESS) {
1440 goto failed;
1443 if (res->count != 1) {
1444 goto failed;
1447 domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1448 if (domain_sid == NULL) {
1449 goto failed;
1452 /* cache the domain_sid in the ldb */
1453 if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1454 goto failed;
1457 talloc_steal(ldb, domain_sid);
1458 talloc_free(tmp_ctx);
1460 return domain_sid;
1462 failed:
1463 talloc_free(tmp_ctx);
1464 return NULL;
1468 get domain sid from cache
1470 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1472 return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1475 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1477 TALLOC_CTX *tmp_ctx;
1478 struct dom_sid *dom_sid_new;
1479 struct dom_sid *dom_sid_old;
1481 /* see if we have a cached copy */
1482 dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1483 "cache.domain_sid"), struct dom_sid);
1485 tmp_ctx = talloc_new(ldb);
1486 if (tmp_ctx == NULL) {
1487 goto failed;
1490 dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1491 if (!dom_sid_new) {
1492 goto failed;
1495 /* cache the domain_sid in the ldb */
1496 if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1497 goto failed;
1500 talloc_steal(ldb, dom_sid_new);
1501 talloc_free(tmp_ctx);
1502 talloc_free(dom_sid_old);
1504 return true;
1506 failed:
1507 DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1508 talloc_free(tmp_ctx);
1509 return false;
1513 work out the domain guid for the current open ldb
1515 const struct GUID *samdb_domain_guid(struct ldb_context *ldb)
1517 TALLOC_CTX *tmp_ctx = NULL;
1518 struct GUID *domain_guid = NULL;
1519 const char *attrs[] = {
1520 "objectGUID",
1521 NULL
1523 struct ldb_result *res = NULL;
1524 int ret;
1526 /* see if we have a cached copy */
1527 domain_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.domain_guid");
1528 if (domain_guid) {
1529 return domain_guid;
1532 tmp_ctx = talloc_new(ldb);
1533 if (tmp_ctx == NULL) {
1534 goto failed;
1537 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectGUID=*");
1538 if (ret != LDB_SUCCESS) {
1539 goto failed;
1542 if (res->count != 1) {
1543 goto failed;
1546 domain_guid = talloc(tmp_ctx, struct GUID);
1547 if (domain_guid == NULL) {
1548 goto failed;
1550 *domain_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1552 /* cache the domain_sid in the ldb */
1553 if (ldb_set_opaque(ldb, "cache.domain_guid", domain_guid) != LDB_SUCCESS) {
1554 goto failed;
1557 talloc_steal(ldb, domain_guid);
1558 talloc_free(tmp_ctx);
1560 return domain_guid;
1562 failed:
1563 talloc_free(tmp_ctx);
1564 return NULL;
1567 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1569 TALLOC_CTX *tmp_ctx;
1570 struct ldb_dn *ntds_settings_dn_new;
1571 struct ldb_dn *ntds_settings_dn_old;
1573 /* see if we have a forced copy from provision */
1574 ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb,
1575 "forced.ntds_settings_dn"), struct ldb_dn);
1577 tmp_ctx = talloc_new(ldb);
1578 if (tmp_ctx == NULL) {
1579 goto failed;
1582 ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1583 if (!ntds_settings_dn_new) {
1584 goto failed;
1587 /* set the DN in the ldb to avoid lookups during provision */
1588 if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1589 goto failed;
1592 talloc_steal(ldb, ntds_settings_dn_new);
1593 talloc_free(tmp_ctx);
1594 talloc_free(ntds_settings_dn_old);
1596 return true;
1598 failed:
1599 DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1600 talloc_free(tmp_ctx);
1601 return false;
1605 work out the ntds settings dn for the current open ldb
1607 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1609 TALLOC_CTX *tmp_ctx;
1610 const char *root_attrs[] = { "dsServiceName", NULL };
1611 int ret;
1612 struct ldb_result *root_res;
1613 struct ldb_dn *settings_dn;
1615 /* see if we have a cached copy */
1616 settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1617 if (settings_dn) {
1618 return ldb_dn_copy(mem_ctx, settings_dn);
1621 tmp_ctx = talloc_new(mem_ctx);
1622 if (tmp_ctx == NULL) {
1623 goto failed;
1626 ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1627 if (ret != LDB_SUCCESS) {
1628 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1629 ldb_errstring(ldb)));
1630 goto failed;
1633 if (root_res->count != 1) {
1634 goto failed;
1637 settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1639 /* note that we do not cache the DN here, as that would mean
1640 * we could not handle server renames at runtime. Only
1641 * provision sets up forced.ntds_settings_dn */
1643 talloc_steal(mem_ctx, settings_dn);
1644 talloc_free(tmp_ctx);
1646 return settings_dn;
1648 failed:
1649 DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1650 talloc_free(tmp_ctx);
1651 return NULL;
1655 work out the ntds settings invocationID/objectGUID for the current open ldb
1657 static const struct GUID *samdb_ntds_GUID(struct ldb_context *ldb,
1658 const char *attribute,
1659 const char *cache_name)
1661 TALLOC_CTX *tmp_ctx;
1662 const char *attrs[] = { attribute, NULL };
1663 int ret;
1664 struct ldb_result *res;
1665 struct GUID *ntds_guid;
1666 struct ldb_dn *ntds_settings_dn = NULL;
1667 const char *errstr = NULL;
1669 /* see if we have a cached copy */
1670 ntds_guid = (struct GUID *)ldb_get_opaque(ldb, cache_name);
1671 if (ntds_guid != NULL) {
1672 return ntds_guid;
1675 tmp_ctx = talloc_new(ldb);
1676 if (tmp_ctx == NULL) {
1677 goto failed;
1680 ntds_settings_dn = samdb_ntds_settings_dn(ldb, tmp_ctx);
1681 if (ntds_settings_dn == NULL) {
1682 errstr = "samdb_ntds_settings_dn() returned NULL";
1683 goto failed;
1686 ret = ldb_search(ldb, tmp_ctx, &res, ntds_settings_dn,
1687 LDB_SCOPE_BASE, attrs, NULL);
1688 if (ret) {
1689 errstr = ldb_errstring(ldb);
1690 goto failed;
1693 if (res->count != 1) {
1694 errstr = "incorrect number of results from base search";
1695 goto failed;
1698 ntds_guid = talloc(tmp_ctx, struct GUID);
1699 if (ntds_guid == NULL) {
1700 goto failed;
1703 *ntds_guid = samdb_result_guid(res->msgs[0], attribute);
1705 if (GUID_all_zero(ntds_guid)) {
1706 if (ldb_msg_find_ldb_val(res->msgs[0], attribute)) {
1707 errstr = "failed to find the GUID attribute";
1708 } else {
1709 errstr = "failed to parse the GUID";
1711 goto failed;
1714 /* cache the domain_sid in the ldb */
1715 if (ldb_set_opaque(ldb, cache_name, ntds_guid) != LDB_SUCCESS) {
1716 errstr = "ldb_set_opaque() failed";
1717 goto failed;
1720 talloc_steal(ldb, ntds_guid);
1721 talloc_free(tmp_ctx);
1723 return ntds_guid;
1725 failed:
1726 DBG_WARNING("Failed to find our own NTDS Settings %s in the ldb: %s!\n",
1727 attribute, errstr);
1728 talloc_free(tmp_ctx);
1729 return NULL;
1733 work out the ntds settings objectGUID for the current open ldb
1735 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1737 return samdb_ntds_GUID(ldb, "objectGUID", "cache.ntds_guid");
1741 work out the ntds settings invocationId for the current open ldb
1743 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1745 return samdb_ntds_GUID(ldb, "invocationId", "cache.invocation_id");
1748 static bool samdb_set_ntds_GUID(struct ldb_context *ldb,
1749 const struct GUID *ntds_guid_in,
1750 const char *attribute,
1751 const char *cache_name)
1753 TALLOC_CTX *tmp_ctx;
1754 struct GUID *ntds_guid_new;
1755 struct GUID *ntds_guid_old;
1757 /* see if we have a cached copy */
1758 ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, cache_name);
1760 tmp_ctx = talloc_new(ldb);
1761 if (tmp_ctx == NULL) {
1762 goto failed;
1765 ntds_guid_new = talloc(tmp_ctx, struct GUID);
1766 if (!ntds_guid_new) {
1767 goto failed;
1770 *ntds_guid_new = *ntds_guid_in;
1772 /* cache the domain_sid in the ldb */
1773 if (ldb_set_opaque(ldb, cache_name, ntds_guid_new) != LDB_SUCCESS) {
1774 goto failed;
1777 talloc_steal(ldb, ntds_guid_new);
1778 talloc_free(tmp_ctx);
1779 talloc_free(ntds_guid_old);
1781 return true;
1783 failed:
1784 DBG_WARNING("Failed to set our own cached %s in the ldb!\n",
1785 attribute);
1786 talloc_free(tmp_ctx);
1787 return false;
1790 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1792 return samdb_set_ntds_GUID(ldb,
1793 ntds_guid_in,
1794 "objectGUID",
1795 "cache.ntds_guid");
1798 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1800 return samdb_set_ntds_GUID(ldb,
1801 invocation_id_in,
1802 "invocationId",
1803 "cache.invocation_id");
1807 work out the server dn for the current open ldb
1809 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1811 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1812 struct ldb_dn *dn;
1813 if (!tmp_ctx) {
1814 return NULL;
1816 dn = ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb, tmp_ctx));
1817 talloc_free(tmp_ctx);
1818 return dn;
1823 work out the server dn for the current open ldb
1825 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1827 struct ldb_dn *server_dn;
1828 struct ldb_dn *servers_dn;
1829 struct ldb_dn *server_site_dn;
1831 /* TODO: there must be a saner way to do this!! */
1832 server_dn = samdb_server_dn(ldb, mem_ctx);
1833 if (!server_dn) return NULL;
1835 servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1836 talloc_free(server_dn);
1837 if (!servers_dn) return NULL;
1839 server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1840 talloc_free(servers_dn);
1842 return server_site_dn;
1846 find the site name from a computers DN record
1848 int samdb_find_site_for_computer(struct ldb_context *ldb,
1849 TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1850 const char **site_name)
1852 int ret;
1853 struct ldb_dn *dn;
1854 const struct ldb_val *rdn_val;
1856 *site_name = NULL;
1858 ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1859 if (ret != LDB_SUCCESS) {
1860 return ret;
1863 if (!ldb_dn_remove_child_components(dn, 2)) {
1864 talloc_free(dn);
1865 return LDB_ERR_INVALID_DN_SYNTAX;
1868 rdn_val = ldb_dn_get_rdn_val(dn);
1869 if (rdn_val == NULL) {
1870 return LDB_ERR_OPERATIONS_ERROR;
1873 (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1874 talloc_free(dn);
1875 if (!*site_name) {
1876 return LDB_ERR_OPERATIONS_ERROR;
1878 return LDB_SUCCESS;
1882 find the NTDS GUID from a computers DN record
1884 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1885 struct GUID *ntds_guid)
1887 int ret;
1888 struct ldb_dn *dn;
1890 *ntds_guid = GUID_zero();
1892 ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1893 if (ret != LDB_SUCCESS) {
1894 return ret;
1897 if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1898 talloc_free(dn);
1899 return LDB_ERR_OPERATIONS_ERROR;
1902 ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1903 talloc_free(dn);
1904 return ret;
1908 find a 'reference' DN that points at another object
1909 (eg. serverReference, rIDManagerReference etc)
1911 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1912 const char *attribute, struct ldb_dn **dn)
1914 const char *attrs[2];
1915 struct ldb_result *res;
1916 int ret;
1918 attrs[0] = attribute;
1919 attrs[1] = NULL;
1921 ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY|DSDB_SEARCH_SHOW_EXTENDED_DN, NULL);
1922 if (ret != LDB_SUCCESS) {
1923 ldb_asprintf_errstring(ldb, "Cannot find DN %s to get attribute %s for reference dn: %s",
1924 ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb));
1925 return ret;
1928 *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1929 if (!*dn) {
1930 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1931 ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1932 ldb_dn_get_linearized(base));
1933 } else {
1934 ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1935 ldb_dn_get_linearized(base));
1937 talloc_free(res);
1938 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1941 talloc_free(res);
1942 return LDB_SUCCESS;
1946 find if a DN (must have GUID component!) is our ntdsDsa
1948 int samdb_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *dn, bool *is_ntdsa)
1950 NTSTATUS status;
1951 struct GUID dn_guid;
1952 const struct GUID *our_ntds_guid;
1953 status = dsdb_get_extended_dn_guid(dn, &dn_guid, "GUID");
1954 if (!NT_STATUS_IS_OK(status)) {
1955 return LDB_ERR_OPERATIONS_ERROR;
1958 our_ntds_guid = samdb_ntds_objectGUID(ldb);
1959 if (!our_ntds_guid) {
1960 DEBUG(0, ("Failed to find our NTDS Settings GUID for comparison with %s - %s\n", ldb_dn_get_linearized(dn), ldb_errstring(ldb)));
1961 return LDB_ERR_OPERATIONS_ERROR;
1964 *is_ntdsa = GUID_equal(&dn_guid, our_ntds_guid);
1965 return LDB_SUCCESS;
1969 find a 'reference' DN that points at another object and indicate if it is our ntdsDsa
1971 int samdb_reference_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *base,
1972 const char *attribute, bool *is_ntdsa)
1974 int ret;
1975 struct ldb_dn *referenced_dn;
1976 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1977 if (tmp_ctx == NULL) {
1978 return LDB_ERR_OPERATIONS_ERROR;
1980 ret = samdb_reference_dn(ldb, tmp_ctx, base, attribute, &referenced_dn);
1981 if (ret != LDB_SUCCESS) {
1982 DEBUG(0, ("Failed to find object %s for attribute %s - %s\n", ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb)));
1983 return ret;
1986 ret = samdb_dn_is_our_ntdsa(ldb, referenced_dn, is_ntdsa);
1988 talloc_free(tmp_ctx);
1989 return ret;
1993 find our machine account via the serverReference attribute in the
1994 server DN
1996 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1998 struct ldb_dn *server_dn;
1999 int ret;
2001 server_dn = samdb_server_dn(ldb, mem_ctx);
2002 if (server_dn == NULL) {
2003 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
2006 ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
2007 talloc_free(server_dn);
2009 return ret;
2013 find the RID Manager$ DN via the rIDManagerReference attribute in the
2014 base DN
2016 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
2018 return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
2019 "rIDManagerReference", dn);
2023 find the RID Set DN via the rIDSetReferences attribute in our
2024 machine account DN
2026 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
2028 struct ldb_dn *server_ref_dn = NULL;
2029 int ret;
2031 ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
2032 if (ret != LDB_SUCCESS) {
2033 return ret;
2035 ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
2036 talloc_free(server_ref_dn);
2037 return ret;
2040 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
2042 const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
2043 mem_ctx));
2045 if (val == NULL) {
2046 return NULL;
2049 return (const char *) val->data;
2053 * Finds the client site by using the client's IP address.
2054 * The "subnet_name" returns the name of the subnet if parameter != NULL
2056 * Has a Windows-based fallback to provide the only site available, or an empty
2057 * string if there are multiple sites.
2059 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2060 const char *ip_address, char **subnet_name,
2061 bool fallback)
2063 const char *attrs[] = { "cn", "siteObject", NULL };
2064 struct ldb_dn *sites_container_dn = NULL;
2065 struct ldb_dn *subnets_dn = NULL;
2066 struct ldb_dn *sites_dn = NULL;
2067 struct ldb_result *res = NULL;
2068 const struct ldb_val *val = NULL;
2069 const char *site_name = NULL;
2070 const char *l_subnet_name = NULL;
2071 const char *allow_list[2] = { NULL, NULL };
2072 unsigned int i, count;
2073 int ret;
2076 * if we don't have a client ip e.g. ncalrpc
2077 * the server site is the client site
2079 if (ip_address == NULL) {
2080 return samdb_server_site_name(ldb, mem_ctx);
2083 sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
2084 if (sites_container_dn == NULL) {
2085 goto exit;
2088 subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
2089 if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
2090 goto exit;
2093 ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
2094 attrs, NULL);
2095 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2096 count = 0;
2097 } else if (ret != LDB_SUCCESS) {
2098 goto exit;
2099 } else {
2100 count = res->count;
2103 for (i = 0; i < count; i++) {
2104 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
2105 NULL);
2107 allow_list[0] = l_subnet_name;
2109 if (allow_access_nolog(NULL, allow_list, "", ip_address)) {
2110 sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
2111 res->msgs[i],
2112 "siteObject");
2113 if (sites_dn == NULL) {
2114 /* No reference, maybe another subnet matches */
2115 continue;
2118 /* "val" cannot be NULL here since "sites_dn" != NULL */
2119 val = ldb_dn_get_rdn_val(sites_dn);
2120 site_name = talloc_strdup(mem_ctx,
2121 (const char *) val->data);
2123 TALLOC_FREE(sites_dn);
2125 break;
2129 if (site_name == NULL && fallback) {
2130 /* This is the Windows Server fallback rule: when no subnet
2131 * exists and we have only one site available then use it (it
2132 * is for sure the same as our server site). If more sites do
2133 * exist then we don't know which one to use and set the site
2134 * name to "". */
2135 size_t cnt = 0;
2136 ret = dsdb_domain_count(
2137 ldb,
2138 &cnt,
2139 sites_container_dn,
2140 NULL,
2141 LDB_SCOPE_SUBTREE,
2142 "(objectClass=site)");
2143 if (ret != LDB_SUCCESS) {
2144 goto exit;
2146 if (cnt == 1) {
2147 site_name = samdb_server_site_name(ldb, mem_ctx);
2148 } else {
2149 site_name = talloc_strdup(mem_ctx, "");
2151 l_subnet_name = NULL;
2154 if (subnet_name != NULL) {
2155 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
2158 exit:
2159 TALLOC_FREE(sites_container_dn);
2160 TALLOC_FREE(subnets_dn);
2161 TALLOC_FREE(res);
2163 return site_name;
2167 work out if we are the PDC for the domain of the current open ldb
2169 bool samdb_is_pdc(struct ldb_context *ldb)
2171 int ret;
2172 bool is_pdc;
2174 ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner",
2175 &is_pdc);
2176 if (ret != LDB_SUCCESS) {
2177 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n",
2178 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
2179 ldb_errstring(ldb)));
2180 return false;
2183 return is_pdc;
2187 work out if we are a Global Catalog server for the domain of the current open ldb
2189 bool samdb_is_gc(struct ldb_context *ldb)
2191 uint32_t options = 0;
2192 if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
2193 return false;
2195 return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
2198 /* Find a domain object in the parents of a particular DN. */
2199 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2200 struct ldb_dn **parent_dn, const char **errstring)
2202 TALLOC_CTX *local_ctx;
2203 struct ldb_dn *sdn = dn;
2204 struct ldb_result *res = NULL;
2205 int ret = LDB_SUCCESS;
2206 const char *attrs[] = { NULL };
2208 local_ctx = talloc_new(mem_ctx);
2209 if (local_ctx == NULL) return ldb_oom(ldb);
2211 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
2212 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
2213 "(|(objectClass=domain)(objectClass=builtinDomain))");
2214 if (ret == LDB_SUCCESS) {
2215 if (res->count == 1) {
2216 break;
2218 } else {
2219 break;
2223 if (ret != LDB_SUCCESS) {
2224 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
2225 ldb_dn_get_linearized(dn),
2226 ldb_dn_get_linearized(sdn),
2227 ldb_errstring(ldb));
2228 talloc_free(local_ctx);
2229 return ret;
2231 /* should never be true with 'ret=LDB_SUCCESS', here to satisfy clang */
2232 if (res == NULL) {
2233 talloc_free(local_ctx);
2234 return LDB_ERR_OTHER;
2236 if (res->count != 1) {
2237 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
2238 ldb_dn_get_linearized(dn));
2239 DEBUG(0,(__location__ ": %s\n", *errstring));
2240 talloc_free(local_ctx);
2241 return LDB_ERR_CONSTRAINT_VIOLATION;
2244 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2245 talloc_free(local_ctx);
2246 return ret;
2249 static void pwd_timeout_debug(struct tevent_context *unused1,
2250 struct tevent_timer *unused2,
2251 struct timeval unused3,
2252 void *unused4)
2254 DEBUG(0, ("WARNING: check_password_complexity: password script "
2255 "took more than 1 second to run\n"));
2260 * Performs checks on a user password (plaintext UNIX format - attribute
2261 * "password"). The remaining parameters have to be extracted from the domain
2262 * object in the AD.
2264 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
2266 enum samr_ValidationStatus samdb_check_password(TALLOC_CTX *mem_ctx,
2267 struct loadparm_context *lp_ctx,
2268 const char *account_name,
2269 const char *user_principal_name,
2270 const char *full_name,
2271 const DATA_BLOB *utf8_blob,
2272 const uint32_t pwdProperties,
2273 const uint32_t minPwdLength)
2275 const struct loadparm_substitution *lp_sub =
2276 lpcfg_noop_substitution();
2277 char *password_script = NULL;
2278 const char *utf8_pw = (const char *)utf8_blob->data;
2281 * This looks strange because it is.
2283 * The check for the number of characters in the password
2284 * should clearly not be against the byte length, or else a
2285 * single UTF8 character would count for more than one.
2287 * We have chosen to use the number of 16-bit units that the
2288 * password encodes to as the measure of length. This is not
2289 * the same as the number of codepoints, if a password
2290 * contains a character beyond the Basic Multilingual Plane
2291 * (above 65535) it will count for more than one "character".
2294 size_t password_characters_roughly = strlen_m(utf8_pw);
2296 /* checks if the "minPwdLength" property is satisfied */
2297 if (minPwdLength > password_characters_roughly) {
2298 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2301 /* We might not be asked to check the password complexity */
2302 if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
2303 return SAMR_VALIDATION_STATUS_SUCCESS;
2306 if (password_characters_roughly == 0) {
2307 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2310 password_script = lpcfg_check_password_script(lp_ctx, lp_sub, mem_ctx);
2311 if (password_script != NULL && *password_script != '\0') {
2312 int check_ret = 0;
2313 int error = 0;
2314 ssize_t nwritten = 0;
2315 struct tevent_context *event_ctx = NULL;
2316 struct tevent_req *req = NULL;
2317 int cps_stdin = -1;
2318 const char * const cmd[4] = {
2319 "/bin/sh", "-c",
2320 password_script,
2321 NULL
2324 event_ctx = tevent_context_init(mem_ctx);
2325 if (event_ctx == NULL) {
2326 TALLOC_FREE(password_script);
2327 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2330 /* Gives a warning after 1 second, terminates after 10 */
2331 tevent_add_timer(event_ctx, event_ctx,
2332 tevent_timeval_current_ofs(1, 0),
2333 pwd_timeout_debug, NULL);
2335 check_ret = setenv("SAMBA_CPS_ACCOUNT_NAME", account_name, 1);
2336 if (check_ret != 0) {
2337 TALLOC_FREE(password_script);
2338 TALLOC_FREE(event_ctx);
2339 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2341 if (user_principal_name != NULL) {
2342 check_ret = setenv("SAMBA_CPS_USER_PRINCIPAL_NAME",
2343 user_principal_name, 1);
2344 } else {
2345 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2347 if (check_ret != 0) {
2348 TALLOC_FREE(password_script);
2349 TALLOC_FREE(event_ctx);
2350 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2352 if (full_name != NULL) {
2353 check_ret = setenv("SAMBA_CPS_FULL_NAME", full_name, 1);
2354 } else {
2355 unsetenv("SAMBA_CPS_FULL_NAME");
2357 if (check_ret != 0) {
2358 TALLOC_FREE(password_script);
2359 TALLOC_FREE(event_ctx);
2360 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2363 req = samba_runcmd_send(event_ctx, event_ctx,
2364 tevent_timeval_current_ofs(10, 0),
2365 100, 100, cmd, NULL);
2366 unsetenv("SAMBA_CPS_ACCOUNT_NAME");
2367 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2368 unsetenv("SAMBA_CPS_FULL_NAME");
2369 if (req == NULL) {
2370 TALLOC_FREE(password_script);
2371 TALLOC_FREE(event_ctx);
2372 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2375 cps_stdin = samba_runcmd_export_stdin(req);
2377 nwritten = write_data(
2378 cps_stdin, utf8_blob->data, utf8_blob->length);
2379 if (nwritten == -1) {
2380 close(cps_stdin);
2381 TALLOC_FREE(password_script);
2382 TALLOC_FREE(event_ctx);
2383 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2386 close(cps_stdin);
2388 if (!tevent_req_poll(req, event_ctx)) {
2389 TALLOC_FREE(password_script);
2390 TALLOC_FREE(event_ctx);
2391 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2394 check_ret = samba_runcmd_recv(req, &error);
2395 TALLOC_FREE(event_ctx);
2397 if (error == ETIMEDOUT) {
2398 DEBUG(0, ("check_password_complexity: check password script took too long!\n"));
2399 TALLOC_FREE(password_script);
2400 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2402 DEBUG(5,("check_password_complexity: check password script (%s) "
2403 "returned [%d]\n", password_script, check_ret));
2405 if (check_ret != 0) {
2406 DEBUG(1,("check_password_complexity: "
2407 "check password script said new password is not good "
2408 "enough!\n"));
2409 TALLOC_FREE(password_script);
2410 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2413 TALLOC_FREE(password_script);
2414 return SAMR_VALIDATION_STATUS_SUCCESS;
2417 TALLOC_FREE(password_script);
2420 * Here are the standard AD password quality rules, which we
2421 * run after the script.
2424 if (!check_password_quality(utf8_pw)) {
2425 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2428 return SAMR_VALIDATION_STATUS_SUCCESS;
2432 * Callback for "samdb_set_password" password change
2434 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2436 int ret;
2438 if (!ares) {
2439 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2442 if (ares->error != LDB_SUCCESS) {
2443 ret = ares->error;
2444 req->context = talloc_steal(req,
2445 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2446 talloc_free(ares);
2447 return ldb_request_done(req, ret);
2450 if (ares->type != LDB_REPLY_DONE) {
2451 talloc_free(ares);
2452 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2455 req->context = talloc_steal(req,
2456 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2457 talloc_free(ares);
2458 return ldb_request_done(req, LDB_SUCCESS);
2461 static NTSTATUS samdb_set_password_request(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2462 struct ldb_dn *user_dn,
2463 const DATA_BLOB *new_password,
2464 const struct samr_Password *ntNewHash,
2465 enum dsdb_password_checked old_password_checked,
2466 bool permit_interdomain_trust,
2467 struct ldb_request **req_out)
2469 struct ldb_message *msg;
2470 struct ldb_message_element *el;
2471 struct ldb_request *req;
2472 int ret;
2473 bool hash_values = false;
2475 *req_out = NULL;
2477 #define CHECK_RET(x) \
2478 if (x != LDB_SUCCESS) { \
2479 talloc_free(msg); \
2480 return NT_STATUS_NO_MEMORY; \
2483 msg = ldb_msg_new(mem_ctx);
2484 if (msg == NULL) {
2485 return NT_STATUS_NO_MEMORY;
2487 msg->dn = user_dn;
2488 if ((new_password != NULL)
2489 && ((ntNewHash == NULL))) {
2490 /* we have the password as plaintext UTF16 */
2491 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2492 new_password, NULL));
2493 el = ldb_msg_find_element(msg, "clearTextPassword");
2494 el->flags = LDB_FLAG_MOD_REPLACE;
2495 } else if ((new_password == NULL)
2496 && ((ntNewHash != NULL))) {
2497 /* we have a password as NT hash */
2498 if (ntNewHash != NULL) {
2499 CHECK_RET(samdb_msg_add_hash(ldb, msg, msg,
2500 "unicodePwd", ntNewHash));
2501 el = ldb_msg_find_element(msg, "unicodePwd");
2502 el->flags = LDB_FLAG_MOD_REPLACE;
2504 hash_values = true;
2505 } else {
2506 /* the password wasn't specified correctly */
2507 talloc_free(msg);
2508 return NT_STATUS_INVALID_PARAMETER;
2511 #undef CHECK_RET
2513 /* build modify request */
2514 ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2515 samdb_set_password_callback, NULL);
2516 if (ret != LDB_SUCCESS) {
2517 talloc_free(msg);
2518 return NT_STATUS_NO_MEMORY;
2521 /* Tie the lifetime of the message to that of the request. */
2522 talloc_steal(req, msg);
2524 /* A password change operation */
2525 if (old_password_checked == DSDB_PASSWORD_CHECKED_AND_CORRECT) {
2526 struct dsdb_control_password_change *change;
2528 change = talloc(req, struct dsdb_control_password_change);
2529 if (change == NULL) {
2530 talloc_free(req);
2531 return NT_STATUS_NO_MEMORY;
2534 change->old_password_checked = old_password_checked;
2536 ret = ldb_request_add_control(req,
2537 DSDB_CONTROL_PASSWORD_CHANGE_OLD_PW_CHECKED_OID,
2538 true, change);
2539 if (ret != LDB_SUCCESS) {
2540 talloc_free(req);
2541 return NT_STATUS_NO_MEMORY;
2544 if (hash_values) {
2545 ret = ldb_request_add_control(req,
2546 DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2547 true, NULL);
2548 if (ret != LDB_SUCCESS) {
2549 talloc_free(req);
2550 return NT_STATUS_NO_MEMORY;
2553 if (permit_interdomain_trust) {
2554 ret = ldb_request_add_control(req,
2555 DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
2556 false, NULL);
2557 if (ret != LDB_SUCCESS) {
2558 talloc_free(req);
2559 return NT_STATUS_NO_MEMORY;
2562 ret = ldb_request_add_control(req,
2563 DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2564 true, NULL);
2565 if (ret != LDB_SUCCESS) {
2566 talloc_free(req);
2567 return NT_STATUS_NO_MEMORY;
2570 *req_out = req;
2572 return NT_STATUS_OK;
2576 * Sets the user password using plaintext UTF16 (attribute "new_password") or NT
2577 * (attribute "ntNewHash") hash. Also pass the old LM and/or NT hash (attributes
2578 * "lmOldHash"/"ntOldHash") if it is a user change or not. The "rejectReason"
2579 * gives some more information if the change failed.
2581 * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2582 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2583 * NT_STATUS_ACCESS_DENIED, NT_STATUS_ACCOUNT_LOCKED_OUT, NT_STATUS_NO_MEMORY
2585 static NTSTATUS samdb_set_password_internal(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2586 struct ldb_dn *user_dn,
2587 const DATA_BLOB *new_password,
2588 const struct samr_Password *ntNewHash,
2589 enum dsdb_password_checked old_password_checked,
2590 enum samPwdChangeReason *reject_reason,
2591 struct samr_DomInfo1 **_dominfo,
2592 bool permit_interdomain_trust)
2594 struct ldb_request *req;
2595 struct dsdb_control_password_change_status *pwd_stat = NULL;
2596 int ret;
2597 NTSTATUS status = NT_STATUS_OK;
2599 status = samdb_set_password_request(ldb,
2600 mem_ctx,
2601 user_dn,
2602 new_password,
2603 ntNewHash,
2604 old_password_checked,
2605 permit_interdomain_trust,
2606 &req);
2607 if (!NT_STATUS_IS_OK(status)) {
2608 return status;
2611 ret = ldb_request(ldb, req);
2612 if (ret == LDB_SUCCESS) {
2613 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2616 if (req->context != NULL) {
2617 struct ldb_control *control = talloc_get_type_abort(req->context,
2618 struct ldb_control);
2619 pwd_stat = talloc_get_type_abort(control->data,
2620 struct dsdb_control_password_change_status);
2621 talloc_steal(mem_ctx, pwd_stat);
2624 talloc_free(req);
2626 /* Sets the domain info (if requested) */
2627 if (_dominfo != NULL) {
2628 struct samr_DomInfo1 *dominfo;
2630 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2631 if (dominfo == NULL) {
2632 return NT_STATUS_NO_MEMORY;
2635 if (pwd_stat != NULL) {
2636 dominfo->min_password_length = pwd_stat->domain_data.minPwdLength;
2637 dominfo->password_properties = pwd_stat->domain_data.pwdProperties;
2638 dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2639 dominfo->max_password_age = pwd_stat->domain_data.maxPwdAge;
2640 dominfo->min_password_age = pwd_stat->domain_data.minPwdAge;
2643 *_dominfo = dominfo;
2646 if (reject_reason != NULL) {
2647 if (pwd_stat != NULL) {
2648 *reject_reason = pwd_stat->reject_reason;
2649 } else {
2650 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2654 if (pwd_stat != NULL) {
2655 talloc_free(pwd_stat);
2658 if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2659 const char *errmsg = ldb_errstring(ldb);
2660 char *endptr = NULL;
2661 WERROR werr = WERR_GEN_FAILURE;
2662 status = NT_STATUS_UNSUCCESSFUL;
2663 if (errmsg != NULL) {
2664 werr = W_ERROR(strtol(errmsg, &endptr, 16));
2665 DBG_WARNING("%s\n", errmsg);
2667 if (endptr != errmsg) {
2668 if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2669 status = NT_STATUS_WRONG_PASSWORD;
2671 if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2672 status = NT_STATUS_PASSWORD_RESTRICTION;
2674 if (W_ERROR_EQUAL(werr, WERR_ACCOUNT_LOCKED_OUT)) {
2675 status = NT_STATUS_ACCOUNT_LOCKED_OUT;
2678 } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2679 /* don't let the caller know if an account doesn't exist */
2680 status = NT_STATUS_WRONG_PASSWORD;
2681 } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2682 status = NT_STATUS_ACCESS_DENIED;
2683 } else if (ret != LDB_SUCCESS) {
2684 DEBUG(1, ("Failed to set password on %s: %s\n",
2685 ldb_dn_get_linearized(user_dn),
2686 ldb_errstring(ldb)));
2687 status = NT_STATUS_UNSUCCESSFUL;
2690 return status;
2693 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2694 struct ldb_dn *user_dn,
2695 const DATA_BLOB *new_password,
2696 const struct samr_Password *ntNewHash,
2697 enum dsdb_password_checked old_password_checked,
2698 enum samPwdChangeReason *reject_reason,
2699 struct samr_DomInfo1 **_dominfo)
2701 return samdb_set_password_internal(ldb, mem_ctx,
2702 user_dn,
2703 new_password,
2704 ntNewHash,
2705 old_password_checked,
2706 reject_reason, _dominfo,
2707 false); /* reject trusts */
2711 * Sets the user password using plaintext UTF16 (attribute "new_password") or NT
2712 * (attribute "ntNewHash") hash. Also pass the old LM and/or NT hash (attributes
2713 * "lmOldHash"/"ntOldHash") if it is a user change or not. The "rejectReason"
2714 * gives some more information if the change failed.
2716 * This wrapper function for "samdb_set_password" takes a SID as input rather
2717 * than a user DN.
2719 * This call encapsulates a new LDB transaction for changing the password;
2720 * therefore the user hasn't to start a new one.
2722 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2723 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2724 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2725 * NT_STATUS_ACCESS_DENIED, NT_STATUS_ACCOUNT_LOCKED_OUT, NT_STATUS_NO_MEMORY
2726 * NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2728 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2729 const struct dom_sid *user_sid,
2730 const uint32_t *new_version, /* optional for trusts */
2731 const DATA_BLOB *new_password,
2732 const struct samr_Password *ntNewHash,
2733 enum dsdb_password_checked old_password_checked,
2734 enum samPwdChangeReason *reject_reason,
2735 struct samr_DomInfo1 **_dominfo)
2737 TALLOC_CTX *frame = talloc_stackframe();
2738 NTSTATUS nt_status;
2739 static const char * const attrs[] = {
2740 "userAccountControl",
2741 "sAMAccountName",
2742 NULL
2744 struct ldb_message *user_msg = NULL;
2745 int ret;
2746 uint32_t uac = 0;
2748 ret = ldb_transaction_start(ldb);
2749 if (ret != LDB_SUCCESS) {
2750 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2751 TALLOC_FREE(frame);
2752 return NT_STATUS_TRANSACTION_ABORTED;
2755 ret = dsdb_search_one(ldb, frame, &user_msg, ldb_get_default_basedn(ldb),
2756 LDB_SCOPE_SUBTREE, attrs, 0,
2757 "(&(objectSid=%s)(objectClass=user))",
2758 ldap_encode_ndr_dom_sid(frame, user_sid));
2759 if (ret != LDB_SUCCESS) {
2760 ldb_transaction_cancel(ldb);
2761 DEBUG(3, ("samdb_set_password_sid: SID[%s] not found in samdb %s - %s, "
2762 "returning NO_SUCH_USER\n",
2763 dom_sid_string(frame, user_sid),
2764 ldb_strerror(ret), ldb_errstring(ldb)));
2765 TALLOC_FREE(frame);
2766 return NT_STATUS_NO_SUCH_USER;
2769 uac = ldb_msg_find_attr_as_uint(user_msg, "userAccountControl", 0);
2770 if (!(uac & UF_ACCOUNT_TYPE_MASK)) {
2771 ldb_transaction_cancel(ldb);
2772 DEBUG(1, ("samdb_set_password_sid: invalid "
2773 "userAccountControl[0x%08X] for SID[%s] DN[%s], "
2774 "returning NO_SUCH_USER\n",
2775 (unsigned)uac, dom_sid_string(frame, user_sid),
2776 ldb_dn_get_linearized(user_msg->dn)));
2777 TALLOC_FREE(frame);
2778 return NT_STATUS_NO_SUCH_USER;
2781 if (uac & UF_INTERDOMAIN_TRUST_ACCOUNT) {
2782 static const char * const tdo_attrs[] = {
2783 "trustAuthIncoming",
2784 "trustDirection",
2785 NULL
2787 struct ldb_message *tdo_msg = NULL;
2788 const char *account_name = NULL;
2789 uint32_t trust_direction;
2790 uint32_t i;
2791 const struct ldb_val *old_val = NULL;
2792 struct trustAuthInOutBlob old_blob = {
2793 .count = 0,
2795 uint32_t old_version = 0;
2796 struct AuthenticationInformation *old_version_a = NULL;
2797 uint32_t _new_version = 0;
2798 struct trustAuthInOutBlob new_blob = {
2799 .count = 0,
2801 struct ldb_val new_val = {
2802 .length = 0,
2804 struct timeval tv = timeval_current();
2805 NTTIME now = timeval_to_nttime(&tv);
2806 enum ndr_err_code ndr_err;
2808 if (new_password == NULL && ntNewHash == NULL) {
2809 ldb_transaction_cancel(ldb);
2810 DEBUG(1, ("samdb_set_password_sid: "
2811 "no new password provided "
2812 "sAMAccountName for SID[%s] DN[%s], "
2813 "returning INVALID_PARAMETER\n",
2814 dom_sid_string(frame, user_sid),
2815 ldb_dn_get_linearized(user_msg->dn)));
2816 TALLOC_FREE(frame);
2817 return NT_STATUS_INVALID_PARAMETER;
2820 if (new_password != NULL && ntNewHash != NULL) {
2821 ldb_transaction_cancel(ldb);
2822 DEBUG(1, ("samdb_set_password_sid: "
2823 "two new passwords provided "
2824 "sAMAccountName for SID[%s] DN[%s], "
2825 "returning INVALID_PARAMETER\n",
2826 dom_sid_string(frame, user_sid),
2827 ldb_dn_get_linearized(user_msg->dn)));
2828 TALLOC_FREE(frame);
2829 return NT_STATUS_INVALID_PARAMETER;
2832 if (new_password != NULL && (new_password->length % 2)) {
2833 ldb_transaction_cancel(ldb);
2834 DEBUG(2, ("samdb_set_password_sid: "
2835 "invalid utf16 length (%zu) "
2836 "sAMAccountName for SID[%s] DN[%s], "
2837 "returning WRONG_PASSWORD\n",
2838 new_password->length,
2839 dom_sid_string(frame, user_sid),
2840 ldb_dn_get_linearized(user_msg->dn)));
2841 TALLOC_FREE(frame);
2842 return NT_STATUS_WRONG_PASSWORD;
2845 if (new_password != NULL && new_password->length >= 500) {
2846 ldb_transaction_cancel(ldb);
2847 DEBUG(2, ("samdb_set_password_sid: "
2848 "utf16 password too long (%zu) "
2849 "sAMAccountName for SID[%s] DN[%s], "
2850 "returning WRONG_PASSWORD\n",
2851 new_password->length,
2852 dom_sid_string(frame, user_sid),
2853 ldb_dn_get_linearized(user_msg->dn)));
2854 TALLOC_FREE(frame);
2855 return NT_STATUS_WRONG_PASSWORD;
2858 account_name = ldb_msg_find_attr_as_string(user_msg,
2859 "sAMAccountName", NULL);
2860 if (account_name == NULL) {
2861 ldb_transaction_cancel(ldb);
2862 DEBUG(1, ("samdb_set_password_sid: missing "
2863 "sAMAccountName for SID[%s] DN[%s], "
2864 "returning NO_SUCH_USER\n",
2865 dom_sid_string(frame, user_sid),
2866 ldb_dn_get_linearized(user_msg->dn)));
2867 TALLOC_FREE(frame);
2868 return NT_STATUS_NO_SUCH_USER;
2871 nt_status = dsdb_trust_search_tdo_by_type(ldb,
2872 SEC_CHAN_DOMAIN,
2873 account_name,
2874 tdo_attrs,
2875 frame, &tdo_msg);
2876 if (!NT_STATUS_IS_OK(nt_status)) {
2877 ldb_transaction_cancel(ldb);
2878 DEBUG(1, ("samdb_set_password_sid: dsdb_trust_search_tdo "
2879 "failed(%s) for sAMAccountName[%s] SID[%s] DN[%s], "
2880 "returning INTERNAL_DB_CORRUPTION\n",
2881 nt_errstr(nt_status), account_name,
2882 dom_sid_string(frame, user_sid),
2883 ldb_dn_get_linearized(user_msg->dn)));
2884 TALLOC_FREE(frame);
2885 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2888 trust_direction = ldb_msg_find_attr_as_int(tdo_msg,
2889 "trustDirection", 0);
2890 if (!(trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {
2891 ldb_transaction_cancel(ldb);
2892 DEBUG(1, ("samdb_set_password_sid: direction[0x%08X] is "
2893 "not inbound for sAMAccountName[%s] "
2894 "DN[%s] TDO[%s], "
2895 "returning INTERNAL_DB_CORRUPTION\n",
2896 (unsigned)trust_direction,
2897 account_name,
2898 ldb_dn_get_linearized(user_msg->dn),
2899 ldb_dn_get_linearized(tdo_msg->dn)));
2900 TALLOC_FREE(frame);
2901 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2904 old_val = ldb_msg_find_ldb_val(tdo_msg, "trustAuthIncoming");
2905 if (old_val != NULL) {
2906 ndr_err = ndr_pull_struct_blob(old_val, frame, &old_blob,
2907 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2908 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2909 ldb_transaction_cancel(ldb);
2910 DEBUG(1, ("samdb_set_password_sid: "
2911 "failed(%s) to parse "
2912 "trustAuthOutgoing sAMAccountName[%s] "
2913 "DN[%s] TDO[%s], "
2914 "returning INTERNAL_DB_CORRUPTION\n",
2915 ndr_map_error2string(ndr_err),
2916 account_name,
2917 ldb_dn_get_linearized(user_msg->dn),
2918 ldb_dn_get_linearized(tdo_msg->dn)));
2920 TALLOC_FREE(frame);
2921 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2925 for (i = old_blob.current.count; i > 0; i--) {
2926 struct AuthenticationInformation *a =
2927 &old_blob.current.array[i - 1];
2929 switch (a->AuthType) {
2930 case TRUST_AUTH_TYPE_NONE:
2931 if (i == old_blob.current.count) {
2933 * remove TRUST_AUTH_TYPE_NONE at the
2934 * end
2936 old_blob.current.count--;
2938 break;
2940 case TRUST_AUTH_TYPE_VERSION:
2941 old_version_a = a;
2942 old_version = a->AuthInfo.version.version;
2943 break;
2945 case TRUST_AUTH_TYPE_CLEAR:
2946 break;
2948 case TRUST_AUTH_TYPE_NT4OWF:
2949 break;
2953 if (new_version == NULL) {
2954 _new_version = 0;
2955 new_version = &_new_version;
2958 if (old_version_a != NULL && *new_version != (old_version + 1)) {
2959 old_version_a->LastUpdateTime = now;
2960 old_version_a->AuthType = TRUST_AUTH_TYPE_NONE;
2963 new_blob.count = MAX(old_blob.current.count, 2);
2964 new_blob.current.array = talloc_zero_array(frame,
2965 struct AuthenticationInformation,
2966 new_blob.count);
2967 if (new_blob.current.array == NULL) {
2968 ldb_transaction_cancel(ldb);
2969 TALLOC_FREE(frame);
2970 return NT_STATUS_NO_MEMORY;
2972 new_blob.previous.array = talloc_zero_array(frame,
2973 struct AuthenticationInformation,
2974 new_blob.count);
2975 if (new_blob.current.array == NULL) {
2976 ldb_transaction_cancel(ldb);
2977 TALLOC_FREE(frame);
2978 return NT_STATUS_NO_MEMORY;
2981 for (i = 0; i < old_blob.current.count; i++) {
2982 struct AuthenticationInformation *o =
2983 &old_blob.current.array[i];
2984 struct AuthenticationInformation *p =
2985 &new_blob.previous.array[i];
2987 *p = *o;
2988 new_blob.previous.count++;
2990 for (; i < new_blob.count; i++) {
2991 struct AuthenticationInformation *pi =
2992 &new_blob.previous.array[i];
2994 if (i == 0) {
2996 * new_blob.previous is still empty so
2997 * we'll do new_blob.previous = new_blob.current
2998 * below.
3000 break;
3003 pi->LastUpdateTime = now;
3004 pi->AuthType = TRUST_AUTH_TYPE_NONE;
3005 new_blob.previous.count++;
3008 for (i = 0; i < new_blob.count; i++) {
3009 struct AuthenticationInformation *ci =
3010 &new_blob.current.array[i];
3012 ci->LastUpdateTime = now;
3013 switch (i) {
3014 case 0:
3015 if (ntNewHash != NULL) {
3016 ci->AuthType = TRUST_AUTH_TYPE_NT4OWF;
3017 ci->AuthInfo.nt4owf.password = *ntNewHash;
3018 break;
3021 ci->AuthType = TRUST_AUTH_TYPE_CLEAR;
3022 ci->AuthInfo.clear.size = new_password->length;
3023 ci->AuthInfo.clear.password = new_password->data;
3024 break;
3025 case 1:
3026 ci->AuthType = TRUST_AUTH_TYPE_VERSION;
3027 ci->AuthInfo.version.version = *new_version;
3028 break;
3029 default:
3030 ci->AuthType = TRUST_AUTH_TYPE_NONE;
3031 break;
3034 new_blob.current.count++;
3037 if (new_blob.previous.count == 0) {
3038 TALLOC_FREE(new_blob.previous.array);
3039 new_blob.previous = new_blob.current;
3042 ndr_err = ndr_push_struct_blob(&new_val, frame, &new_blob,
3043 (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
3044 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3045 ldb_transaction_cancel(ldb);
3046 DEBUG(1, ("samdb_set_password_sid: "
3047 "failed(%s) to generate "
3048 "trustAuthOutgoing sAMAccountName[%s] "
3049 "DN[%s] TDO[%s], "
3050 "returning UNSUCCESSFUL\n",
3051 ndr_map_error2string(ndr_err),
3052 account_name,
3053 ldb_dn_get_linearized(user_msg->dn),
3054 ldb_dn_get_linearized(tdo_msg->dn)));
3055 TALLOC_FREE(frame);
3056 return NT_STATUS_UNSUCCESSFUL;
3059 tdo_msg->num_elements = 0;
3060 TALLOC_FREE(tdo_msg->elements);
3062 ret = ldb_msg_append_value(tdo_msg, "trustAuthIncoming",
3063 &new_val, LDB_FLAG_MOD_REPLACE);
3064 if (ret != LDB_SUCCESS) {
3065 ldb_transaction_cancel(ldb);
3066 TALLOC_FREE(frame);
3067 return NT_STATUS_NO_MEMORY;
3070 ret = ldb_modify(ldb, tdo_msg);
3071 if (ret != LDB_SUCCESS) {
3072 nt_status = dsdb_ldb_err_to_ntstatus(ret);
3073 ldb_transaction_cancel(ldb);
3074 DEBUG(1, ("samdb_set_password_sid: "
3075 "failed to replace "
3076 "trustAuthOutgoing sAMAccountName[%s] "
3077 "DN[%s] TDO[%s], "
3078 "%s - %s\n",
3079 account_name,
3080 ldb_dn_get_linearized(user_msg->dn),
3081 ldb_dn_get_linearized(tdo_msg->dn),
3082 nt_errstr(nt_status), ldb_errstring(ldb)));
3083 TALLOC_FREE(frame);
3084 return nt_status;
3088 nt_status = samdb_set_password_internal(ldb, mem_ctx,
3089 user_msg->dn,
3090 new_password,
3091 ntNewHash,
3092 old_password_checked,
3093 reject_reason, _dominfo,
3094 true); /* permit trusts */
3095 if (!NT_STATUS_IS_OK(nt_status)) {
3096 ldb_transaction_cancel(ldb);
3097 TALLOC_FREE(frame);
3098 return nt_status;
3101 ret = ldb_transaction_commit(ldb);
3102 if (ret != LDB_SUCCESS) {
3103 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
3104 ldb_dn_get_linearized(user_msg->dn),
3105 ldb_errstring(ldb)));
3106 TALLOC_FREE(frame);
3107 return NT_STATUS_TRANSACTION_ABORTED;
3110 TALLOC_FREE(frame);
3111 return NT_STATUS_OK;
3115 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
3116 struct dom_sid *sid, struct ldb_dn **ret_dn)
3118 struct ldb_message *msg;
3119 struct ldb_dn *basedn = NULL;
3120 char *sidstr;
3121 int ret;
3123 sidstr = dom_sid_string(mem_ctx, sid);
3124 NT_STATUS_HAVE_NO_MEMORY(sidstr);
3126 /* We might have to create a ForeignSecurityPrincipal, even if this user
3127 * is in our own domain */
3129 msg = ldb_msg_new(sidstr);
3130 if (msg == NULL) {
3131 talloc_free(sidstr);
3132 return NT_STATUS_NO_MEMORY;
3135 ret = dsdb_wellknown_dn(sam_ctx, sidstr,
3136 ldb_get_default_basedn(sam_ctx),
3137 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
3138 &basedn);
3139 if (ret != LDB_SUCCESS) {
3140 DEBUG(0, ("Failed to find DN for "
3141 "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
3142 talloc_free(sidstr);
3143 return NT_STATUS_INTERNAL_DB_CORRUPTION;
3146 /* add core elements to the ldb_message for the alias */
3147 msg->dn = basedn;
3148 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
3149 talloc_free(sidstr);
3150 return NT_STATUS_NO_MEMORY;
3153 ret = ldb_msg_add_string(msg, "objectClass",
3154 "foreignSecurityPrincipal");
3155 if (ret != LDB_SUCCESS) {
3156 talloc_free(sidstr);
3157 return NT_STATUS_NO_MEMORY;
3160 /* create the alias */
3161 ret = ldb_add(sam_ctx, msg);
3162 if (ret != LDB_SUCCESS) {
3163 DEBUG(0,("Failed to create foreignSecurityPrincipal "
3164 "record %s: %s\n",
3165 ldb_dn_get_linearized(msg->dn),
3166 ldb_errstring(sam_ctx)));
3167 talloc_free(sidstr);
3168 return NT_STATUS_INTERNAL_DB_CORRUPTION;
3171 *ret_dn = talloc_steal(mem_ctx, msg->dn);
3172 talloc_free(sidstr);
3174 return NT_STATUS_OK;
3179 Find the DN of a domain, assuming it to be a dotted.dns name
3182 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
3184 unsigned int i;
3185 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3186 const char *binary_encoded;
3187 const char * const *split_realm;
3188 struct ldb_dn *dn;
3190 if (!tmp_ctx) {
3191 return NULL;
3194 split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
3195 if (!split_realm) {
3196 talloc_free(tmp_ctx);
3197 return NULL;
3199 dn = ldb_dn_new(mem_ctx, ldb, NULL);
3200 for (i=0; split_realm[i]; i++) {
3201 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
3202 if (binary_encoded == NULL) {
3203 DEBUG(2, ("Failed to add dc= element to DN %s\n",
3204 ldb_dn_get_linearized(dn)));
3205 talloc_free(tmp_ctx);
3206 return NULL;
3208 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
3209 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
3210 binary_encoded, ldb_dn_get_linearized(dn)));
3211 talloc_free(tmp_ctx);
3212 return NULL;
3215 if (!ldb_dn_validate(dn)) {
3216 DEBUG(2, ("Failed to validated DN %s\n",
3217 ldb_dn_get_linearized(dn)));
3218 talloc_free(tmp_ctx);
3219 return NULL;
3221 talloc_free(tmp_ctx);
3222 return dn;
3227 Find the DNS equivalent of a DN, in dotted DNS form
3229 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
3231 int i, num_components = ldb_dn_get_comp_num(dn);
3232 char *dns_name = talloc_strdup(mem_ctx, "");
3233 if (dns_name == NULL) {
3234 return NULL;
3237 for (i=0; i<num_components; i++) {
3238 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
3239 char *s;
3240 if (v == NULL) {
3241 talloc_free(dns_name);
3242 return NULL;
3244 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
3245 (int)v->length, (int)v->length, (char *)v->data);
3246 if (s == NULL) {
3247 talloc_free(dns_name);
3248 return NULL;
3250 dns_name = s;
3253 /* remove the last '.' */
3254 if (dns_name[0] != 0) {
3255 dns_name[strlen(dns_name)-1] = 0;
3258 return dns_name;
3262 Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
3263 name is based on the forest DNS name
3265 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
3266 TALLOC_CTX *mem_ctx,
3267 const struct GUID *ntds_guid)
3269 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3270 const char *guid_str;
3271 struct ldb_dn *forest_dn;
3272 const char *dnsforest;
3273 char *ret;
3275 guid_str = GUID_string(tmp_ctx, ntds_guid);
3276 if (guid_str == NULL) {
3277 talloc_free(tmp_ctx);
3278 return NULL;
3280 forest_dn = ldb_get_root_basedn(samdb);
3281 if (forest_dn == NULL) {
3282 talloc_free(tmp_ctx);
3283 return NULL;
3285 dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
3286 if (dnsforest == NULL) {
3287 talloc_free(tmp_ctx);
3288 return NULL;
3290 ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
3291 talloc_free(tmp_ctx);
3292 return ret;
3297 Find the DN of a domain, be it the netbios or DNS name
3299 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
3300 const char *domain_name)
3302 const char * const domain_ref_attrs[] = {
3303 "ncName", NULL
3305 const char * const domain_ref2_attrs[] = {
3306 NULL
3308 struct ldb_result *res_domain_ref;
3309 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
3310 int ret_domain;
3312 if (escaped_domain == NULL) {
3313 return NULL;
3316 /* find the domain's DN */
3317 ret_domain = ldb_search(ldb, mem_ctx,
3318 &res_domain_ref,
3319 samdb_partitions_dn(ldb, mem_ctx),
3320 LDB_SCOPE_ONELEVEL,
3321 domain_ref_attrs,
3322 "(&(nETBIOSName=%s)(objectclass=crossRef))",
3323 escaped_domain);
3324 if (ret_domain != LDB_SUCCESS) {
3325 return NULL;
3328 if (res_domain_ref->count == 0) {
3329 ret_domain = ldb_search(ldb, mem_ctx,
3330 &res_domain_ref,
3331 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
3332 LDB_SCOPE_BASE,
3333 domain_ref2_attrs,
3334 "(objectclass=domain)");
3335 if (ret_domain != LDB_SUCCESS) {
3336 return NULL;
3339 if (res_domain_ref->count == 1) {
3340 return res_domain_ref->msgs[0]->dn;
3342 return NULL;
3345 if (res_domain_ref->count > 1) {
3346 DEBUG(0,("Found %d records matching domain [%s]\n",
3347 ret_domain, domain_name));
3348 return NULL;
3351 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
3357 use a GUID to find a DN
3359 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
3360 TALLOC_CTX *mem_ctx,
3361 const struct GUID *guid,
3362 uint32_t dsdb_flags,
3363 struct ldb_dn **dn)
3365 int ret;
3366 struct ldb_result *res;
3367 const char *attrs[] = { NULL };
3368 struct GUID_txt_buf buf;
3369 char *guid_str = GUID_buf_string(guid, &buf);
3371 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3372 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3373 DSDB_SEARCH_SHOW_EXTENDED_DN |
3374 DSDB_SEARCH_ONE_ONLY | dsdb_flags,
3375 "objectGUID=%s", guid_str);
3376 if (ret != LDB_SUCCESS) {
3377 return ret;
3380 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3381 talloc_free(res);
3383 return LDB_SUCCESS;
3387 use a DN to find a GUID with a given attribute name
3389 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
3390 struct ldb_dn *dn, const char *attribute,
3391 struct GUID *guid)
3393 int ret;
3394 struct ldb_result *res = NULL;
3395 const char *attrs[2];
3396 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3398 attrs[0] = attribute;
3399 attrs[1] = NULL;
3401 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3402 DSDB_SEARCH_SHOW_DELETED |
3403 DSDB_SEARCH_SHOW_RECYCLED);
3404 if (ret != LDB_SUCCESS) {
3405 talloc_free(tmp_ctx);
3406 return ret;
3408 /* satisfy clang */
3409 if (res == NULL) {
3410 talloc_free(tmp_ctx);
3411 return LDB_ERR_OTHER;
3413 if (res->count < 1) {
3414 talloc_free(tmp_ctx);
3415 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3417 *guid = samdb_result_guid(res->msgs[0], attribute);
3418 talloc_free(tmp_ctx);
3419 return LDB_SUCCESS;
3423 use a DN to find a GUID
3425 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
3426 struct ldb_dn *dn, struct GUID *guid)
3428 return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
3434 adds the given GUID to the given ldb_message. This value is added
3435 for the given attr_name (may be either "objectGUID" or "parentGUID").
3436 This function is used in processing 'add' requests.
3438 int dsdb_msg_add_guid(struct ldb_message *msg,
3439 struct GUID *guid,
3440 const char *attr_name)
3442 int ret;
3443 struct ldb_val v;
3444 NTSTATUS status;
3445 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
3447 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
3448 if (!NT_STATUS_IS_OK(status)) {
3449 ret = LDB_ERR_OPERATIONS_ERROR;
3450 goto done;
3453 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
3454 if (ret != LDB_SUCCESS) {
3455 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
3456 attr_name));
3457 goto done;
3460 ret = LDB_SUCCESS;
3462 done:
3463 talloc_free(tmp_ctx);
3464 return ret;
3470 use a DN to find a SID
3472 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
3473 struct ldb_dn *dn, struct dom_sid *sid)
3475 int ret;
3476 struct ldb_result *res = NULL;
3477 const char *attrs[] = { "objectSid", NULL };
3478 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3479 struct dom_sid *s;
3481 ZERO_STRUCTP(sid);
3483 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3484 DSDB_SEARCH_SHOW_DELETED |
3485 DSDB_SEARCH_SHOW_RECYCLED);
3486 if (ret != LDB_SUCCESS) {
3487 talloc_free(tmp_ctx);
3488 return ret;
3490 if (res == NULL) {
3491 talloc_free(tmp_ctx);
3492 return LDB_ERR_OTHER;
3494 if (res->count < 1) {
3495 talloc_free(tmp_ctx);
3496 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3498 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
3499 if (s == NULL) {
3500 talloc_free(tmp_ctx);
3501 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3503 *sid = *s;
3504 talloc_free(tmp_ctx);
3505 return LDB_SUCCESS;
3509 use a SID to find a DN
3511 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
3512 TALLOC_CTX *mem_ctx,
3513 struct dom_sid *sid, struct ldb_dn **dn)
3515 int ret;
3516 struct ldb_result *res;
3517 const char *attrs[] = { NULL };
3518 char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
3520 if (!sid_str) {
3521 return ldb_operr(ldb);
3524 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3525 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3526 DSDB_SEARCH_SHOW_EXTENDED_DN |
3527 DSDB_SEARCH_ONE_ONLY,
3528 "objectSid=%s", sid_str);
3529 talloc_free(sid_str);
3530 if (ret != LDB_SUCCESS) {
3531 return ret;
3534 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3535 talloc_free(res);
3537 return LDB_SUCCESS;
3541 load a repsFromTo blob list for a given partition GUID
3542 attr must be "repsFrom" or "repsTo"
3544 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3545 const char *attr, struct repsFromToBlob **r, uint32_t *count)
3547 const char *attrs[] = { attr, NULL };
3548 struct ldb_result *res = NULL;
3549 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3550 unsigned int i;
3551 struct ldb_message_element *el;
3552 int ret;
3554 *r = NULL;
3555 *count = 0;
3557 if (tmp_ctx == NULL) {
3558 return WERR_NOT_ENOUGH_MEMORY;
3561 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
3562 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3563 /* partition hasn't been replicated yet */
3564 talloc_free(tmp_ctx);
3565 return WERR_OK;
3567 if (ret != LDB_SUCCESS) {
3568 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
3569 talloc_free(tmp_ctx);
3570 return WERR_DS_DRA_INTERNAL_ERROR;
3573 /* satisfy clang */
3574 if (res == NULL) {
3575 talloc_free(tmp_ctx);
3576 return WERR_DS_DRA_INTERNAL_ERROR;
3578 el = ldb_msg_find_element(res->msgs[0], attr);
3579 if (el == NULL) {
3580 /* it's OK to be empty */
3581 talloc_free(tmp_ctx);
3582 return WERR_OK;
3585 *count = el->num_values;
3586 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
3587 if (*r == NULL) {
3588 talloc_free(tmp_ctx);
3589 return WERR_DS_DRA_INTERNAL_ERROR;
3592 for (i=0; i<(*count); i++) {
3593 enum ndr_err_code ndr_err;
3594 ndr_err = ndr_pull_struct_blob(&el->values[i],
3595 mem_ctx,
3596 &(*r)[i],
3597 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3598 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3599 talloc_free(tmp_ctx);
3600 return WERR_DS_DRA_INTERNAL_ERROR;
3604 talloc_free(tmp_ctx);
3606 return WERR_OK;
3610 save the repsFromTo blob list for a given partition GUID
3611 attr must be "repsFrom" or "repsTo"
3613 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3614 const char *attr, struct repsFromToBlob *r, uint32_t count)
3616 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3617 struct ldb_message *msg;
3618 struct ldb_message_element *el;
3619 unsigned int i;
3621 if (tmp_ctx == NULL) {
3622 goto failed;
3625 msg = ldb_msg_new(tmp_ctx);
3626 if (msg == NULL) {
3627 goto failed;
3629 msg->dn = dn;
3630 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
3631 goto failed;
3634 el->values = talloc_array(msg, struct ldb_val, count);
3635 if (!el->values) {
3636 goto failed;
3639 for (i=0; i<count; i++) {
3640 struct ldb_val v;
3641 enum ndr_err_code ndr_err;
3643 ndr_err = ndr_push_struct_blob(&v, tmp_ctx,
3644 &r[i],
3645 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3646 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3647 goto failed;
3650 el->num_values++;
3651 el->values[i] = v;
3654 if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
3655 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
3656 goto failed;
3659 talloc_free(tmp_ctx);
3661 return WERR_OK;
3663 failed:
3664 talloc_free(tmp_ctx);
3665 return WERR_DS_DRA_INTERNAL_ERROR;
3670 load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
3671 object for a partition
3673 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
3674 uint64_t *uSN, uint64_t *urgent_uSN)
3676 struct ldb_request *req;
3677 int ret;
3678 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3679 struct dsdb_control_current_partition *p_ctrl;
3680 struct ldb_result *res;
3682 if (tmp_ctx == NULL) {
3683 return ldb_oom(ldb);
3686 res = talloc_zero(tmp_ctx, struct ldb_result);
3687 if (!res) {
3688 talloc_free(tmp_ctx);
3689 return ldb_oom(ldb);
3692 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3693 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
3694 LDB_SCOPE_BASE,
3695 NULL, NULL,
3696 NULL,
3697 res, ldb_search_default_callback,
3698 NULL);
3699 if (ret != LDB_SUCCESS) {
3700 talloc_free(tmp_ctx);
3701 return ret;
3704 p_ctrl = talloc(req, struct dsdb_control_current_partition);
3705 if (p_ctrl == NULL) {
3706 talloc_free(tmp_ctx);
3707 return ldb_oom(ldb);
3709 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
3710 p_ctrl->dn = dn;
3712 ret = ldb_request_add_control(req,
3713 DSDB_CONTROL_CURRENT_PARTITION_OID,
3714 false, p_ctrl);
3715 if (ret != LDB_SUCCESS) {
3716 talloc_free(tmp_ctx);
3717 return ret;
3720 /* Run the new request */
3721 ret = ldb_request(ldb, req);
3723 if (ret == LDB_SUCCESS) {
3724 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3727 if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
3728 /* it hasn't been created yet, which means
3729 an implicit value of zero */
3730 *uSN = 0;
3731 talloc_free(tmp_ctx);
3732 return LDB_SUCCESS;
3735 if (ret != LDB_SUCCESS) {
3736 talloc_free(tmp_ctx);
3737 return ret;
3740 if (res->count < 1) {
3741 *uSN = 0;
3742 if (urgent_uSN) {
3743 *urgent_uSN = 0;
3745 } else {
3746 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
3747 if (urgent_uSN) {
3748 *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
3752 talloc_free(tmp_ctx);
3754 return LDB_SUCCESS;
3757 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
3758 const struct drsuapi_DsReplicaCursor2 *c2)
3760 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3763 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
3764 const struct drsuapi_DsReplicaCursor *c2)
3766 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3770 * Return the NTDS object for a GUID, confirming it is in the
3771 * configuration partition and a nTDSDSA object
3773 int samdb_get_ntds_obj_by_guid(TALLOC_CTX *mem_ctx,
3774 struct ldb_context *sam_ctx,
3775 const struct GUID *objectGUID,
3776 const char **attrs,
3777 struct ldb_message **msg)
3779 int ret;
3780 struct ldb_result *res;
3781 struct GUID_txt_buf guid_buf;
3782 char *guid_str = GUID_buf_string(objectGUID, &guid_buf);
3783 struct ldb_dn *config_dn = NULL;
3785 config_dn = ldb_get_config_basedn(sam_ctx);
3786 if (config_dn == NULL) {
3787 return ldb_operr(sam_ctx);
3790 ret = dsdb_search(sam_ctx,
3791 mem_ctx,
3792 &res,
3793 config_dn,
3794 LDB_SCOPE_SUBTREE,
3795 attrs,
3796 DSDB_SEARCH_ONE_ONLY,
3797 "(&(objectGUID=%s)(objectClass=nTDSDSA))",
3798 guid_str);
3799 if (ret != LDB_SUCCESS) {
3800 return ret;
3802 if (msg) {
3803 *msg = talloc_steal(mem_ctx, res->msgs[0]);
3805 TALLOC_FREE(res);
3806 return ret;
3811 see if a computer identified by its objectGUID is a RODC
3813 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
3815 /* 1) find the DN for this servers NTDSDSA object
3816 2) search for the msDS-isRODC attribute
3817 3) if not present then not a RODC
3818 4) if present and TRUE then is a RODC
3820 const char *attrs[] = { "msDS-isRODC", NULL };
3821 int ret;
3822 struct ldb_message *msg;
3823 TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
3825 if (tmp_ctx == NULL) {
3826 return ldb_oom(sam_ctx);
3829 ret = samdb_get_ntds_obj_by_guid(tmp_ctx,
3830 sam_ctx,
3831 objectGUID,
3832 attrs, &msg);
3834 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3835 *is_rodc = false;
3836 talloc_free(tmp_ctx);
3837 return LDB_SUCCESS;
3840 if (ret != LDB_SUCCESS) {
3841 DEBUG(1,("Failed to find our own NTDS Settings object by objectGUID=%s!\n",
3842 GUID_string(tmp_ctx, objectGUID)));
3843 *is_rodc = false;
3844 talloc_free(tmp_ctx);
3845 return ret;
3848 ret = ldb_msg_find_attr_as_bool(msg, "msDS-isRODC", 0);
3849 *is_rodc = (ret == 1);
3851 talloc_free(tmp_ctx);
3852 return LDB_SUCCESS;
3857 see if we are a RODC
3859 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
3861 const struct GUID *objectGUID;
3862 int ret;
3863 bool *cached;
3865 /* see if we have a cached copy */
3866 cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
3867 if (cached) {
3868 *am_rodc = *cached;
3869 return LDB_SUCCESS;
3872 objectGUID = samdb_ntds_objectGUID(sam_ctx);
3873 if (!objectGUID) {
3874 return ldb_operr(sam_ctx);
3877 ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
3878 if (ret != LDB_SUCCESS) {
3879 return ret;
3882 cached = talloc(sam_ctx, bool);
3883 if (cached == NULL) {
3884 return ldb_oom(sam_ctx);
3886 *cached = *am_rodc;
3888 ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
3889 if (ret != LDB_SUCCESS) {
3890 talloc_free(cached);
3891 return ldb_operr(sam_ctx);
3894 return LDB_SUCCESS;
3897 int samdb_dns_host_name(struct ldb_context *sam_ctx, const char **host_name)
3899 const char *_host_name = NULL;
3900 const char *attrs[] = { "dnsHostName", NULL };
3901 TALLOC_CTX *tmp_ctx = NULL;
3902 int ret;
3903 struct ldb_result *res = NULL;
3905 _host_name = (const char *)ldb_get_opaque(sam_ctx, "cache.dns_host_name");
3906 if (_host_name != NULL) {
3907 *host_name = _host_name;
3908 return LDB_SUCCESS;
3911 tmp_ctx = talloc_new(sam_ctx);
3912 if (tmp_ctx == NULL) {
3913 return ldb_oom(sam_ctx);
3916 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, NULL, attrs, 0);
3918 if (res == NULL || res->count != 1 || ret != LDB_SUCCESS) {
3919 DEBUG(0, ("Failed to get rootDSE for dnsHostName: %s\n",
3920 ldb_errstring(sam_ctx)));
3921 TALLOC_FREE(tmp_ctx);
3922 return ret;
3925 _host_name = ldb_msg_find_attr_as_string(res->msgs[0],
3926 "dnsHostName",
3927 NULL);
3928 if (_host_name == NULL) {
3929 DEBUG(0, ("Failed to get dnsHostName from rootDSE\n"));
3930 TALLOC_FREE(tmp_ctx);
3931 return LDB_ERR_OPERATIONS_ERROR;
3933 ret = ldb_set_opaque(sam_ctx, "cache.dns_host_name",
3934 discard_const_p(char *, _host_name));
3935 if (ret != LDB_SUCCESS) {
3936 TALLOC_FREE(tmp_ctx);
3937 return ldb_operr(sam_ctx);
3940 *host_name = talloc_steal(sam_ctx, _host_name);
3942 TALLOC_FREE(tmp_ctx);
3943 return LDB_SUCCESS;
3946 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3948 TALLOC_CTX *tmp_ctx;
3949 bool *cached;
3951 tmp_ctx = talloc_new(ldb);
3952 if (tmp_ctx == NULL) {
3953 goto failed;
3956 cached = talloc(tmp_ctx, bool);
3957 if (!cached) {
3958 goto failed;
3961 *cached = am_rodc;
3962 if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3963 goto failed;
3966 talloc_steal(ldb, cached);
3967 talloc_free(tmp_ctx);
3968 return true;
3970 failed:
3971 DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3972 talloc_free(tmp_ctx);
3973 return false;
3978 * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3979 * flags are DS_NTDSSETTINGS_OPT_*
3981 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3982 uint32_t *options)
3984 int rc;
3985 TALLOC_CTX *tmp_ctx;
3986 struct ldb_result *res;
3987 struct ldb_dn *site_dn;
3988 const char *attrs[] = { "options", NULL };
3990 tmp_ctx = talloc_new(ldb_ctx);
3991 if (tmp_ctx == NULL)
3992 goto failed;
3994 /* Retrieve the site dn for the ldb that we
3995 * have open. This is our local site.
3997 site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3998 if (site_dn == NULL)
3999 goto failed;
4001 /* Perform a one level (child) search from the local
4002 * site distinguished name. We're looking for the
4003 * "options" attribute within the nTDSSiteSettings
4004 * object
4006 rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
4007 LDB_SCOPE_ONELEVEL, attrs,
4008 "objectClass=nTDSSiteSettings");
4010 if (rc != LDB_SUCCESS || res->count != 1)
4011 goto failed;
4013 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
4015 talloc_free(tmp_ctx);
4017 return LDB_SUCCESS;
4019 failed:
4020 DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
4021 talloc_free(tmp_ctx);
4022 return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
4026 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
4028 flags are DS_NTDS_OPTION_*
4030 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
4032 TALLOC_CTX *tmp_ctx;
4033 const char *attrs[] = { "options", NULL };
4034 int ret;
4035 struct ldb_result *res;
4037 tmp_ctx = talloc_new(ldb);
4038 if (tmp_ctx == NULL) {
4039 goto failed;
4042 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
4043 if (ret != LDB_SUCCESS) {
4044 goto failed;
4047 if (res->count != 1) {
4048 goto failed;
4051 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
4053 talloc_free(tmp_ctx);
4055 return LDB_SUCCESS;
4057 failed:
4058 DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
4059 talloc_free(tmp_ctx);
4060 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4063 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
4065 const char *attrs[] = { "objectCategory", NULL };
4066 int ret;
4067 struct ldb_result *res;
4069 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
4070 if (ret != LDB_SUCCESS) {
4071 goto failed;
4074 if (res->count != 1) {
4075 goto failed;
4078 return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
4080 failed:
4081 DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
4082 return NULL;
4086 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
4087 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
4089 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
4091 char **tokens, *ret;
4092 size_t i;
4094 tokens = str_list_make(mem_ctx, cn, " -_");
4095 if (tokens == NULL || tokens[0] == NULL) {
4096 return NULL;
4099 /* "tolower()" and "toupper()" should also work properly on 0x00 */
4100 tokens[0][0] = tolower(tokens[0][0]);
4101 for (i = 1; tokens[i] != NULL; i++)
4102 tokens[i][0] = toupper(tokens[i][0]);
4104 ret = talloc_strdup(mem_ctx, tokens[0]);
4105 if (ret == NULL) {
4106 talloc_free(tokens);
4107 return NULL;
4109 for (i = 1; tokens[i] != NULL; i++) {
4110 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
4111 if (ret == NULL) {
4112 talloc_free(tokens);
4113 return NULL;
4117 talloc_free(tokens);
4119 return ret;
4123 * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
4125 int dsdb_functional_level(struct ldb_context *ldb)
4127 unsigned long long *domainFunctionality =
4128 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), unsigned long long);
4129 if (!domainFunctionality) {
4130 /* this is expected during initial provision */
4131 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
4132 return DS_DOMAIN_FUNCTION_2000;
4134 return *domainFunctionality;
4138 * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
4140 int dsdb_forest_functional_level(struct ldb_context *ldb)
4142 unsigned long long *forestFunctionality =
4143 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), unsigned long long);
4144 if (!forestFunctionality) {
4145 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
4146 return DS_DOMAIN_FUNCTION_2000;
4148 return *forestFunctionality;
4152 * This detects and returns the DC functional level (DS_DOMAIN_FUNCTION_*)
4154 int dsdb_dc_functional_level(struct ldb_context *ldb)
4156 unsigned long long *dcFunctionality =
4157 talloc_get_type(ldb_get_opaque(ldb, "domainControllerFunctionality"), unsigned long long);
4158 if (!dcFunctionality) {
4159 /* this is expected during initial provision */
4160 DEBUG(4,(__location__ ": WARNING: domainControllerFunctionality not setup\n"));
4161 return DS_DOMAIN_FUNCTION_2008_R2;
4163 return *dcFunctionality;
4166 const char *dsdb_dc_operatingSystemVersion(int dc_functional_level)
4168 const char *operatingSystemVersion = NULL;
4171 * While we are there also update
4172 * operatingSystem and operatingSystemVersion
4173 * as at least operatingSystemVersion is really
4174 * important for some clients/applications (like exchange).
4177 if (dc_functional_level >= DS_DOMAIN_FUNCTION_2016) {
4178 /* Pretend Windows 2016 */
4179 operatingSystemVersion = "10.0 (14393)";
4180 } else if (dc_functional_level >= DS_DOMAIN_FUNCTION_2012_R2) {
4181 /* Pretend Windows 2012 R2 */
4182 operatingSystemVersion = "6.3 (9600)";
4183 } else if (dc_functional_level >= DS_DOMAIN_FUNCTION_2012) {
4184 /* Pretend Windows 2012 */
4185 operatingSystemVersion = "6.2 (9200)";
4186 } else {
4187 /* Pretend Windows 2008 R2 */
4188 operatingSystemVersion = "6.1 (7600)";
4191 return operatingSystemVersion;
4194 int dsdb_check_and_update_fl(struct ldb_context *ldb_ctx, struct loadparm_context *lp_ctx)
4196 TALLOC_CTX *frame = talloc_stackframe();
4197 int ret;
4199 int db_dc_functional_level;
4200 int db_domain_functional_level;
4201 int db_forest_functional_level;
4202 int lp_dc_functional_level = lpcfg_ad_dc_functional_level(lp_ctx);
4203 bool am_rodc;
4204 struct ldb_message *msg = NULL;
4205 struct ldb_dn *dc_ntds_settings_dn = NULL;
4206 struct ldb_dn *dc_computer_dn = NULL;
4207 const char *operatingSystem = NULL;
4208 const char *operatingSystemVersion = NULL;
4210 db_dc_functional_level = dsdb_dc_functional_level(ldb_ctx);
4211 db_domain_functional_level = dsdb_functional_level(ldb_ctx);
4212 db_forest_functional_level = dsdb_forest_functional_level(ldb_ctx);
4214 if (lp_dc_functional_level < db_domain_functional_level) {
4215 DBG_ERR("Refusing to start as smb.conf 'ad dc functional level' maps to %d, "
4216 "which is less than the domain functional level of %d\n",
4217 lp_dc_functional_level, db_domain_functional_level);
4218 TALLOC_FREE(frame);
4219 return LDB_ERR_CONSTRAINT_VIOLATION;
4222 if (lp_dc_functional_level < db_forest_functional_level) {
4223 DBG_ERR("Refusing to start as smb.conf 'ad dc functional level' maps to %d, "
4224 "which is less than the forest functional level of %d\n",
4225 lp_dc_functional_level, db_forest_functional_level);
4226 TALLOC_FREE(frame);
4227 return LDB_ERR_CONSTRAINT_VIOLATION;
4230 /* Check if we need to update the DB */
4231 if (db_dc_functional_level == lp_dc_functional_level) {
4233 * Note that this early return means
4234 * we're not updating operatingSystem and
4235 * operatingSystemVersion.
4237 * But at least for now that's
4238 * exactly what we want.
4240 TALLOC_FREE(frame);
4241 return LDB_SUCCESS;
4244 /* Confirm we are not an RODC before we try a modify */
4245 ret = samdb_rodc(ldb_ctx, &am_rodc);
4246 if (ret != LDB_SUCCESS) {
4247 DBG_ERR("Failed to determine if this server is an RODC\n");
4248 TALLOC_FREE(frame);
4249 return ret;
4252 if (am_rodc) {
4253 DBG_WARNING("Unable to update DC's msDS-Behavior-Version "
4254 "(from %d to %d) and operatingSystem[Version] "
4255 "as we are an RODC\n",
4256 db_dc_functional_level, lp_dc_functional_level);
4257 TALLOC_FREE(frame);
4258 return LDB_SUCCESS;
4261 dc_ntds_settings_dn = samdb_ntds_settings_dn(ldb_ctx, frame);
4263 if (dc_ntds_settings_dn == NULL) {
4264 DBG_ERR("Failed to find own NTDS Settings DN\n");
4265 TALLOC_FREE(frame);
4266 return LDB_ERR_NO_SUCH_OBJECT;
4269 /* Now update our msDS-Behavior-Version */
4271 msg = ldb_msg_new(frame);
4272 if (msg == NULL) {
4273 DBG_ERR("Failed to allocate message to update msDS-Behavior-Version\n");
4274 TALLOC_FREE(frame);
4275 return LDB_ERR_OPERATIONS_ERROR;
4278 msg->dn = dc_ntds_settings_dn;
4280 ret = samdb_msg_add_int(ldb_ctx, frame, msg, "msDS-Behavior-Version", lp_dc_functional_level);
4281 if (ret != LDB_SUCCESS) {
4282 DBG_ERR("Failed to set new msDS-Behavior-Version on message\n");
4283 TALLOC_FREE(frame);
4284 return LDB_ERR_OPERATIONS_ERROR;
4287 ret = dsdb_replace(ldb_ctx, msg, 0);
4288 if (ret != LDB_SUCCESS) {
4289 DBG_ERR("Failed to update DB with new msDS-Behavior-Version on %s: %s\n",
4290 ldb_dn_get_linearized(dc_ntds_settings_dn),
4291 ldb_errstring(ldb_ctx));
4292 TALLOC_FREE(frame);
4293 return ret;
4297 * We have to update the opaque because this particular ldb_context
4298 * will not re-read the DB
4301 unsigned long long *val = talloc(ldb_ctx, unsigned long long);
4302 if (!val) {
4303 TALLOC_FREE(frame);
4304 return LDB_ERR_OPERATIONS_ERROR;
4306 *val = lp_dc_functional_level;
4307 ret = ldb_set_opaque(ldb_ctx,
4308 "domainControllerFunctionality", val);
4309 if (ret != LDB_SUCCESS) {
4310 DBG_ERR("Failed to re-set domainControllerFunctionality opaque\n");
4311 TALLOC_FREE(val);
4312 TALLOC_FREE(frame);
4313 return ret;
4318 * While we are there also update
4319 * operatingSystem and operatingSystemVersion
4320 * as at least operatingSystemVersion is really
4321 * important for some clients/applications (like exchange).
4324 operatingSystem = talloc_asprintf(frame, "Samba-%s",
4325 samba_version_string());
4326 if (operatingSystem == NULL) {
4327 TALLOC_FREE(frame);
4328 return ldb_oom(ldb_ctx);
4331 operatingSystemVersion = dsdb_dc_operatingSystemVersion(db_dc_functional_level);
4333 ret = samdb_server_reference_dn(ldb_ctx, frame, &dc_computer_dn);
4334 if (ret != LDB_SUCCESS) {
4335 DBG_ERR("Failed to get the dc_computer_dn: %s\n",
4336 ldb_errstring(ldb_ctx));
4337 TALLOC_FREE(frame);
4338 return ret;
4341 msg = ldb_msg_new(frame);
4342 if (msg == NULL) {
4343 DBG_ERR("Failed to allocate message to update msDS-Behavior-Version\n");
4344 TALLOC_FREE(frame);
4345 return LDB_ERR_OPERATIONS_ERROR;
4348 msg->dn = dc_computer_dn;
4350 ret = samdb_msg_add_addval(ldb_ctx, frame, msg,
4351 "operatingSystem",
4352 operatingSystem);
4353 if (ret != LDB_SUCCESS) {
4354 DBG_ERR("Failed to set new operatingSystem on message\n");
4355 TALLOC_FREE(frame);
4356 return ldb_operr(ldb_ctx);
4359 ret = samdb_msg_add_addval(ldb_ctx, frame, msg,
4360 "operatingSystemVersion",
4361 operatingSystemVersion);
4362 if (ret != LDB_SUCCESS) {
4363 DBG_ERR("Failed to set new operatingSystemVersion on message\n");
4364 TALLOC_FREE(frame);
4365 return ldb_operr(ldb_ctx);
4368 ret = dsdb_replace(ldb_ctx, msg, 0);
4369 if (ret != LDB_SUCCESS) {
4370 DBG_ERR("Failed to update DB with new operatingSystem[Version] on %s: %s\n",
4371 ldb_dn_get_linearized(dc_computer_dn),
4372 ldb_errstring(ldb_ctx));
4373 TALLOC_FREE(frame);
4374 return ret;
4377 TALLOC_FREE(frame);
4378 return LDB_SUCCESS;
4383 set a GUID in an extended DN structure
4385 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
4387 struct ldb_val v;
4388 NTSTATUS status;
4389 int ret;
4391 status = GUID_to_ndr_blob(guid, dn, &v);
4392 if (!NT_STATUS_IS_OK(status)) {
4393 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4396 ret = ldb_dn_set_extended_component(dn, component_name, &v);
4397 data_blob_free(&v);
4398 return ret;
4402 return a GUID from a extended DN structure
4404 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
4406 const struct ldb_val *v;
4408 v = ldb_dn_get_extended_component(dn, component_name);
4409 if (v == NULL) {
4410 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4413 return GUID_from_ndr_blob(v, guid);
4417 return a uint64_t from a extended DN structure
4419 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
4421 const struct ldb_val *v;
4422 int error = 0;
4424 v = ldb_dn_get_extended_component(dn, component_name);
4425 if (v == NULL) {
4426 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4429 /* Just check we don't allow the caller to fill our stack */
4430 if (v->length >= 64) {
4431 return NT_STATUS_INVALID_PARAMETER;
4432 } else {
4433 char s[v->length+1];
4434 memcpy(s, v->data, v->length);
4435 s[v->length] = 0;
4437 *val = smb_strtoull(s, NULL, 0, &error, SMB_STR_STANDARD);
4438 if (error != 0) {
4439 return NT_STATUS_INVALID_PARAMETER;
4442 return NT_STATUS_OK;
4446 return a NTTIME from a extended DN structure
4448 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
4450 return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
4454 return a uint32_t from a extended DN structure
4456 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
4458 const struct ldb_val *v;
4459 int error = 0;
4461 v = ldb_dn_get_extended_component(dn, component_name);
4462 if (v == NULL) {
4463 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4466 /* Just check we don't allow the caller to fill our stack */
4467 if (v->length >= 32) {
4468 return NT_STATUS_INVALID_PARAMETER;
4469 } else {
4470 char s[v->length + 1];
4471 memcpy(s, v->data, v->length);
4472 s[v->length] = 0;
4473 *val = smb_strtoul(s, NULL, 0, &error, SMB_STR_STANDARD);
4474 if (error != 0) {
4475 return NT_STATUS_INVALID_PARAMETER;
4479 return NT_STATUS_OK;
4483 return a dom_sid from a extended DN structure
4485 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
4487 const struct ldb_val *sid_blob;
4488 enum ndr_err_code ndr_err;
4490 sid_blob = ldb_dn_get_extended_component(dn, component_name);
4491 if (!sid_blob) {
4492 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4495 ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
4496 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
4497 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4498 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
4499 return status;
4502 return NT_STATUS_OK;
4507 return RMD_FLAGS directly from a ldb_dn
4508 returns 0 if not found
4510 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
4512 uint32_t rmd_flags = 0;
4513 NTSTATUS status = dsdb_get_extended_dn_uint32(dn, &rmd_flags,
4514 "RMD_FLAGS");
4515 if (NT_STATUS_IS_OK(status)) {
4516 return rmd_flags;
4518 return 0;
4522 return RMD_FLAGS directly from a ldb_val for a DN
4523 returns 0 if RMD_FLAGS is not found
4525 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
4527 const char *p;
4528 uint32_t flags;
4529 char *end;
4530 int error = 0;
4532 if (val->length < 13) {
4533 return 0;
4535 p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
4536 if (!p) {
4537 return 0;
4539 flags = smb_strtoul(p+11, &end, 10, &error, SMB_STR_STANDARD);
4540 if (!end || *end != '>' || error != 0) {
4541 /* it must end in a > */
4542 return 0;
4544 return flags;
4548 return true if a ldb_val containing a DN in storage form is deleted
4550 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
4552 return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
4556 return true if a ldb_val containing a DN in storage form is
4557 in the upgraded w2k3 linked attribute format
4559 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
4561 return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
4565 return a DN for a wellknown GUID
4567 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
4568 struct ldb_dn *nc_root, const char *wk_guid,
4569 struct ldb_dn **wkguid_dn)
4571 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4572 const char *attrs[] = { NULL };
4573 int ret;
4574 struct ldb_dn *dn;
4575 struct ldb_result *res = NULL;
4577 if (tmp_ctx == NULL) {
4578 return ldb_oom(samdb);
4581 /* construct the magic WKGUID DN */
4582 dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
4583 wk_guid, ldb_dn_get_linearized(nc_root));
4584 if (!wkguid_dn) {
4585 talloc_free(tmp_ctx);
4586 return ldb_operr(samdb);
4589 ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
4590 DSDB_SEARCH_SHOW_DELETED |
4591 DSDB_SEARCH_SHOW_RECYCLED);
4592 if (ret != LDB_SUCCESS) {
4593 talloc_free(tmp_ctx);
4594 return ret;
4596 /* fix clang warning */
4597 if (res == NULL){
4598 talloc_free(tmp_ctx);
4599 return LDB_ERR_OTHER;
4602 (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
4603 talloc_free(tmp_ctx);
4604 return LDB_SUCCESS;
4608 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
4610 return ldb_dn_compare(*dn1, *dn2);
4614 find a NC root given a DN within the NC by reading the rootDSE namingContexts
4616 static int dsdb_find_nc_root_string_based(struct ldb_context *samdb,
4617 TALLOC_CTX *mem_ctx,
4618 struct ldb_dn *dn,
4619 struct ldb_dn **nc_root)
4621 const char *root_attrs[] = { "namingContexts", NULL };
4622 TALLOC_CTX *tmp_ctx;
4623 int ret;
4624 struct ldb_message_element *el;
4625 struct ldb_result *root_res;
4626 unsigned int i;
4627 struct ldb_dn **nc_dns;
4629 tmp_ctx = talloc_new(samdb);
4630 if (tmp_ctx == NULL) {
4631 return ldb_oom(samdb);
4634 ret = ldb_search(samdb, tmp_ctx, &root_res,
4635 ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
4636 if (ret != LDB_SUCCESS || root_res->count == 0) {
4637 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
4638 talloc_free(tmp_ctx);
4639 return ret;
4642 el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
4643 if ((el == NULL) || (el->num_values < 3)) {
4644 struct ldb_message *tmp_msg;
4646 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list.\n"));
4648 /* This generates a temporary list of NCs in order to let the
4649 * provisioning work. */
4650 tmp_msg = ldb_msg_new(tmp_ctx);
4651 if (tmp_msg == NULL) {
4652 talloc_free(tmp_ctx);
4653 return ldb_oom(samdb);
4655 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4656 ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
4657 if (ret != LDB_SUCCESS) {
4658 talloc_free(tmp_ctx);
4659 return ret;
4661 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4662 ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
4663 if (ret != LDB_SUCCESS) {
4664 talloc_free(tmp_ctx);
4665 return ret;
4667 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4668 ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
4669 if (ret != LDB_SUCCESS) {
4670 talloc_free(tmp_ctx);
4671 return ret;
4673 el = &tmp_msg->elements[0];
4676 nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
4677 if (!nc_dns) {
4678 talloc_free(tmp_ctx);
4679 return ldb_oom(samdb);
4682 for (i=0; i<el->num_values; i++) {
4683 nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
4684 if (nc_dns[i] == NULL) {
4685 talloc_free(tmp_ctx);
4686 return ldb_operr(samdb);
4690 TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
4692 for (i=0; i<el->num_values; i++) {
4693 if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
4694 (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
4695 talloc_free(tmp_ctx);
4696 return LDB_SUCCESS;
4700 talloc_free(tmp_ctx);
4701 return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4704 struct dsdb_get_partition_and_dn {
4705 TALLOC_CTX *mem_ctx;
4706 unsigned int count;
4707 struct ldb_dn *dn;
4708 struct ldb_dn *partition_dn;
4709 bool want_partition_dn;
4712 static int dsdb_get_partition_and_dn(struct ldb_request *req,
4713 struct ldb_reply *ares)
4715 int ret;
4716 struct dsdb_get_partition_and_dn *context = req->context;
4717 struct ldb_control *partition_ctrl = NULL;
4718 struct dsdb_control_current_partition *partition = NULL;
4720 if (!ares) {
4721 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
4723 if (ares->error != LDB_SUCCESS
4724 && ares->error != LDB_ERR_NO_SUCH_OBJECT) {
4725 return ldb_request_done(req, ares->error);
4728 switch (ares->type) {
4729 case LDB_REPLY_ENTRY:
4730 if (context->count != 0) {
4731 return ldb_request_done(req,
4732 LDB_ERR_CONSTRAINT_VIOLATION);
4734 context->count++;
4736 context->dn = talloc_steal(context->mem_ctx,
4737 ares->message->dn);
4738 break;
4740 case LDB_REPLY_REFERRAL:
4741 talloc_free(ares);
4742 return ldb_request_done(req, LDB_SUCCESS);
4744 case LDB_REPLY_DONE:
4745 partition_ctrl
4746 = ldb_reply_get_control(ares,
4747 DSDB_CONTROL_CURRENT_PARTITION_OID);
4748 if (!context->want_partition_dn ||
4749 partition_ctrl == NULL) {
4750 ret = ares->error;
4751 talloc_free(ares);
4753 return ldb_request_done(req, ret);
4756 partition
4757 = talloc_get_type_abort(partition_ctrl->data,
4758 struct dsdb_control_current_partition);
4759 context->partition_dn
4760 = ldb_dn_copy(context->mem_ctx, partition->dn);
4761 if (context->partition_dn == NULL) {
4762 return ldb_request_done(req,
4763 LDB_ERR_OPERATIONS_ERROR);
4766 ret = ares->error;
4767 talloc_free(ares);
4769 return ldb_request_done(req, ret);
4772 talloc_free(ares);
4773 return LDB_SUCCESS;
4777 find a NC root given a DN within the NC
4779 int dsdb_normalise_dn_and_find_nc_root(struct ldb_context *samdb,
4780 TALLOC_CTX *mem_ctx,
4781 struct ldb_dn *dn,
4782 struct ldb_dn **normalised_dn,
4783 struct ldb_dn **nc_root)
4785 TALLOC_CTX *tmp_ctx;
4786 int ret;
4787 struct ldb_request *req;
4788 struct ldb_result *res;
4789 struct ldb_dn *search_dn = dn;
4790 static const char * attrs[] = { NULL };
4791 bool has_extended = ldb_dn_has_extended(dn);
4792 bool has_normal_components = ldb_dn_get_comp_num(dn) >= 1;
4793 struct dsdb_get_partition_and_dn context = {
4794 .mem_ctx = mem_ctx,
4795 .want_partition_dn = nc_root != NULL
4798 if (!has_extended && !has_normal_components) {
4799 return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT,
4800 "Request for NC root for rootDSE (\"\") denied.");
4803 tmp_ctx = talloc_new(samdb);
4804 if (tmp_ctx == NULL) {
4805 return ldb_oom(samdb);
4808 res = talloc_zero(tmp_ctx, struct ldb_result);
4809 if (res == NULL) {
4810 talloc_free(tmp_ctx);
4811 return ldb_oom(samdb);
4814 if (has_extended && has_normal_components) {
4815 bool minimise_ok;
4816 search_dn = ldb_dn_copy(tmp_ctx, dn);
4817 if (search_dn == NULL) {
4818 talloc_free(tmp_ctx);
4819 return ldb_oom(samdb);
4821 minimise_ok = ldb_dn_minimise(search_dn);
4822 if (!minimise_ok) {
4823 talloc_free(tmp_ctx);
4824 return ldb_operr(samdb);
4828 ret = ldb_build_search_req(&req, samdb, tmp_ctx,
4829 search_dn,
4830 LDB_SCOPE_BASE,
4831 NULL,
4832 attrs,
4833 NULL,
4834 &context,
4835 dsdb_get_partition_and_dn,
4836 NULL);
4837 if (ret != LDB_SUCCESS) {
4838 talloc_free(tmp_ctx);
4839 return ret;
4842 ret = ldb_request_add_control(req,
4843 DSDB_CONTROL_CURRENT_PARTITION_OID,
4844 false, NULL);
4845 if (ret != LDB_SUCCESS) {
4846 talloc_free(tmp_ctx);
4847 return ret;
4850 ret = dsdb_request_add_controls(req,
4851 DSDB_SEARCH_SHOW_RECYCLED|
4852 DSDB_SEARCH_SHOW_DELETED|
4853 DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT);
4854 if (ret != LDB_SUCCESS) {
4855 talloc_free(tmp_ctx);
4856 return ret;
4859 ret = ldb_request(samdb, req);
4860 if (ret == LDB_SUCCESS) {
4861 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4865 * This could be a new DN, not in the DB, which is OK. If we
4866 * don't need the normalised DN, we can continue.
4868 * We may be told the partition it would be in in the search
4869 * reply control, or if not we can do a string-based match.
4872 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
4873 if (normalised_dn != NULL) {
4874 talloc_free(tmp_ctx);
4875 return ret;
4877 ret = LDB_SUCCESS;
4878 ldb_reset_err_string(samdb);
4879 } else if (ret != LDB_SUCCESS) {
4880 talloc_free(tmp_ctx);
4881 return ret;
4884 if (normalised_dn != NULL) {
4885 if (context.count != 1) {
4886 /* No results */
4887 ldb_asprintf_errstring(samdb,
4888 "Request for NC root for %s failed to return any results.",
4889 ldb_dn_get_linearized(dn));
4890 talloc_free(tmp_ctx);
4891 return LDB_ERR_NO_SUCH_OBJECT;
4893 *normalised_dn = context.dn;
4897 * If the user did not need to find the nc_root,
4898 * we are done
4900 if (nc_root == NULL) {
4901 talloc_free(tmp_ctx);
4902 return ret;
4906 * When we are working locally, both for the case were
4907 * we find the DN, and the case where we fail, we get
4908 * back via controls the partition it was in or should
4909 * have been in, to return to the client
4911 if (context.partition_dn != NULL) {
4912 (*nc_root) = context.partition_dn;
4914 talloc_free(tmp_ctx);
4915 return ret;
4919 * This is a remote operation, which is a little harder as we
4920 * have a work out the nc_root from the list of NCs. If we did
4921 * at least resolve the DN to a string, get that now, it makes
4922 * the string-based match below possible for a GUID-based
4923 * input over remote LDAP.
4925 if (context.dn) {
4926 dn = context.dn;
4927 } else if (has_extended && !has_normal_components) {
4928 ldb_asprintf_errstring(samdb,
4929 "Cannot determine NC root "
4930 "for a not-found bare extended DN %s.",
4931 ldb_dn_get_extended_linearized(tmp_ctx, dn, 1));
4932 talloc_free(tmp_ctx);
4933 return LDB_ERR_NO_SUCH_OBJECT;
4937 * Either we are working against a remote LDAP
4938 * server or the object doesn't exist locally.
4940 * This means any GUID that was present in the DN
4941 * therefore could not be evaluated, so do a
4942 * string-based match instead.
4944 talloc_free(tmp_ctx);
4945 return dsdb_find_nc_root_string_based(samdb,
4946 mem_ctx,
4948 nc_root);
4952 find a NC root given a DN within the NC
4954 int dsdb_find_nc_root(struct ldb_context *samdb,
4955 TALLOC_CTX *mem_ctx,
4956 struct ldb_dn *dn,
4957 struct ldb_dn **nc_root)
4959 return dsdb_normalise_dn_and_find_nc_root(samdb,
4960 mem_ctx,
4962 NULL,
4963 nc_root);
4967 find the deleted objects DN for any object, by looking for the NC
4968 root, then looking up the wellknown GUID
4970 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
4971 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
4972 struct ldb_dn **do_dn)
4974 struct ldb_dn *nc_root;
4975 int ret;
4977 ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
4978 if (ret != LDB_SUCCESS) {
4979 return ret;
4982 ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
4983 talloc_free(nc_root);
4984 return ret;
4988 return the tombstoneLifetime, in days
4990 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
4992 struct ldb_dn *dn;
4993 dn = ldb_get_config_basedn(ldb);
4994 if (!dn) {
4995 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4997 dn = ldb_dn_copy(ldb, dn);
4998 if (!dn) {
4999 return ldb_operr(ldb);
5001 /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
5002 be a wellknown GUID for this */
5003 if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
5004 talloc_free(dn);
5005 return ldb_operr(ldb);
5008 *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
5009 talloc_free(dn);
5010 return LDB_SUCCESS;
5014 compare a ldb_val to a string case insensitively
5016 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
5018 size_t len = strlen(s);
5019 int ret;
5020 if (len > v->length) return 1;
5021 ret = strncasecmp(s, (const char *)v->data, v->length);
5022 if (ret != 0) return ret;
5023 if (v->length > len && v->data[len] != 0) {
5024 return -1;
5026 return 0;
5031 load the UDV for a partition in v2 format
5032 The list is returned sorted, and with our local cursor added
5034 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
5035 struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
5037 static const char *attrs[] = { "replUpToDateVector", NULL };
5038 struct ldb_result *r = NULL;
5039 const struct ldb_val *ouv_value;
5040 unsigned int i;
5041 int ret;
5042 uint64_t highest_usn = 0;
5043 const struct GUID *our_invocation_id;
5044 static const struct timeval tv1970;
5045 NTTIME nt1970 = timeval_to_nttime(&tv1970);
5047 ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
5048 if (ret != LDB_SUCCESS) {
5049 return ret;
5051 /* fix clang warning */
5052 if (r == NULL) {
5053 return LDB_ERR_OTHER;
5055 ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
5056 if (ouv_value) {
5057 enum ndr_err_code ndr_err;
5058 struct replUpToDateVectorBlob ouv;
5060 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
5061 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
5062 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
5063 talloc_free(r);
5064 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
5066 if (ouv.version != 2) {
5067 /* we always store as version 2, and
5068 * replUpToDateVector is not replicated
5070 talloc_free(r);
5071 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
5074 *count = ouv.ctr.ctr2.count;
5075 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
5076 } else {
5077 *count = 0;
5078 *cursors = NULL;
5081 talloc_free(r);
5083 our_invocation_id = samdb_ntds_invocation_id(samdb);
5084 if (!our_invocation_id) {
5085 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
5086 talloc_free(*cursors);
5087 return ldb_operr(samdb);
5090 ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
5091 if (ret != LDB_SUCCESS) {
5092 /* nothing to add - this can happen after a vampire */
5093 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
5094 return LDB_SUCCESS;
5097 for (i=0; i<*count; i++) {
5098 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
5099 (*cursors)[i].highest_usn = highest_usn;
5100 (*cursors)[i].last_sync_success = nt1970;
5101 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
5102 return LDB_SUCCESS;
5106 (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
5107 if (! *cursors) {
5108 return ldb_oom(samdb);
5111 (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
5112 (*cursors)[*count].highest_usn = highest_usn;
5113 (*cursors)[*count].last_sync_success = nt1970;
5114 (*count)++;
5116 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
5118 return LDB_SUCCESS;
5122 load the UDV for a partition in version 1 format
5123 The list is returned sorted, and with our local cursor added
5125 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
5126 struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
5128 struct drsuapi_DsReplicaCursor2 *v2 = NULL;
5129 uint32_t i;
5130 int ret;
5132 ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
5133 if (ret != LDB_SUCCESS) {
5134 return ret;
5137 if (*count == 0) {
5138 talloc_free(v2);
5139 *cursors = NULL;
5140 return LDB_SUCCESS;
5143 *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
5144 if (*cursors == NULL) {
5145 talloc_free(v2);
5146 return ldb_oom(samdb);
5149 for (i=0; i<*count; i++) {
5150 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
5151 (*cursors)[i].highest_usn = v2[i].highest_usn;
5153 talloc_free(v2);
5154 return LDB_SUCCESS;
5158 add a set of controls to a ldb_request structure based on a set of
5159 flags. See util.h for a list of available flags
5161 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
5163 int ret;
5164 if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
5165 struct ldb_search_options_control *options;
5166 /* Using the phantom root control allows us to search all partitions */
5167 options = talloc(req, struct ldb_search_options_control);
5168 if (options == NULL) {
5169 return LDB_ERR_OPERATIONS_ERROR;
5171 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
5173 ret = ldb_request_add_control(req,
5174 LDB_CONTROL_SEARCH_OPTIONS_OID,
5175 true, options);
5176 if (ret != LDB_SUCCESS) {
5177 return ret;
5181 if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
5182 ret = ldb_request_add_control(req,
5183 DSDB_CONTROL_NO_GLOBAL_CATALOG,
5184 false, NULL);
5185 if (ret != LDB_SUCCESS) {
5186 return ret;
5190 if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
5191 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
5192 if (ret != LDB_SUCCESS) {
5193 return ret;
5197 if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
5198 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
5199 if (ret != LDB_SUCCESS) {
5200 return ret;
5204 if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
5205 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
5206 if (ret != LDB_SUCCESS) {
5207 return ret;
5211 if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
5212 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
5213 if (!extended_ctrl) {
5214 return LDB_ERR_OPERATIONS_ERROR;
5216 extended_ctrl->type = 1;
5218 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
5219 if (ret != LDB_SUCCESS) {
5220 return ret;
5224 if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
5225 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
5226 if (ret != LDB_SUCCESS) {
5227 return ret;
5231 if (dsdb_flags & DSDB_MODIFY_RELAX) {
5232 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
5233 if (ret != LDB_SUCCESS) {
5234 return ret;
5238 if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
5239 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
5240 if (ret != LDB_SUCCESS) {
5241 return ret;
5245 if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
5246 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
5247 if (ret != LDB_SUCCESS) {
5248 return ret;
5252 if (dsdb_flags & DSDB_TREE_DELETE) {
5253 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
5254 if (ret != LDB_SUCCESS) {
5255 return ret;
5259 if (dsdb_flags & DSDB_PROVISION) {
5260 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
5261 if (ret != LDB_SUCCESS) {
5262 return ret;
5266 /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
5267 if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
5268 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
5269 if (ret != LDB_SUCCESS) {
5270 return ret;
5274 if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
5276 * This must not be critical, as it will only be
5277 * handled (and need to be handled) if the other
5278 * attributes in the request bring password_hash into
5279 * action
5281 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
5282 if (ret != LDB_SUCCESS) {
5283 return ret;
5287 if (dsdb_flags & DSDB_REPLMD_VANISH_LINKS) {
5288 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLMD_VANISH_LINKS, true, NULL);
5289 if (ret != LDB_SUCCESS) {
5290 return ret;
5294 if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
5295 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
5296 if (ret != LDB_SUCCESS) {
5297 return ret;
5301 if (dsdb_flags & DSDB_FLAG_REPLICATED_UPDATE) {
5302 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
5303 if (ret != LDB_SUCCESS) {
5304 return ret;
5308 if (dsdb_flags & DSDB_FLAG_FORCE_ALLOW_VALIDATED_DNS_HOSTNAME_SPN_WRITE) {
5309 ret = ldb_request_add_control(req, DSDB_CONTROL_FORCE_ALLOW_VALIDATED_DNS_HOSTNAME_SPN_WRITE_OID, true, NULL);
5310 if (ret != LDB_SUCCESS) {
5311 return ret;
5315 if (dsdb_flags & DSDB_MARK_REQ_UNTRUSTED) {
5316 ldb_req_mark_untrusted(req);
5319 return LDB_SUCCESS;
5323 returns true if a control with the specified "oid" exists
5325 bool dsdb_request_has_control(struct ldb_request *req, const char *oid)
5327 return (ldb_request_get_control(req, oid) != NULL);
5331 an add with a set of controls
5333 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
5334 uint32_t dsdb_flags)
5336 struct ldb_request *req;
5337 int ret;
5339 ret = ldb_build_add_req(&req, ldb, ldb,
5340 message,
5341 NULL,
5342 NULL,
5343 ldb_op_default_callback,
5344 NULL);
5346 if (ret != LDB_SUCCESS) return ret;
5348 ret = dsdb_request_add_controls(req, dsdb_flags);
5349 if (ret != LDB_SUCCESS) {
5350 talloc_free(req);
5351 return ret;
5354 ret = dsdb_autotransaction_request(ldb, req);
5356 talloc_free(req);
5357 return ret;
5361 a modify with a set of controls
5363 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
5364 uint32_t dsdb_flags)
5366 struct ldb_request *req;
5367 int ret;
5369 ret = ldb_build_mod_req(&req, ldb, ldb,
5370 message,
5371 NULL,
5372 NULL,
5373 ldb_op_default_callback,
5374 NULL);
5376 if (ret != LDB_SUCCESS) return ret;
5378 ret = dsdb_request_add_controls(req, dsdb_flags);
5379 if (ret != LDB_SUCCESS) {
5380 talloc_free(req);
5381 return ret;
5384 ret = dsdb_autotransaction_request(ldb, req);
5386 talloc_free(req);
5387 return ret;
5391 a delete with a set of flags
5393 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
5394 uint32_t dsdb_flags)
5396 struct ldb_request *req;
5397 int ret;
5399 ret = ldb_build_del_req(&req, ldb, ldb,
5401 NULL,
5402 NULL,
5403 ldb_op_default_callback,
5404 NULL);
5406 if (ret != LDB_SUCCESS) return ret;
5408 ret = dsdb_request_add_controls(req, dsdb_flags);
5409 if (ret != LDB_SUCCESS) {
5410 talloc_free(req);
5411 return ret;
5414 ret = dsdb_autotransaction_request(ldb, req);
5416 talloc_free(req);
5417 return ret;
5421 like dsdb_modify() but set all the element flags to
5422 LDB_FLAG_MOD_REPLACE
5424 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
5426 unsigned int i;
5428 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5429 for (i=0;i<msg->num_elements;i++) {
5430 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5433 return dsdb_modify(ldb, msg, dsdb_flags);
5436 const char *dsdb_search_scope_as_string(enum ldb_scope scope)
5438 const char *scope_str;
5440 switch (scope) {
5441 case LDB_SCOPE_BASE:
5442 scope_str = "BASE";
5443 break;
5444 case LDB_SCOPE_ONELEVEL:
5445 scope_str = "ONE";
5446 break;
5447 case LDB_SCOPE_SUBTREE:
5448 scope_str = "SUB";
5449 break;
5450 default:
5451 scope_str = "<Invalid scope>";
5452 break;
5454 return scope_str;
5459 search for attrs on one DN, allowing for dsdb_flags controls
5461 int dsdb_search_dn(struct ldb_context *ldb,
5462 TALLOC_CTX *mem_ctx,
5463 struct ldb_result **_result,
5464 struct ldb_dn *basedn,
5465 const char * const *attrs,
5466 uint32_t dsdb_flags)
5468 int ret;
5469 struct ldb_request *req;
5470 struct ldb_result *res;
5471 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5473 if (tmp_ctx == NULL) {
5474 return ldb_oom(ldb);
5477 res = talloc_zero(tmp_ctx, struct ldb_result);
5478 if (!res) {
5479 talloc_free(tmp_ctx);
5480 return ldb_oom(ldb);
5483 ret = ldb_build_search_req(&req, ldb, res,
5484 basedn,
5485 LDB_SCOPE_BASE,
5486 NULL,
5487 attrs,
5488 NULL,
5489 res,
5490 ldb_search_default_callback,
5491 NULL);
5492 if (ret != LDB_SUCCESS) {
5493 talloc_free(tmp_ctx);
5494 return ret;
5497 ret = dsdb_request_add_controls(req, dsdb_flags);
5498 if (ret != LDB_SUCCESS) {
5499 talloc_free(tmp_ctx);
5500 return ret;
5503 ret = ldb_request(ldb, req);
5504 if (ret == LDB_SUCCESS) {
5505 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
5508 talloc_free(req);
5509 if (ret != LDB_SUCCESS) {
5510 DBG_INFO("flags=0x%08x %s -> %s (%s)\n",
5511 dsdb_flags,
5512 basedn?ldb_dn_get_extended_linearized(tmp_ctx,
5513 basedn,
5514 1):"NULL",
5515 ldb_errstring(ldb), ldb_strerror(ret));
5516 talloc_free(tmp_ctx);
5517 return ret;
5520 DBG_DEBUG("flags=0x%08x %s -> %d\n",
5521 dsdb_flags,
5522 basedn?ldb_dn_get_extended_linearized(tmp_ctx,
5523 basedn,
5524 1):"NULL",
5525 res->count);
5527 *_result = talloc_steal(mem_ctx, res);
5529 talloc_free(tmp_ctx);
5530 return LDB_SUCCESS;
5534 search for attrs on one DN, by the GUID of the DN, allowing for
5535 dsdb_flags controls
5537 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
5538 TALLOC_CTX *mem_ctx,
5539 struct ldb_result **_result,
5540 const struct GUID *guid,
5541 const char * const *attrs,
5542 uint32_t dsdb_flags)
5544 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5545 struct ldb_dn *dn;
5546 int ret;
5548 if (tmp_ctx == NULL) {
5549 return ldb_oom(ldb);
5552 dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
5553 if (dn == NULL) {
5554 talloc_free(tmp_ctx);
5555 return ldb_oom(ldb);
5558 ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
5559 talloc_free(tmp_ctx);
5560 return ret;
5563 NTSTATUS gmsa_system_password_update_request(
5564 struct ldb_context *ldb,
5565 TALLOC_CTX *mem_ctx,
5566 struct ldb_dn *dn,
5567 const uint8_t
5568 password_buf[static const GMSA_PASSWORD_NULL_TERMINATED_LEN],
5569 struct ldb_request **request_out)
5571 DATA_BLOB password_blob = {};
5572 struct ldb_request *request = NULL;
5573 NTSTATUS status;
5574 int ret;
5576 dn = ldb_dn_copy(mem_ctx, dn);
5577 if (dn == NULL) {
5578 return NT_STATUS_INTERNAL_ERROR;
5581 /* Make a copy of the password. */
5582 password_blob = data_blob_talloc(mem_ctx,
5583 password_buf,
5584 GMSA_PASSWORD_LEN);
5585 if (password_blob.data == NULL) {
5586 talloc_free(dn);
5587 return NT_STATUS_NO_MEMORY;
5590 status = samdb_set_password_request(ldb,
5591 mem_ctx,
5593 &password_blob,
5594 NULL,
5595 DSDB_PASSWORD_RESET,
5596 false /* reject trusts */,
5597 &request);
5598 if (!NT_STATUS_IS_OK(status)) {
5599 data_blob_free(&password_blob);
5600 talloc_free(dn);
5601 return status;
5604 /* Tie the lifetime of the password to that of the request. */
5605 talloc_steal(request, password_blob.data);
5607 /* Tie the lifetime of the DN to that of the request. */
5608 talloc_steal(request, dn);
5610 /* Make sure the password update happens as System. */
5611 ret = dsdb_request_add_controls(request, DSDB_FLAG_AS_SYSTEM);
5612 if (ret) {
5613 talloc_free(request);
5614 return NT_STATUS_NO_MEMORY;
5617 *request_out = request;
5618 return NT_STATUS_OK;
5622 general search with dsdb_flags for controls
5624 int dsdb_search(struct ldb_context *ldb,
5625 TALLOC_CTX *mem_ctx,
5626 struct ldb_result **_result,
5627 struct ldb_dn *basedn,
5628 enum ldb_scope scope,
5629 const char * const *attrs,
5630 uint32_t dsdb_flags,
5631 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
5633 int ret;
5634 struct ldb_request *req;
5635 struct ldb_result *res;
5636 va_list ap;
5637 char *expression = NULL;
5638 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5639 int tries;
5640 const int max_tries = 5;
5642 /* cross-partitions searches with a basedn break multi-domain support */
5643 SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
5645 if (tmp_ctx == NULL) {
5646 return ldb_oom(ldb);
5649 res = talloc(tmp_ctx, struct ldb_result);
5650 if (!res) {
5651 talloc_free(tmp_ctx);
5652 return ldb_oom(ldb);
5655 if (exp_fmt) {
5656 va_start(ap, exp_fmt);
5657 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
5658 va_end(ap);
5660 if (!expression) {
5661 talloc_free(tmp_ctx);
5662 return ldb_oom(ldb);
5666 for (tries = 0; tries < max_tries; ++tries) {
5667 bool retry = true;
5669 *res = (struct ldb_result){};
5671 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
5672 basedn,
5673 scope,
5674 expression,
5675 attrs,
5676 NULL,
5677 res,
5678 ldb_search_default_callback,
5679 NULL);
5680 if (ret != LDB_SUCCESS) {
5681 talloc_free(tmp_ctx);
5682 return ret;
5685 ret = dsdb_request_add_controls(req, dsdb_flags);
5686 if (ret != LDB_SUCCESS) {
5687 talloc_free(tmp_ctx);
5688 ldb_reset_err_string(ldb);
5689 return ret;
5692 ret = ldb_request(ldb, req);
5693 if (ret == LDB_SUCCESS) {
5694 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
5697 if (ret != LDB_SUCCESS) {
5698 DBG_INFO("%s flags=0x%08x %s %s -> %s (%s)\n",
5699 dsdb_search_scope_as_string(scope),
5700 dsdb_flags,
5701 basedn?ldb_dn_get_extended_linearized(tmp_ctx,
5702 basedn,
5703 1):"NULL",
5704 expression?expression:"NULL",
5705 ldb_errstring(ldb), ldb_strerror(ret));
5706 talloc_free(tmp_ctx);
5707 return ret;
5710 if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
5711 if (res->count == 0) {
5712 DBG_INFO("%s SEARCH_ONE_ONLY flags=0x%08x %s %s -> %u results\n",
5713 dsdb_search_scope_as_string(scope),
5714 dsdb_flags,
5715 basedn?ldb_dn_get_extended_linearized(tmp_ctx,
5716 basedn,
5717 1):"NULL",
5718 expression?expression:"NULL", res->count);
5719 talloc_free(tmp_ctx);
5720 ldb_reset_err_string(ldb);
5721 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
5723 if (res->count != 1) {
5724 DBG_INFO("%s SEARCH_ONE_ONLY flags=0x%08x %s %s -> %u (expected 1) results\n",
5725 dsdb_search_scope_as_string(scope),
5726 dsdb_flags,
5727 basedn?ldb_dn_get_extended_linearized(tmp_ctx,
5728 basedn,
5729 1):"NULL",
5730 expression?expression:"NULL", res->count);
5731 talloc_free(tmp_ctx);
5732 ldb_reset_err_string(ldb);
5733 return LDB_ERR_CONSTRAINT_VIOLATION;
5737 if (!(dsdb_flags & DSDB_SEARCH_UPDATE_MANAGED_PASSWORDS)) {
5738 break;
5742 * If we’re searching for passwords, we must account for the
5743 * possibility that one or more of the accounts are Group
5744 * Managed Service Accounts with out‐of‐date keys. In such a
5745 * case, we must derive the new password(s), update the keys,
5746 * and perform the search again to get the updated results.
5748 * The following attributes are necessary in order for this to
5749 * work properly:
5751 * • msDS-ManagedPasswordId
5752 * • msDS-ManagedPasswordInterval
5753 * • objectClass
5754 * • objectSid
5755 * • whenCreated
5758 ret = dsdb_update_gmsa_keys(ldb, tmp_ctx, res, &retry);
5759 if (ret) {
5760 talloc_free(tmp_ctx);
5761 return ret;
5763 if (!retry) {
5764 break;
5767 if (tries == max_tries) {
5768 talloc_free(tmp_ctx);
5769 ldb_reset_err_string(ldb);
5770 return ldb_operr(ldb);
5773 *_result = talloc_steal(mem_ctx, res);
5775 DBG_DEBUG("%s flags=0x%08x %s %s -> %d\n",
5776 dsdb_search_scope_as_string(scope),
5777 dsdb_flags,
5778 basedn?ldb_dn_get_extended_linearized(tmp_ctx,
5779 basedn,
5780 1):"NULL",
5781 expression?expression:"NULL",
5782 res->count);
5783 talloc_free(tmp_ctx);
5784 return LDB_SUCCESS;
5789 general search with dsdb_flags for controls
5790 returns exactly 1 record or an error
5792 int dsdb_search_one(struct ldb_context *ldb,
5793 TALLOC_CTX *mem_ctx,
5794 struct ldb_message **msg,
5795 struct ldb_dn *basedn,
5796 enum ldb_scope scope,
5797 const char * const *attrs,
5798 uint32_t dsdb_flags,
5799 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
5801 int ret;
5802 struct ldb_result *res;
5803 va_list ap;
5804 char *expression = NULL;
5805 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5807 if (tmp_ctx == NULL) {
5808 return ldb_oom(ldb);
5811 dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
5813 res = talloc_zero(tmp_ctx, struct ldb_result);
5814 if (!res) {
5815 talloc_free(tmp_ctx);
5816 return ldb_oom(ldb);
5819 if (exp_fmt) {
5820 va_start(ap, exp_fmt);
5821 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
5822 va_end(ap);
5824 if (!expression) {
5825 talloc_free(tmp_ctx);
5826 return ldb_oom(ldb);
5828 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
5829 dsdb_flags, "%s", expression);
5830 } else {
5831 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
5832 dsdb_flags, NULL);
5835 if (ret != LDB_SUCCESS) {
5836 talloc_free(tmp_ctx);
5837 return ret;
5840 *msg = talloc_steal(mem_ctx, res->msgs[0]);
5841 talloc_free(tmp_ctx);
5843 return LDB_SUCCESS;
5846 /* returns back the forest DNS name */
5847 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
5849 const char *forest_name = ldb_dn_canonical_string(mem_ctx,
5850 ldb_get_root_basedn(ldb));
5851 char *p;
5853 if (forest_name == NULL) {
5854 return NULL;
5857 p = strchr(forest_name, '/');
5858 if (p) {
5859 *p = '\0';
5862 return forest_name;
5865 /* returns back the default domain DNS name */
5866 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
5868 const char *domain_name = ldb_dn_canonical_string(mem_ctx,
5869 ldb_get_default_basedn(ldb));
5870 char *p;
5872 if (domain_name == NULL) {
5873 return NULL;
5876 p = strchr(domain_name, '/');
5877 if (p) {
5878 *p = '\0';
5881 return domain_name;
5885 validate that an DSA GUID belongs to the specified user sid.
5886 The user SID must be a domain controller account (either RODC or
5887 RWDC)
5889 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
5890 const struct GUID *dsa_guid,
5891 const struct dom_sid *sid)
5893 /* strategy:
5894 - find DN of record with the DSA GUID in the
5895 configuration partition (objectGUID)
5896 - remove "NTDS Settings" component from DN
5897 - do a base search on that DN for serverReference with
5898 extended-dn enabled
5899 - extract objectSid from resulting serverReference
5900 attribute
5901 - check this sid matches the sid argument
5903 struct ldb_dn *config_dn;
5904 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5905 struct ldb_message *msg;
5906 const char *attrs1[] = { NULL };
5907 const char *attrs2[] = { "serverReference", NULL };
5908 int ret;
5909 struct ldb_dn *dn, *account_dn;
5910 struct dom_sid sid2;
5911 NTSTATUS status;
5913 if (tmp_ctx == NULL) {
5914 return ldb_oom(ldb);
5917 config_dn = ldb_get_config_basedn(ldb);
5919 ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
5920 attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
5921 if (ret != LDB_SUCCESS) {
5922 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
5923 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
5924 talloc_free(tmp_ctx);
5925 return ldb_operr(ldb);
5927 dn = msg->dn;
5929 if (!ldb_dn_remove_child_components(dn, 1)) {
5930 talloc_free(tmp_ctx);
5931 return ldb_operr(ldb);
5934 ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
5935 attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
5936 "(objectClass=server)");
5937 if (ret != LDB_SUCCESS) {
5938 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
5939 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
5940 talloc_free(tmp_ctx);
5941 return ldb_operr(ldb);
5944 account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
5945 if (account_dn == NULL) {
5946 DEBUG(1,(__location__ ": Failed to find account dn "
5947 "(serverReference) for %s, parent of DSA with "
5948 "objectGUID %s, sid %s\n",
5949 ldb_dn_get_linearized(msg->dn),
5950 GUID_string(tmp_ctx, dsa_guid),
5951 dom_sid_string(tmp_ctx, sid)));
5952 talloc_free(tmp_ctx);
5953 return ldb_operr(ldb);
5956 status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
5957 if (!NT_STATUS_IS_OK(status)) {
5958 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
5959 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
5960 talloc_free(tmp_ctx);
5961 return ldb_operr(ldb);
5964 if (!dom_sid_equal(sid, &sid2)) {
5965 /* someone is trying to spoof another account */
5966 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
5967 GUID_string(tmp_ctx, dsa_guid),
5968 dom_sid_string(tmp_ctx, sid),
5969 dom_sid_string(tmp_ctx, &sid2)));
5970 talloc_free(tmp_ctx);
5971 return ldb_operr(ldb);
5974 talloc_free(tmp_ctx);
5975 return LDB_SUCCESS;
5978 static const char * const secret_attributes[] = {
5979 DSDB_SECRET_ATTRIBUTES,
5980 NULL
5984 check if the attribute belongs to the RODC filtered attribute set
5985 Note that attributes that are in the filtered attribute set are the
5986 ones that _are_ always sent to a RODC
5988 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
5990 /* they never get secret attributes */
5991 if (ldb_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
5992 return false;
5995 /* they do get non-secret critical attributes */
5996 if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
5997 return true;
6000 /* they do get non-secret attributes marked as being in the FAS */
6001 if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
6002 return true;
6005 /* other attributes are denied */
6006 return false;
6009 /* return fsmo role dn and role owner dn for a particular role*/
6010 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
6011 struct ldb_context *ldb,
6012 uint32_t role,
6013 struct ldb_dn **fsmo_role_dn,
6014 struct ldb_dn **role_owner_dn)
6016 int ret;
6017 switch (role) {
6018 case DREPL_NAMING_MASTER:
6019 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
6020 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
6021 if (ret != LDB_SUCCESS) {
6022 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s\n",
6023 ldb_errstring(ldb)));
6024 talloc_free(tmp_ctx);
6025 return WERR_DS_DRA_INTERNAL_ERROR;
6027 break;
6028 case DREPL_INFRASTRUCTURE_MASTER:
6029 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
6030 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
6031 if (ret != LDB_SUCCESS) {
6032 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s\n",
6033 ldb_errstring(ldb)));
6034 talloc_free(tmp_ctx);
6035 return WERR_DS_DRA_INTERNAL_ERROR;
6037 break;
6038 case DREPL_RID_MASTER:
6039 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
6040 if (ret != LDB_SUCCESS) {
6041 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s\n", ldb_errstring(ldb)));
6042 talloc_free(tmp_ctx);
6043 return WERR_DS_DRA_INTERNAL_ERROR;
6046 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
6047 if (ret != LDB_SUCCESS) {
6048 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s\n",
6049 ldb_errstring(ldb)));
6050 talloc_free(tmp_ctx);
6051 return WERR_DS_DRA_INTERNAL_ERROR;
6053 break;
6054 case DREPL_SCHEMA_MASTER:
6055 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
6056 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
6057 if (ret != LDB_SUCCESS) {
6058 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s\n",
6059 ldb_errstring(ldb)));
6060 talloc_free(tmp_ctx);
6061 return WERR_DS_DRA_INTERNAL_ERROR;
6063 break;
6064 case DREPL_PDC_MASTER:
6065 *fsmo_role_dn = ldb_get_default_basedn(ldb);
6066 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
6067 if (ret != LDB_SUCCESS) {
6068 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s\n",
6069 ldb_errstring(ldb)));
6070 talloc_free(tmp_ctx);
6071 return WERR_DS_DRA_INTERNAL_ERROR;
6073 break;
6074 default:
6075 return WERR_DS_DRA_INTERNAL_ERROR;
6077 return WERR_OK;
6080 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
6081 TALLOC_CTX *mem_ctx,
6082 struct ldb_dn *server_dn)
6084 int ldb_ret;
6085 struct ldb_result *res = NULL;
6086 const char * const attrs[] = { "dNSHostName", NULL};
6088 ldb_ret = ldb_search(ldb, mem_ctx, &res,
6089 server_dn,
6090 LDB_SCOPE_BASE,
6091 attrs, NULL);
6092 if (ldb_ret != LDB_SUCCESS) {
6093 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s\n",
6094 ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
6095 return NULL;
6098 return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
6102 returns true if an attribute is in the filter,
6103 false otherwise, provided that attribute value is provided with the expression
6105 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
6106 const char *attr)
6108 unsigned int i;
6109 switch (tree->operation) {
6110 case LDB_OP_AND:
6111 case LDB_OP_OR:
6112 for (i=0;i<tree->u.list.num_elements;i++) {
6113 if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
6114 attr))
6115 return true;
6117 return false;
6118 case LDB_OP_NOT:
6119 return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
6120 case LDB_OP_EQUALITY:
6121 if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
6122 return true;
6124 return false;
6125 case LDB_OP_GREATER:
6126 case LDB_OP_LESS:
6127 case LDB_OP_APPROX:
6128 if (ldb_attr_cmp(tree->u.comparison.attr, attr) == 0) {
6129 return true;
6131 return false;
6132 case LDB_OP_SUBSTRING:
6133 if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
6134 return true;
6136 return false;
6137 case LDB_OP_PRESENT:
6138 /* (attrname=*) is not filtered out */
6139 return false;
6140 case LDB_OP_EXTENDED:
6141 if (tree->u.extended.attr &&
6142 ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
6143 return true;
6145 return false;
6147 return false;
6150 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
6151 const char *location, const char *func,
6152 const char *reason)
6154 if (reason == NULL) {
6155 reason = win_errstr(werr);
6157 ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
6158 W_ERROR_V(werr), reason, location, func);
6159 return ldb_ecode;
6163 map an ldb error code to an approximate NTSTATUS code
6165 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
6167 switch (err) {
6168 case LDB_SUCCESS:
6169 return NT_STATUS_OK;
6171 case LDB_ERR_PROTOCOL_ERROR:
6172 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
6174 case LDB_ERR_TIME_LIMIT_EXCEEDED:
6175 return NT_STATUS_IO_TIMEOUT;
6177 case LDB_ERR_SIZE_LIMIT_EXCEEDED:
6178 return NT_STATUS_BUFFER_TOO_SMALL;
6180 case LDB_ERR_COMPARE_FALSE:
6181 case LDB_ERR_COMPARE_TRUE:
6182 return NT_STATUS_REVISION_MISMATCH;
6184 case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
6185 return NT_STATUS_NOT_SUPPORTED;
6187 case LDB_ERR_STRONG_AUTH_REQUIRED:
6188 case LDB_ERR_CONFIDENTIALITY_REQUIRED:
6189 case LDB_ERR_SASL_BIND_IN_PROGRESS:
6190 case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
6191 case LDB_ERR_INVALID_CREDENTIALS:
6192 case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
6193 case LDB_ERR_UNWILLING_TO_PERFORM:
6194 return NT_STATUS_ACCESS_DENIED;
6196 case LDB_ERR_NO_SUCH_OBJECT:
6197 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
6199 case LDB_ERR_REFERRAL:
6200 case LDB_ERR_NO_SUCH_ATTRIBUTE:
6201 return NT_STATUS_NOT_FOUND;
6203 case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
6204 return NT_STATUS_NOT_SUPPORTED;
6206 case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
6207 return NT_STATUS_BUFFER_TOO_SMALL;
6209 case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
6210 case LDB_ERR_INAPPROPRIATE_MATCHING:
6211 case LDB_ERR_CONSTRAINT_VIOLATION:
6212 case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
6213 case LDB_ERR_INVALID_DN_SYNTAX:
6214 case LDB_ERR_NAMING_VIOLATION:
6215 case LDB_ERR_OBJECT_CLASS_VIOLATION:
6216 case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
6217 case LDB_ERR_NOT_ALLOWED_ON_RDN:
6218 return NT_STATUS_INVALID_PARAMETER;
6220 case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
6221 case LDB_ERR_ENTRY_ALREADY_EXISTS:
6222 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
6224 case LDB_ERR_BUSY:
6225 return NT_STATUS_NETWORK_BUSY;
6227 case LDB_ERR_ALIAS_PROBLEM:
6228 case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
6229 case LDB_ERR_UNAVAILABLE:
6230 case LDB_ERR_LOOP_DETECT:
6231 case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
6232 case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
6233 case LDB_ERR_OTHER:
6234 case LDB_ERR_OPERATIONS_ERROR:
6235 break;
6237 return NT_STATUS_UNSUCCESSFUL;
6242 create a new naming context that will hold a partial replica
6244 int dsdb_create_partial_replica_NC(struct ldb_context *ldb, struct ldb_dn *dn)
6246 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
6247 struct ldb_message *msg;
6248 int ret;
6250 if (tmp_ctx == NULL) {
6251 return ldb_oom(ldb);
6254 msg = ldb_msg_new(tmp_ctx);
6255 if (msg == NULL) {
6256 talloc_free(tmp_ctx);
6257 return ldb_oom(ldb);
6260 msg->dn = dn;
6261 ret = ldb_msg_add_string(msg, "objectClass", "top");
6262 if (ret != LDB_SUCCESS) {
6263 talloc_free(tmp_ctx);
6264 return ldb_oom(ldb);
6267 /* [MS-DRSR] implies that we should only add the 'top'
6268 * objectclass, but that would cause lots of problems with our
6269 * objectclass code as top is not structural, so we add
6270 * 'domainDNS' as well to keep things sane. We're expecting
6271 * this new NC to be of objectclass domainDNS after
6272 * replication anyway
6274 ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
6275 if (ret != LDB_SUCCESS) {
6276 talloc_free(tmp_ctx);
6277 return ldb_oom(ldb);
6280 ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
6281 INSTANCE_TYPE_IS_NC_HEAD|
6282 INSTANCE_TYPE_NC_ABOVE|
6283 INSTANCE_TYPE_UNINSTANT);
6284 if (ret != LDB_SUCCESS) {
6285 talloc_free(tmp_ctx);
6286 return ldb_oom(ldb);
6289 ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
6290 if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
6291 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
6292 ldb_dn_get_linearized(dn),
6293 ldb_errstring(ldb), ldb_strerror(ret)));
6294 talloc_free(tmp_ctx);
6295 return ret;
6298 DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
6300 talloc_free(tmp_ctx);
6301 return LDB_SUCCESS;
6305 * Return the effective badPwdCount
6307 * This requires that the user_msg have (if present):
6308 * - badPasswordTime
6309 * - badPwdCount
6311 * This also requires that the domain_msg have (if present):
6312 * - lockOutObservationWindow
6314 int dsdb_effective_badPwdCount(const struct ldb_message *user_msg,
6315 int64_t lockOutObservationWindow,
6316 NTTIME now)
6318 int64_t badPasswordTime;
6319 badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
6321 if (badPasswordTime - lockOutObservationWindow >= now) {
6322 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
6323 } else {
6324 return 0;
6329 * Returns a user's PSO, or NULL if none was found
6331 static struct ldb_result *lookup_user_pso(struct ldb_context *sam_ldb,
6332 TALLOC_CTX *mem_ctx,
6333 const struct ldb_message *user_msg,
6334 const char * const *attrs)
6336 struct ldb_result *res = NULL;
6337 struct ldb_dn *pso_dn = NULL;
6338 int ret;
6340 /* if the user has a PSO that applies, then use the PSO's setting */
6341 pso_dn = ldb_msg_find_attr_as_dn(sam_ldb, mem_ctx, user_msg,
6342 "msDS-ResultantPSO");
6344 if (pso_dn != NULL) {
6346 ret = dsdb_search_dn(sam_ldb, mem_ctx, &res, pso_dn, attrs, 0);
6347 if (ret != LDB_SUCCESS) {
6350 * log the error. The caller should fallback to using
6351 * the default domain password settings
6353 DBG_ERR("Error retrieving msDS-ResultantPSO %s for %s\n",
6354 ldb_dn_get_linearized(pso_dn),
6355 ldb_dn_get_linearized(user_msg->dn));
6357 talloc_free(pso_dn);
6359 return res;
6363 * Return the msDS-LockoutObservationWindow for a user message
6365 * This requires that the user_msg have (if present):
6366 * - msDS-ResultantPSO
6368 int64_t samdb_result_msds_LockoutObservationWindow(
6369 struct ldb_context *sam_ldb,
6370 TALLOC_CTX *mem_ctx,
6371 struct ldb_dn *domain_dn,
6372 const struct ldb_message *user_msg)
6374 int64_t lockOutObservationWindow;
6375 struct ldb_result *res = NULL;
6376 const char *attrs[] = { "msDS-LockoutObservationWindow",
6377 NULL };
6378 if (domain_dn == NULL) {
6379 smb_panic("domain dn is NULL");
6381 res = lookup_user_pso(sam_ldb, mem_ctx, user_msg, attrs);
6383 if (res != NULL) {
6384 lockOutObservationWindow =
6385 ldb_msg_find_attr_as_int64(res->msgs[0],
6386 "msDS-LockoutObservationWindow",
6387 DEFAULT_OBSERVATION_WINDOW);
6388 talloc_free(res);
6389 } else {
6391 /* no PSO was found, lookup the default domain setting */
6392 lockOutObservationWindow =
6393 samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
6394 "lockOutObservationWindow", NULL);
6396 return lockOutObservationWindow;
6400 * Return the effective badPwdCount
6402 * This requires that the user_msg have (if present):
6403 * - badPasswordTime
6404 * - badPwdCount
6405 * - msDS-ResultantPSO
6407 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
6408 TALLOC_CTX *mem_ctx,
6409 struct ldb_dn *domain_dn,
6410 const struct ldb_message *user_msg)
6412 struct timeval tv_now = timeval_current();
6413 NTTIME now = timeval_to_nttime(&tv_now);
6414 int64_t lockOutObservationWindow =
6415 samdb_result_msds_LockoutObservationWindow(
6416 sam_ldb, mem_ctx, domain_dn, user_msg);
6417 return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
6421 * Returns the lockoutThreshold that applies. If a PSO is specified, then that
6422 * setting is used over the domain defaults
6424 static int64_t get_lockout_threshold(struct ldb_message *domain_msg,
6425 struct ldb_message *pso_msg)
6427 if (pso_msg != NULL) {
6428 return ldb_msg_find_attr_as_int(pso_msg,
6429 "msDS-LockoutThreshold", 0);
6430 } else {
6431 return ldb_msg_find_attr_as_int(domain_msg,
6432 "lockoutThreshold", 0);
6437 * Returns the lockOutObservationWindow that applies. If a PSO is specified,
6438 * then that setting is used over the domain defaults
6440 static int64_t get_lockout_observation_window(struct ldb_message *domain_msg,
6441 struct ldb_message *pso_msg)
6443 if (pso_msg != NULL) {
6444 return ldb_msg_find_attr_as_int64(pso_msg,
6445 "msDS-LockoutObservationWindow",
6446 DEFAULT_OBSERVATION_WINDOW);
6447 } else {
6448 return ldb_msg_find_attr_as_int64(domain_msg,
6449 "lockOutObservationWindow",
6450 DEFAULT_OBSERVATION_WINDOW);
6455 * Prepare an update to the badPwdCount and associated attributes.
6457 * This requires that the user_msg have (if present):
6458 * - objectSid
6459 * - badPasswordTime
6460 * - badPwdCount
6462 * This also requires that the domain_msg have (if present):
6463 * - pwdProperties
6464 * - lockoutThreshold
6465 * - lockOutObservationWindow
6467 * This also requires that the pso_msg have (if present):
6468 * - msDS-LockoutThreshold
6469 * - msDS-LockoutObservationWindow
6471 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
6472 struct ldb_context *sam_ctx,
6473 struct ldb_message *user_msg,
6474 struct ldb_message *domain_msg,
6475 struct ldb_message *pso_msg,
6476 struct ldb_message **_mod_msg)
6478 int ret, badPwdCount;
6479 unsigned int i;
6480 int64_t lockoutThreshold, lockOutObservationWindow;
6481 struct dom_sid *sid;
6482 struct timeval tv_now = timeval_current();
6483 NTTIME now = timeval_to_nttime(&tv_now);
6484 NTSTATUS status;
6485 uint32_t pwdProperties, rid = 0;
6486 struct ldb_message *mod_msg;
6488 sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
6490 pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
6491 "pwdProperties", -1);
6492 if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
6493 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
6494 if (!NT_STATUS_IS_OK(status)) {
6496 * This can't happen anyway, but always try
6497 * and update the badPwdCount on failure
6499 rid = 0;
6502 TALLOC_FREE(sid);
6505 * Work out if we are doing password lockout on the domain.
6506 * Also, the built in administrator account is exempt:
6507 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
6509 lockoutThreshold = get_lockout_threshold(domain_msg, pso_msg);
6510 if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
6511 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
6512 ldb_dn_get_linearized(user_msg->dn)));
6513 return NT_STATUS_OK;
6516 mod_msg = ldb_msg_new(mem_ctx);
6517 if (mod_msg == NULL) {
6518 return NT_STATUS_NO_MEMORY;
6520 mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
6521 if (mod_msg->dn == NULL) {
6522 TALLOC_FREE(mod_msg);
6523 return NT_STATUS_NO_MEMORY;
6526 lockOutObservationWindow = get_lockout_observation_window(domain_msg,
6527 pso_msg);
6529 badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
6531 badPwdCount++;
6533 ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
6534 if (ret != LDB_SUCCESS) {
6535 TALLOC_FREE(mod_msg);
6536 return NT_STATUS_NO_MEMORY;
6538 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
6539 if (ret != LDB_SUCCESS) {
6540 TALLOC_FREE(mod_msg);
6541 return NT_STATUS_NO_MEMORY;
6544 if (badPwdCount >= lockoutThreshold) {
6545 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
6546 if (ret != LDB_SUCCESS) {
6547 TALLOC_FREE(mod_msg);
6548 return NT_STATUS_NO_MEMORY;
6550 DEBUGC( DBGC_AUTH, 1, ("Locked out user %s after %d wrong passwords\n",
6551 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
6552 } else {
6553 DEBUGC( DBGC_AUTH, 5, ("Updated badPwdCount on %s after %d wrong passwords\n",
6554 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
6557 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
6558 for (i=0; i< mod_msg->num_elements; i++) {
6559 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
6562 *_mod_msg = mod_msg;
6563 return NT_STATUS_OK;
6567 * Sets defaults for a User object
6568 * List of default attributes set:
6569 * accountExpires, badPasswordTime, badPwdCount,
6570 * codePage, countryCode, lastLogoff, lastLogon
6571 * logonCount, pwdLastSet
6573 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
6574 struct ldb_message *usr_obj,
6575 struct ldb_request *req)
6577 size_t i;
6578 int ret;
6579 const struct attribute_values {
6580 const char *name;
6581 const char *value;
6582 const char *add_value;
6583 const char *mod_value;
6584 const char *control;
6585 unsigned add_flags;
6586 unsigned mod_flags;
6587 } map[] = {
6589 .name = "accountExpires",
6590 .add_value = "9223372036854775807",
6591 .mod_value = "0",
6594 .name = "badPasswordTime",
6595 .value = "0"
6598 .name = "badPwdCount",
6599 .value = "0"
6602 .name = "codePage",
6603 .value = "0"
6606 .name = "countryCode",
6607 .value = "0"
6610 .name = "lastLogoff",
6611 .value = "0"
6614 .name = "lastLogon",
6615 .value = "0"
6618 .name = "logonCount",
6619 .value = "0"
6622 .name = "logonHours",
6623 .add_flags = DSDB_FLAG_INTERNAL_FORCE_META_DATA,
6626 .name = "pwdLastSet",
6627 .value = "0",
6628 .control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
6631 .name = "adminCount",
6632 .mod_value = "0",
6635 .name = "operatorCount",
6636 .mod_value = "0",
6640 for (i = 0; i < ARRAY_SIZE(map); i++) {
6641 bool added = false;
6642 const char *value = NULL;
6643 unsigned flags = 0;
6645 if (req != NULL && req->operation == LDB_ADD) {
6646 value = map[i].add_value;
6647 flags = map[i].add_flags;
6648 } else {
6649 value = map[i].mod_value;
6650 flags = map[i].mod_flags;
6653 if (value == NULL) {
6654 value = map[i].value;
6657 if (value != NULL) {
6658 flags |= LDB_FLAG_MOD_ADD;
6661 if (flags == 0) {
6662 continue;
6665 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
6666 map[i].name,
6667 value, flags,
6668 &added);
6669 if (ret != LDB_SUCCESS) {
6670 return ret;
6673 if (req != NULL && added && map[i].control != NULL) {
6674 ret = ldb_request_add_control(req,
6675 map[i].control,
6676 false, NULL);
6677 if (ret != LDB_SUCCESS) {
6678 return ret;
6683 return LDB_SUCCESS;
6687 * Sets 'sAMAccountType on user object based on userAccountControl.
6688 * This function is used in processing both 'add' and 'modify' requests.
6689 * @param ldb Current ldb_context
6690 * @param usr_obj ldb_message representing User object
6691 * @param user_account_control Value for userAccountControl flags
6692 * @param account_type_p Optional pointer to account_type to return
6693 * @return LDB_SUCCESS or LDB_ERR* code on failure
6695 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
6696 uint32_t user_account_control, uint32_t *account_type_p)
6698 int ret;
6699 uint32_t account_type;
6701 account_type = ds_uf2atype(user_account_control);
6702 if (account_type == 0) {
6703 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
6704 return LDB_ERR_UNWILLING_TO_PERFORM;
6706 ret = samdb_msg_add_uint_flags(ldb, usr_obj, usr_obj,
6707 "sAMAccountType",
6708 account_type,
6709 LDB_FLAG_MOD_REPLACE);
6710 if (ret != LDB_SUCCESS) {
6711 return ret;
6714 if (account_type_p) {
6715 *account_type_p = account_type;
6718 return LDB_SUCCESS;
6722 * Determine and set primaryGroupID based on userAccountControl value.
6723 * This function is used in processing both 'add' and 'modify' requests.
6724 * @param ldb Current ldb_context
6725 * @param usr_obj ldb_message representing User object
6726 * @param user_account_control Value for userAccountControl flags
6727 * @param group_rid_p Optional pointer to group RID to return
6728 * @return LDB_SUCCESS or LDB_ERR* code on failure
6730 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
6731 uint32_t user_account_control, uint32_t *group_rid_p)
6733 int ret;
6734 uint32_t rid;
6736 rid = ds_uf2prim_group_rid(user_account_control);
6738 ret = samdb_msg_add_uint_flags(ldb, usr_obj, usr_obj,
6739 "primaryGroupID", rid,
6740 LDB_FLAG_MOD_REPLACE);
6741 if (ret != LDB_SUCCESS) {
6742 return ret;
6745 if (group_rid_p) {
6746 *group_rid_p = rid;
6749 return LDB_SUCCESS;
6753 * Returns True if the source and target DNs both have the same naming context,
6754 * i.e. they're both in the same partition.
6756 bool dsdb_objects_have_same_nc(struct ldb_context *ldb,
6757 TALLOC_CTX *mem_ctx,
6758 struct ldb_dn *source_dn,
6759 struct ldb_dn *target_dn)
6761 TALLOC_CTX *tmp_ctx;
6762 struct ldb_dn *source_nc = NULL;
6763 struct ldb_dn *target_nc = NULL;
6764 int ret;
6765 bool same_nc = true;
6767 tmp_ctx = talloc_new(mem_ctx);
6768 if (tmp_ctx == NULL) {
6769 return ldb_oom(ldb);
6772 ret = dsdb_find_nc_root(ldb, tmp_ctx, source_dn, &source_nc);
6773 /* fix clang warning */
6774 if (source_nc == NULL) {
6775 ret = LDB_ERR_OTHER;
6777 if (ret != LDB_SUCCESS) {
6778 DBG_ERR("Failed to find base DN for source %s: %s\n",
6779 ldb_dn_get_linearized(source_dn), ldb_errstring(ldb));
6780 talloc_free(tmp_ctx);
6781 return true;
6784 ret = dsdb_find_nc_root(ldb, tmp_ctx, target_dn, &target_nc);
6785 /* fix clang warning */
6786 if (target_nc == NULL) {
6787 ret = LDB_ERR_OTHER;
6789 if (ret != LDB_SUCCESS) {
6790 DBG_ERR("Failed to find base DN for target %s: %s\n",
6791 ldb_dn_get_linearized(target_dn), ldb_errstring(ldb));
6792 talloc_free(tmp_ctx);
6793 return true;
6796 same_nc = (ldb_dn_compare(source_nc, target_nc) == 0);
6798 talloc_free(tmp_ctx);
6800 return same_nc;
6803 * Context for dsdb_count_domain_callback
6805 struct dsdb_count_domain_context {
6807 * Number of matching records
6809 size_t count;
6811 * sid of the domain that the records must belong to.
6812 * if NULL records can belong to any domain.
6814 struct dom_sid *dom_sid;
6818 * @brief ldb async callback for dsdb_domain_count.
6820 * count the number of records in the database matching an LDAP query,
6821 * optionally filtering for domain membership.
6823 * @param [in,out] req the ldb request being processed
6824 * req->context contains:
6825 * count The number of matching records
6826 * dom_sid The domain sid, if present records must belong
6827 * to the domain to be counted.
6828 *@param [in,out] ares The query result.
6830 * @return an LDB error code
6833 static int dsdb_count_domain_callback(
6834 struct ldb_request *req,
6835 struct ldb_reply *ares)
6838 if (ares == NULL) {
6839 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
6841 if (ares->error != LDB_SUCCESS) {
6842 int error = ares->error;
6843 TALLOC_FREE(ares);
6844 return ldb_request_done(req, error);
6847 switch (ares->type) {
6848 case LDB_REPLY_ENTRY:
6850 struct dsdb_count_domain_context *context = NULL;
6851 ssize_t ret;
6852 bool in_domain;
6853 struct dom_sid sid;
6854 const struct ldb_val *v;
6856 context = req->context;
6857 if (context->dom_sid == NULL) {
6858 context->count++;
6859 break;
6862 v = ldb_msg_find_ldb_val(ares->message, "objectSid");
6863 if (v == NULL) {
6864 break;
6867 ret = sid_parse(v->data, v->length, &sid);
6868 if (ret == -1) {
6869 break;
6872 in_domain = dom_sid_in_domain(context->dom_sid, &sid);
6873 if (!in_domain) {
6874 break;
6877 context->count++;
6878 break;
6880 case LDB_REPLY_REFERRAL:
6881 break;
6883 case LDB_REPLY_DONE:
6884 TALLOC_FREE(ares);
6885 return ldb_request_done(req, LDB_SUCCESS);
6888 TALLOC_FREE(ares);
6890 return LDB_SUCCESS;
6894 * @brief Count the number of records matching a query.
6896 * Count the number of entries in the database matching the supplied query,
6897 * optionally filtering only those entries belonging to the supplied domain.
6899 * @param ldb [in] Current ldb context
6900 * @param count [out] Pointer to the count
6901 * @param base [in] The base dn for the query
6902 * @param dom_sid [in] The domain sid, if non NULL records that are not a member
6903 * of the domain are ignored.
6904 * @param scope [in] Search scope.
6905 * @param exp_fmt [in] format string for the query.
6907 * @return LDB_STATUS code.
6909 int PRINTF_ATTRIBUTE(6, 7) dsdb_domain_count(
6910 struct ldb_context *ldb,
6911 size_t *count,
6912 struct ldb_dn *base,
6913 struct dom_sid *dom_sid,
6914 enum ldb_scope scope,
6915 const char *exp_fmt, ...)
6917 TALLOC_CTX *tmp_ctx = NULL;
6918 struct ldb_request *req = NULL;
6919 struct dsdb_count_domain_context *context = NULL;
6920 char *expression = NULL;
6921 const char *object_sid[] = {"objectSid", NULL};
6922 const char *none[] = {NULL};
6923 va_list ap;
6924 int ret;
6926 *count = 0;
6927 tmp_ctx = talloc_new(ldb);
6928 if (tmp_ctx == NULL) {
6929 return ldb_oom(ldb);
6932 context = talloc_zero(tmp_ctx, struct dsdb_count_domain_context);
6933 if (context == NULL) {
6934 return LDB_ERR_OPERATIONS_ERROR;
6936 context->dom_sid = dom_sid;
6938 if (exp_fmt) {
6939 va_start(ap, exp_fmt);
6940 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
6941 va_end(ap);
6943 if (expression == NULL) {
6944 TALLOC_FREE(context);
6945 TALLOC_FREE(tmp_ctx);
6946 return LDB_ERR_OPERATIONS_ERROR;
6950 ret = ldb_build_search_req(
6951 &req,
6952 ldb,
6953 tmp_ctx,
6954 base,
6955 scope,
6956 expression,
6957 (dom_sid == NULL) ? none : object_sid,
6958 NULL,
6959 context,
6960 dsdb_count_domain_callback,
6961 NULL);
6962 ldb_req_set_location(req, "dsdb_domain_count");
6964 if (ret != LDB_SUCCESS) goto done;
6966 ret = ldb_request(ldb, req);
6968 if (ret == LDB_SUCCESS) {
6969 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
6970 if (ret == LDB_SUCCESS) {
6971 *count = context->count;
6976 done:
6977 TALLOC_FREE(expression);
6978 TALLOC_FREE(req);
6979 TALLOC_FREE(context);
6980 TALLOC_FREE(tmp_ctx);
6982 return ret;
6986 * Returns 1 if 'sids' contains the Protected Users group SID for the domain, 0
6987 * if not. Returns a negative value on error.
6989 int dsdb_is_protected_user(struct ldb_context *ldb,
6990 const struct auth_SidAttr *sids,
6991 uint32_t num_sids)
6993 const struct dom_sid *domain_sid = NULL;
6994 struct dom_sid protected_users_sid;
6995 uint32_t i;
6997 domain_sid = samdb_domain_sid(ldb);
6998 if (domain_sid == NULL) {
6999 return -1;
7002 protected_users_sid = *domain_sid;
7003 if (!sid_append_rid(&protected_users_sid, DOMAIN_RID_PROTECTED_USERS)) {
7004 return -1;
7007 for (i = 0; i < num_sids; ++i) {
7008 if (dom_sid_equal(&protected_users_sid, &sids[i].sid)) {
7009 return 1;
7013 return 0;