s4/rodc: RODC FAS initial implementation
[Samba/ekacnet.git] / source4 / dsdb / common / util.c
blobe4e55fc530fe17248a3499cf41a4ae1c2051c79d
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 "events/events.h"
26 #include "ldb.h"
27 #include "ldb_errors.h"
28 #include "../lib/util/util_ldb.h"
29 #include "../lib/crypto/crypto.h"
30 #include "dsdb/samdb/samdb.h"
31 #include "libcli/security/security.h"
32 #include "librpc/gen_ndr/ndr_security.h"
33 #include "librpc/gen_ndr/ndr_misc.h"
34 #include "../libds/common/flags.h"
35 #include "dsdb/common/proto.h"
36 #include "libcli/ldap/ldap_ndr.h"
37 #include "param/param.h"
38 #include "libcli/auth/libcli_auth.h"
39 #include "librpc/gen_ndr/ndr_drsblobs.h"
40 #include "system/locale.h"
41 #include "lib/util/tsort.h"
42 #include "dsdb/common/util.h"
43 #include "lib/socket/socket.h"
44 #include "dsdb/samdb/ldb_modules/util.h"
47 search the sam for the specified attributes in a specific domain, filter on
48 objectSid being in domain_sid.
50 int samdb_search_domain(struct ldb_context *sam_ldb,
51 TALLOC_CTX *mem_ctx,
52 struct ldb_dn *basedn,
53 struct ldb_message ***res,
54 const char * const *attrs,
55 const struct dom_sid *domain_sid,
56 const char *format, ...) _PRINTF_ATTRIBUTE(7,8)
58 va_list ap;
59 int i, count;
61 va_start(ap, format);
62 count = gendb_search_v(sam_ldb, mem_ctx, basedn,
63 res, attrs, format, ap);
64 va_end(ap);
66 i=0;
68 while (i<count) {
69 struct dom_sid *entry_sid;
71 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
73 if ((entry_sid == NULL) ||
74 (!dom_sid_in_domain(domain_sid, entry_sid))) {
75 /* Delete that entry from the result set */
76 (*res)[i] = (*res)[count-1];
77 count -= 1;
78 talloc_free(entry_sid);
79 continue;
81 talloc_free(entry_sid);
82 i += 1;
85 return count;
89 search the sam for a single string attribute in exactly 1 record
91 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
92 TALLOC_CTX *mem_ctx,
93 struct ldb_dn *basedn,
94 const char *attr_name,
95 const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
97 int count;
98 const char *attrs[2] = { NULL, NULL };
99 struct ldb_message **res = NULL;
101 attrs[0] = attr_name;
103 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
104 if (count > 1) {
105 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
106 attr_name, format, count));
108 if (count != 1) {
109 talloc_free(res);
110 return NULL;
113 return samdb_result_string(res[0], attr_name, NULL);
117 search the sam for a single string attribute in exactly 1 record
119 const char *samdb_search_string(struct ldb_context *sam_ldb,
120 TALLOC_CTX *mem_ctx,
121 struct ldb_dn *basedn,
122 const char *attr_name,
123 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
125 va_list ap;
126 const char *str;
128 va_start(ap, format);
129 str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
130 va_end(ap);
132 return str;
135 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
136 TALLOC_CTX *mem_ctx,
137 struct ldb_dn *basedn,
138 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
140 va_list ap;
141 struct ldb_dn *ret;
142 struct ldb_message **res = NULL;
143 int count;
145 va_start(ap, format);
146 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
147 va_end(ap);
149 if (count != 1) return NULL;
151 ret = talloc_steal(mem_ctx, res[0]->dn);
152 talloc_free(res);
154 return ret;
158 search the sam for a dom_sid attribute in exactly 1 record
160 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
161 TALLOC_CTX *mem_ctx,
162 struct ldb_dn *basedn,
163 const char *attr_name,
164 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
166 va_list ap;
167 int count;
168 struct ldb_message **res;
169 const char *attrs[2] = { NULL, NULL };
170 struct dom_sid *sid;
172 attrs[0] = attr_name;
174 va_start(ap, format);
175 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
176 va_end(ap);
177 if (count > 1) {
178 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
179 attr_name, format, count));
181 if (count != 1) {
182 talloc_free(res);
183 return NULL;
185 sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
186 talloc_free(res);
187 return sid;
191 return the count of the number of records in the sam matching the query
193 int samdb_search_count(struct ldb_context *sam_ldb,
194 struct ldb_dn *basedn,
195 const char *format, ...) _PRINTF_ATTRIBUTE(3,4)
197 va_list ap;
198 struct ldb_message **res;
199 const char *attrs[] = { NULL };
200 int ret;
201 TALLOC_CTX *tmp_ctx = talloc_new(sam_ldb);
203 va_start(ap, format);
204 ret = gendb_search_v(sam_ldb, tmp_ctx, basedn, &res, attrs, format, ap);
205 va_end(ap);
206 talloc_free(tmp_ctx);
208 return ret;
213 search the sam for a single integer attribute in exactly 1 record
215 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
216 TALLOC_CTX *mem_ctx,
217 unsigned int default_value,
218 struct ldb_dn *basedn,
219 const char *attr_name,
220 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
222 va_list ap;
223 int count;
224 struct ldb_message **res;
225 const char *attrs[2] = { NULL, NULL };
227 attrs[0] = attr_name;
229 va_start(ap, format);
230 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
231 va_end(ap);
233 if (count != 1) {
234 return default_value;
237 return samdb_result_uint(res[0], attr_name, default_value);
241 search the sam for a single signed 64 bit integer attribute in exactly 1 record
243 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
244 TALLOC_CTX *mem_ctx,
245 int64_t default_value,
246 struct ldb_dn *basedn,
247 const char *attr_name,
248 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
250 va_list ap;
251 int count;
252 struct ldb_message **res;
253 const char *attrs[2] = { NULL, NULL };
255 attrs[0] = attr_name;
257 va_start(ap, format);
258 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
259 va_end(ap);
261 if (count != 1) {
262 return default_value;
265 return samdb_result_int64(res[0], attr_name, default_value);
269 search the sam for multipe records each giving a single string attribute
270 return the number of matches, or -1 on error
272 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
273 TALLOC_CTX *mem_ctx,
274 struct ldb_dn *basedn,
275 const char ***strs,
276 const char *attr_name,
277 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
279 va_list ap;
280 int count, i;
281 const char *attrs[2] = { NULL, NULL };
282 struct ldb_message **res = NULL;
284 attrs[0] = attr_name;
286 va_start(ap, format);
287 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
288 va_end(ap);
290 if (count <= 0) {
291 return count;
294 /* make sure its single valued */
295 for (i=0;i<count;i++) {
296 if (res[i]->num_elements != 1) {
297 DEBUG(1,("samdb: search for %s %s not single valued\n",
298 attr_name, format));
299 talloc_free(res);
300 return -1;
304 *strs = talloc_array(mem_ctx, const char *, count+1);
305 if (! *strs) {
306 talloc_free(res);
307 return -1;
310 for (i=0;i<count;i++) {
311 (*strs)[i] = samdb_result_string(res[i], attr_name, NULL);
313 (*strs)[count] = NULL;
315 return count;
319 pull a uint from a result set.
321 unsigned int samdb_result_uint(const struct ldb_message *msg, const char *attr, unsigned int default_value)
323 return ldb_msg_find_attr_as_uint(msg, attr, default_value);
327 pull a (signed) int64 from a result set.
329 int64_t samdb_result_int64(const struct ldb_message *msg, const char *attr, int64_t default_value)
331 return ldb_msg_find_attr_as_int64(msg, attr, default_value);
335 pull a string from a result set.
337 const char *samdb_result_string(const struct ldb_message *msg, const char *attr,
338 const char *default_value)
340 return ldb_msg_find_attr_as_string(msg, attr, default_value);
343 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
344 const char *attr, struct ldb_dn *default_value)
346 struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
347 if (!ret_dn) {
348 return default_value;
350 return ret_dn;
354 pull a rid from a objectSid in a result set.
356 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
357 const char *attr, uint32_t default_value)
359 struct dom_sid *sid;
360 uint32_t rid;
362 sid = samdb_result_dom_sid(mem_ctx, msg, attr);
363 if (sid == NULL) {
364 return default_value;
366 rid = sid->sub_auths[sid->num_auths-1];
367 talloc_free(sid);
368 return rid;
372 pull a dom_sid structure from a objectSid in a result set.
374 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
375 const char *attr)
377 const struct ldb_val *v;
378 struct dom_sid *sid;
379 enum ndr_err_code ndr_err;
380 v = ldb_msg_find_ldb_val(msg, attr);
381 if (v == NULL) {
382 return NULL;
384 sid = talloc(mem_ctx, struct dom_sid);
385 if (sid == NULL) {
386 return NULL;
388 ndr_err = ndr_pull_struct_blob(v, sid, NULL, sid,
389 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
390 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
391 talloc_free(sid);
392 return NULL;
394 return sid;
398 pull a guid structure from a objectGUID in a result set.
400 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
402 const struct ldb_val *v;
403 struct GUID guid;
404 NTSTATUS status;
406 v = ldb_msg_find_ldb_val(msg, attr);
407 if (!v) return GUID_zero();
409 status = GUID_from_ndr_blob(v, &guid);
410 if (!NT_STATUS_IS_OK(status)) {
411 return GUID_zero();
414 return guid;
418 pull a sid prefix from a objectSid in a result set.
419 this is used to find the domain sid for a user
421 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
422 const char *attr)
424 struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
425 if (!sid || sid->num_auths < 1) return NULL;
426 sid->num_auths--;
427 return sid;
431 pull a NTTIME in a result set.
433 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
434 NTTIME default_value)
436 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
440 * Windows stores 0 for lastLogoff.
441 * But when a MS DC return the lastLogoff (as Logoff Time)
442 * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
443 * cause windows 2008 and newer version to fail for SMB requests
445 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
447 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
449 if (ret == 0)
450 ret = 0x7FFFFFFFFFFFFFFFULL;
452 return ret;
456 * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
457 * indicate an account doesn't expire.
459 * When Windows initially creates an account, it sets
460 * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF). However,
461 * when changing from an account having a specific expiration date to
462 * that account never expiring, it sets accountExpires = 0.
464 * Consolidate that logic here to allow clearer logic for account expiry in
465 * the rest of the code.
467 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
469 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
472 if (ret == 0)
473 ret = 0x7FFFFFFFFFFFFFFFULL;
475 return ret;
479 pull a uint64_t from a result set.
481 uint64_t samdb_result_uint64(const struct ldb_message *msg, const char *attr,
482 uint64_t default_value)
484 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
489 construct the allow_password_change field from the PwdLastSet attribute and the
490 domain password settings
492 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb,
493 TALLOC_CTX *mem_ctx,
494 struct ldb_dn *domain_dn,
495 struct ldb_message *msg,
496 const char *attr)
498 uint64_t attr_time = samdb_result_uint64(msg, attr, 0);
499 int64_t minPwdAge;
501 if (attr_time == 0) {
502 return 0;
505 minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
507 /* yes, this is a -= not a += as minPwdAge is stored as the negative
508 of the number of 100-nano-seconds */
509 attr_time -= minPwdAge;
511 return attr_time;
515 construct the force_password_change field from the PwdLastSet
516 attribute, the userAccountControl and the domain password settings
518 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb,
519 TALLOC_CTX *mem_ctx,
520 struct ldb_dn *domain_dn,
521 struct ldb_message *msg)
523 uint64_t attr_time = samdb_result_uint64(msg, "pwdLastSet", 0);
524 uint32_t userAccountControl = samdb_result_uint64(msg, "userAccountControl", 0);
525 int64_t maxPwdAge;
527 /* Machine accounts don't expire, and there is a flag for 'no expiry' */
528 if (!(userAccountControl & UF_NORMAL_ACCOUNT)
529 || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
530 return 0x7FFFFFFFFFFFFFFFULL;
533 if (attr_time == 0) {
534 return 0;
537 maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "maxPwdAge", NULL);
538 if (maxPwdAge == 0) {
539 return 0x7FFFFFFFFFFFFFFFULL;
540 } else {
541 attr_time -= maxPwdAge;
544 return attr_time;
548 pull a samr_Password structutre from a result set.
550 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
552 struct samr_Password *hash = NULL;
553 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
554 if (val && (val->length >= sizeof(hash->hash))) {
555 hash = talloc(mem_ctx, struct samr_Password);
556 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
558 return hash;
562 pull an array of samr_Password structures from a result set.
564 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
565 const char *attr, struct samr_Password **hashes)
567 unsigned int count, i;
568 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
570 *hashes = NULL;
571 if (!val) {
572 return 0;
574 count = val->length / 16;
575 if (count == 0) {
576 return 0;
579 *hashes = talloc_array(mem_ctx, struct samr_Password, count);
580 if (! *hashes) {
581 return 0;
584 for (i=0;i<count;i++) {
585 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
588 return count;
591 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct ldb_message *msg,
592 struct samr_Password **lm_pwd, struct samr_Password **nt_pwd)
594 struct samr_Password *lmPwdHash, *ntPwdHash;
595 if (nt_pwd) {
596 unsigned int num_nt;
597 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
598 if (num_nt == 0) {
599 *nt_pwd = NULL;
600 } else if (num_nt > 1) {
601 return NT_STATUS_INTERNAL_DB_CORRUPTION;
602 } else {
603 *nt_pwd = &ntPwdHash[0];
606 if (lm_pwd) {
607 /* Ensure that if we have turned off LM
608 * authentication, that we never use the LM hash, even
609 * if we store it */
610 if (lp_lanman_auth(lp_ctx)) {
611 unsigned int num_lm;
612 num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
613 if (num_lm == 0) {
614 *lm_pwd = NULL;
615 } else if (num_lm > 1) {
616 return NT_STATUS_INTERNAL_DB_CORRUPTION;
617 } else {
618 *lm_pwd = &lmPwdHash[0];
620 } else {
621 *lm_pwd = NULL;
624 return NT_STATUS_OK;
628 pull a samr_LogonHours structutre from a result set.
630 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
632 struct samr_LogonHours hours;
633 const int units_per_week = 168;
634 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
635 ZERO_STRUCT(hours);
636 hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week);
637 if (!hours.bits) {
638 return hours;
640 hours.units_per_week = units_per_week;
641 memset(hours.bits, 0xFF, units_per_week);
642 if (val) {
643 memcpy(hours.bits, val->data, MIN(val->length, units_per_week));
645 return hours;
649 pull a set of account_flags from a result set.
651 This requires that the attributes:
652 pwdLastSet
653 userAccountControl
654 be included in 'msg'
656 uint32_t samdb_result_acct_flags(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
657 struct ldb_message *msg, struct ldb_dn *domain_dn)
659 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
660 uint32_t acct_flags = ds_uf2acb(userAccountControl);
661 NTTIME must_change_time;
662 NTTIME now;
664 must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx,
665 domain_dn, msg);
667 /* Test account expire time */
668 unix_to_nt_time(&now, time(NULL));
669 /* check for expired password */
670 if (must_change_time < now) {
671 acct_flags |= ACB_PW_EXPIRED;
673 return acct_flags;
676 struct lsa_BinaryString samdb_result_parameters(TALLOC_CTX *mem_ctx,
677 struct ldb_message *msg,
678 const char *attr)
680 struct lsa_BinaryString s;
681 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
683 ZERO_STRUCT(s);
685 if (!val) {
686 return s;
689 s.array = talloc_array(mem_ctx, uint16_t, val->length/2);
690 if (!s.array) {
691 return s;
693 s.length = s.size = val->length;
694 memcpy(s.array, val->data, val->length);
696 return s;
699 /* Find an attribute, with a particular value */
701 /* The current callers of this function expect a very specific
702 * behaviour: In particular, objectClass subclass equivilance is not
703 * wanted. This means that we should not lookup the schema for the
704 * comparison function */
705 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
706 const struct ldb_message *msg,
707 const char *name, const char *value)
709 unsigned int i;
710 struct ldb_message_element *el = ldb_msg_find_element(msg, name);
712 if (!el) {
713 return NULL;
716 for (i=0;i<el->num_values;i++) {
717 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
718 return el;
722 return NULL;
725 int samdb_find_or_add_value(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
727 if (samdb_find_attribute(ldb, msg, name, set_value) == NULL) {
728 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
730 return LDB_SUCCESS;
733 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
735 struct ldb_message_element *el;
737 el = ldb_msg_find_element(msg, name);
738 if (el) {
739 return LDB_SUCCESS;
742 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
748 add a string element to a message
750 int samdb_msg_add_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
751 const char *attr_name, const char *str)
753 char *s = talloc_strdup(mem_ctx, str);
754 char *a = talloc_strdup(mem_ctx, attr_name);
755 if (s == NULL || a == NULL) {
756 return LDB_ERR_OPERATIONS_ERROR;
758 return ldb_msg_add_string(msg, a, s);
762 add a dom_sid element to a message
764 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
765 const char *attr_name, struct dom_sid *sid)
767 struct ldb_val v;
768 enum ndr_err_code ndr_err;
770 ndr_err = ndr_push_struct_blob(&v, mem_ctx,
771 lp_iconv_convenience(ldb_get_opaque(sam_ldb, "loadparm")),
772 sid,
773 (ndr_push_flags_fn_t)ndr_push_dom_sid);
774 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
775 return LDB_ERR_OPERATIONS_ERROR;
777 return ldb_msg_add_value(msg, attr_name, &v, NULL);
782 add a delete element operation to a message
784 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
785 const char *attr_name)
787 /* we use an empty replace rather than a delete, as it allows for
788 dsdb_replace() to be used everywhere */
789 return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
793 add a add attribute value to a message
795 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
796 const char *attr_name, const char *value)
798 struct ldb_message_element *el;
799 char *a, *v;
800 int ret;
801 a = talloc_strdup(mem_ctx, attr_name);
802 if (a == NULL)
803 return LDB_ERR_OPERATIONS_ERROR;
804 v = talloc_strdup(mem_ctx, value);
805 if (v == NULL)
806 return LDB_ERR_OPERATIONS_ERROR;
807 ret = ldb_msg_add_string(msg, a, v);
808 if (ret != 0)
809 return ret;
810 el = ldb_msg_find_element(msg, a);
811 if (el == NULL)
812 return LDB_ERR_OPERATIONS_ERROR;
813 el->flags = LDB_FLAG_MOD_ADD;
814 return LDB_SUCCESS;
818 add a delete attribute value to a message
820 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
821 const char *attr_name, const char *value)
823 struct ldb_message_element *el;
824 char *a, *v;
825 int ret;
826 a = talloc_strdup(mem_ctx, attr_name);
827 if (a == NULL)
828 return LDB_ERR_OPERATIONS_ERROR;
829 v = talloc_strdup(mem_ctx, value);
830 if (v == NULL)
831 return LDB_ERR_OPERATIONS_ERROR;
832 ret = ldb_msg_add_string(msg, a, v);
833 if (ret != 0)
834 return ret;
835 el = ldb_msg_find_element(msg, a);
836 if (el == NULL)
837 return LDB_ERR_OPERATIONS_ERROR;
838 el->flags = LDB_FLAG_MOD_DELETE;
839 return LDB_SUCCESS;
843 add a int element to a message
845 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
846 const char *attr_name, int v)
848 const char *s = talloc_asprintf(mem_ctx, "%d", v);
849 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
853 add a unsigned int element to a message
855 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
856 const char *attr_name, unsigned int v)
858 return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
862 add a (signed) int64_t element to a message
864 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
865 const char *attr_name, int64_t v)
867 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
868 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
872 add a uint64_t element to a message
874 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
875 const char *attr_name, uint64_t v)
877 return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
881 add a samr_Password element to a message
883 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
884 const char *attr_name, struct samr_Password *hash)
886 struct ldb_val val;
887 val.data = talloc_memdup(mem_ctx, hash->hash, 16);
888 if (!val.data) {
889 return LDB_ERR_OPERATIONS_ERROR;
891 val.length = 16;
892 return ldb_msg_add_value(msg, attr_name, &val, NULL);
896 add a samr_Password array to a message
898 int samdb_msg_add_hashes(TALLOC_CTX *mem_ctx, struct ldb_message *msg,
899 const char *attr_name, struct samr_Password *hashes,
900 unsigned int count)
902 struct ldb_val val;
903 unsigned int i;
904 val.data = talloc_array_size(mem_ctx, 16, count);
905 val.length = count*16;
906 if (!val.data) {
907 return LDB_ERR_OPERATIONS_ERROR;
909 for (i=0;i<count;i++) {
910 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
912 return ldb_msg_add_value(msg, attr_name, &val, NULL);
916 add a acct_flags element to a message
918 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
919 const char *attr_name, uint32_t v)
921 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
925 add a logon_hours element to a message
927 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
928 const char *attr_name, struct samr_LogonHours *hours)
930 struct ldb_val val;
931 val.length = hours->units_per_week / 8;
932 val.data = hours->bits;
933 return ldb_msg_add_value(msg, attr_name, &val, NULL);
937 add a parameters element to a message
939 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
940 const char *attr_name, struct lsa_BinaryString *parameters)
942 struct ldb_val val;
943 val.length = parameters->length;
944 val.data = (uint8_t *)parameters->array;
945 return ldb_msg_add_value(msg, attr_name, &val, NULL);
948 add a general value element to a message
950 int samdb_msg_add_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
951 const char *attr_name, const struct ldb_val *val)
953 return ldb_msg_add_value(msg, attr_name, val, NULL);
957 sets a general value element to a message
959 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
960 const char *attr_name, const struct ldb_val *val)
962 struct ldb_message_element *el;
964 el = ldb_msg_find_element(msg, attr_name);
965 if (el) {
966 el->num_values = 0;
968 return ldb_msg_add_value(msg, attr_name, val, NULL);
972 set a string element in a message
974 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
975 const char *attr_name, const char *str)
977 struct ldb_message_element *el;
979 el = ldb_msg_find_element(msg, attr_name);
980 if (el) {
981 el->num_values = 0;
983 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, str);
987 * Handle ldb_request in transaction
989 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
990 struct ldb_request *req)
992 int ret;
994 ret = ldb_transaction_start(sam_ldb);
995 if (ret != LDB_SUCCESS) {
996 return ret;
999 ret = ldb_request(sam_ldb, req);
1000 if (ret == LDB_SUCCESS) {
1001 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1004 if (ret == LDB_SUCCESS) {
1005 return ldb_transaction_commit(sam_ldb);
1007 ldb_transaction_cancel(sam_ldb);
1009 return ret;
1013 return a default security descriptor
1015 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1017 struct security_descriptor *sd;
1019 sd = security_descriptor_initialise(mem_ctx);
1021 return sd;
1024 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1026 struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1027 struct ldb_dn *aggregate_dn;
1028 if (!schema_dn) {
1029 return NULL;
1032 aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1033 if (!aggregate_dn) {
1034 return NULL;
1036 if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1037 return NULL;
1039 return aggregate_dn;
1042 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1044 struct ldb_dn *new_dn;
1046 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1047 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1048 talloc_free(new_dn);
1049 return NULL;
1051 return new_dn;
1054 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1056 struct ldb_dn *new_dn;
1058 new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1059 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1060 talloc_free(new_dn);
1061 return NULL;
1063 return new_dn;
1066 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1068 struct ldb_dn *new_dn;
1070 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1071 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1072 talloc_free(new_dn);
1073 return NULL;
1075 return new_dn;
1079 work out the domain sid for the current open ldb
1081 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1083 TALLOC_CTX *tmp_ctx;
1084 const struct dom_sid *domain_sid;
1085 const char *attrs[] = {
1086 "objectSid",
1087 NULL
1089 struct ldb_result *res;
1090 int ret;
1092 /* see if we have a cached copy */
1093 domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1094 if (domain_sid) {
1095 return domain_sid;
1098 tmp_ctx = talloc_new(ldb);
1099 if (tmp_ctx == NULL) {
1100 goto failed;
1103 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1105 if (ret != LDB_SUCCESS) {
1106 goto failed;
1109 if (res->count != 1) {
1110 goto failed;
1113 domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1114 if (domain_sid == NULL) {
1115 goto failed;
1118 /* cache the domain_sid in the ldb */
1119 if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1120 goto failed;
1123 talloc_steal(ldb, domain_sid);
1124 talloc_free(tmp_ctx);
1126 return domain_sid;
1128 failed:
1129 talloc_free(tmp_ctx);
1130 return NULL;
1134 get domain sid from cache
1136 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1138 return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1141 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1143 TALLOC_CTX *tmp_ctx;
1144 struct dom_sid *dom_sid_new;
1145 struct dom_sid *dom_sid_old;
1147 /* see if we have a cached copy */
1148 dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1149 "cache.domain_sid"), struct dom_sid);
1151 tmp_ctx = talloc_new(ldb);
1152 if (tmp_ctx == NULL) {
1153 goto failed;
1156 dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1157 if (!dom_sid_new) {
1158 goto failed;
1161 /* cache the domain_sid in the ldb */
1162 if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1163 goto failed;
1166 talloc_steal(ldb, dom_sid_new);
1167 talloc_free(tmp_ctx);
1168 talloc_free(dom_sid_old);
1170 return true;
1172 failed:
1173 DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1174 talloc_free(tmp_ctx);
1175 return false;
1178 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1180 TALLOC_CTX *tmp_ctx;
1181 struct ldb_dn *ntds_settings_dn_new;
1182 struct ldb_dn *ntds_settings_dn_old;
1184 /* see if we have a cached copy */
1185 ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb,
1186 "cache.ntds_settings_dn"), struct ldb_dn);
1188 tmp_ctx = talloc_new(ldb);
1189 if (tmp_ctx == NULL) {
1190 goto failed;
1193 ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1194 if (!ntds_settings_dn_new) {
1195 goto failed;
1198 /* cache the domain_sid in the ldb */
1199 if (ldb_set_opaque(ldb, "cache.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1200 goto failed;
1203 talloc_steal(ldb, ntds_settings_dn_new);
1204 talloc_free(tmp_ctx);
1205 talloc_free(ntds_settings_dn_old);
1207 return true;
1209 failed:
1210 DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1211 talloc_free(tmp_ctx);
1212 return false;
1215 /* Obtain the short name of the flexible single master operator
1216 * (FSMO), such as the PDC Emulator */
1217 const char *samdb_result_fsmo_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
1218 const char *attr)
1220 /* Format is cn=NTDS Settings,cn=<NETBIOS name of FSMO>,.... */
1221 struct ldb_dn *fsmo_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
1222 const struct ldb_val *val = ldb_dn_get_component_val(fsmo_dn, 1);
1223 const char *name = ldb_dn_get_component_name(fsmo_dn, 1);
1225 if (!name || (ldb_attr_cmp(name, "cn") != 0)) {
1226 /* Ensure this matches the format. This gives us a
1227 * bit more confidence that a 'cn' value will be a
1228 * ascii string */
1229 return NULL;
1231 if (val) {
1232 return (char *)val->data;
1234 return NULL;
1238 work out the ntds settings dn for the current open ldb
1240 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1242 TALLOC_CTX *tmp_ctx;
1243 const char *root_attrs[] = { "dsServiceName", NULL };
1244 int ret;
1245 struct ldb_result *root_res;
1246 struct ldb_dn *settings_dn;
1248 /* see if we have a cached copy */
1249 settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "cache.ntds_settings_dn");
1250 if (settings_dn) {
1251 return settings_dn;
1254 tmp_ctx = talloc_new(ldb);
1255 if (tmp_ctx == NULL) {
1256 goto failed;
1259 ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1260 if (ret) {
1261 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1262 ldb_errstring(ldb)));
1263 goto failed;
1266 if (root_res->count != 1) {
1267 goto failed;
1270 settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1272 /* cache the domain_sid in the ldb */
1273 if (ldb_set_opaque(ldb, "cache.settings_dn", settings_dn) != LDB_SUCCESS) {
1274 goto failed;
1277 talloc_steal(ldb, settings_dn);
1278 talloc_free(tmp_ctx);
1280 return settings_dn;
1282 failed:
1283 DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1284 talloc_free(tmp_ctx);
1285 return NULL;
1289 work out the ntds settings invocationId for the current open ldb
1291 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1293 TALLOC_CTX *tmp_ctx;
1294 const char *attrs[] = { "invocationId", NULL };
1295 int ret;
1296 struct ldb_result *res;
1297 struct GUID *invocation_id;
1299 /* see if we have a cached copy */
1300 invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1301 if (invocation_id) {
1302 return invocation_id;
1305 tmp_ctx = talloc_new(ldb);
1306 if (tmp_ctx == NULL) {
1307 goto failed;
1310 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1311 if (ret) {
1312 goto failed;
1315 if (res->count != 1) {
1316 goto failed;
1319 invocation_id = talloc(tmp_ctx, struct GUID);
1320 if (!invocation_id) {
1321 goto failed;
1324 *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1326 /* cache the domain_sid in the ldb */
1327 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1328 goto failed;
1331 talloc_steal(ldb, invocation_id);
1332 talloc_free(tmp_ctx);
1334 return invocation_id;
1336 failed:
1337 DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1338 talloc_free(tmp_ctx);
1339 return NULL;
1342 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1344 TALLOC_CTX *tmp_ctx;
1345 struct GUID *invocation_id_new;
1346 struct GUID *invocation_id_old;
1348 /* see if we have a cached copy */
1349 invocation_id_old = (struct GUID *)ldb_get_opaque(ldb,
1350 "cache.invocation_id");
1352 tmp_ctx = talloc_new(ldb);
1353 if (tmp_ctx == NULL) {
1354 goto failed;
1357 invocation_id_new = talloc(tmp_ctx, struct GUID);
1358 if (!invocation_id_new) {
1359 goto failed;
1362 *invocation_id_new = *invocation_id_in;
1364 /* cache the domain_sid in the ldb */
1365 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1366 goto failed;
1369 talloc_steal(ldb, invocation_id_new);
1370 talloc_free(tmp_ctx);
1371 talloc_free(invocation_id_old);
1373 return true;
1375 failed:
1376 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1377 talloc_free(tmp_ctx);
1378 return false;
1382 work out the ntds settings objectGUID for the current open ldb
1384 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1386 TALLOC_CTX *tmp_ctx;
1387 const char *attrs[] = { "objectGUID", NULL };
1388 int ret;
1389 struct ldb_result *res;
1390 struct GUID *ntds_guid;
1392 /* see if we have a cached copy */
1393 ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1394 if (ntds_guid) {
1395 return ntds_guid;
1398 tmp_ctx = talloc_new(ldb);
1399 if (tmp_ctx == NULL) {
1400 goto failed;
1403 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1404 if (ret) {
1405 goto failed;
1408 if (res->count != 1) {
1409 goto failed;
1412 ntds_guid = talloc(tmp_ctx, struct GUID);
1413 if (!ntds_guid) {
1414 goto failed;
1417 *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1419 /* cache the domain_sid in the ldb */
1420 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1421 goto failed;
1424 talloc_steal(ldb, ntds_guid);
1425 talloc_free(tmp_ctx);
1427 return ntds_guid;
1429 failed:
1430 DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1431 talloc_free(tmp_ctx);
1432 return NULL;
1435 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1437 TALLOC_CTX *tmp_ctx;
1438 struct GUID *ntds_guid_new;
1439 struct GUID *ntds_guid_old;
1441 /* see if we have a cached copy */
1442 ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1444 tmp_ctx = talloc_new(ldb);
1445 if (tmp_ctx == NULL) {
1446 goto failed;
1449 ntds_guid_new = talloc(tmp_ctx, struct GUID);
1450 if (!ntds_guid_new) {
1451 goto failed;
1454 *ntds_guid_new = *ntds_guid_in;
1456 /* cache the domain_sid in the ldb */
1457 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1458 goto failed;
1461 talloc_steal(ldb, ntds_guid_new);
1462 talloc_free(tmp_ctx);
1463 talloc_free(ntds_guid_old);
1465 return true;
1467 failed:
1468 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1469 talloc_free(tmp_ctx);
1470 return false;
1474 work out the server dn for the current open ldb
1476 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1478 return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1482 work out the server dn for the current open ldb
1484 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1486 struct ldb_dn *server_dn;
1487 struct ldb_dn *servers_dn;
1488 struct ldb_dn *server_site_dn;
1490 /* TODO: there must be a saner way to do this!! */
1491 server_dn = samdb_server_dn(ldb, mem_ctx);
1492 if (!server_dn) return NULL;
1494 servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1495 talloc_free(server_dn);
1496 if (!servers_dn) return NULL;
1498 server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1499 talloc_free(servers_dn);
1501 return server_site_dn;
1505 find a 'reference' DN that points at another object
1506 (eg. serverReference, rIDManagerReference etc)
1508 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1509 const char *attribute, struct ldb_dn **dn)
1511 const char *attrs[2];
1512 struct ldb_result *res;
1513 int ret;
1515 attrs[0] = attribute;
1516 attrs[1] = NULL;
1518 ret = ldb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, NULL);
1519 if (ret != LDB_SUCCESS) {
1520 return ret;
1522 if (res->count != 1) {
1523 talloc_free(res);
1524 return LDB_ERR_NO_SUCH_OBJECT;
1527 *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1528 if (!*dn) {
1529 talloc_free(res);
1530 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1533 talloc_free(res);
1534 return LDB_SUCCESS;
1538 find our machine account via the serverReference attribute in the
1539 server DN
1541 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1543 struct ldb_dn *server_dn;
1544 int ret;
1546 server_dn = samdb_server_dn(ldb, mem_ctx);
1547 if (server_dn == NULL) {
1548 return LDB_ERR_NO_SUCH_OBJECT;
1551 ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1552 talloc_free(server_dn);
1554 return ret;
1558 find the RID Manager$ DN via the rIDManagerReference attribute in the
1559 base DN
1561 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1563 return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1564 "rIDManagerReference", dn);
1568 find the RID Set DN via the rIDSetReferences attribute in our
1569 machine account DN
1571 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1573 struct ldb_dn *server_ref_dn;
1574 int ret;
1576 ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1577 if (ret != LDB_SUCCESS) {
1578 return ret;
1580 ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1581 talloc_free(server_ref_dn);
1582 return ret;
1585 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1587 const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1588 mem_ctx));
1590 if (val == NULL) {
1591 return NULL;
1594 return (const char *) val->data;
1598 * Finds the client site by using the client's IP address.
1599 * The "subnet_name" returns the name of the subnet if parameter != NULL
1601 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1602 const char *ip_address, char **subnet_name)
1604 const char *attrs[] = { "cn", "siteObject", NULL };
1605 struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1606 struct ldb_result *res;
1607 const struct ldb_val *val;
1608 const char *site_name = NULL, *l_subnet_name = NULL;
1609 const char *allow_list[2] = { NULL, NULL };
1610 unsigned int i;
1611 int cnt, ret;
1614 * if we don't have a client ip e.g. ncalrpc
1615 * the server site is the client site
1617 if (ip_address == NULL) {
1618 return samdb_server_site_name(ldb, mem_ctx);
1621 sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1622 if (sites_container_dn == NULL) {
1623 return NULL;
1626 subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1627 if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1628 talloc_free(sites_container_dn);
1629 talloc_free(subnets_dn);
1630 return NULL;
1633 ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1634 attrs, NULL);
1635 if (ret != LDB_SUCCESS) {
1636 talloc_free(sites_container_dn);
1637 talloc_free(subnets_dn);
1638 return NULL;
1641 for (i = 0; i < res->count; i++) {
1642 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1643 NULL);
1645 allow_list[0] = l_subnet_name;
1647 if (allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1648 sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1649 res->msgs[i],
1650 "siteObject");
1651 if (sites_dn == NULL) {
1652 /* No reference, maybe another subnet matches */
1653 continue;
1656 /* "val" cannot be NULL here since "sites_dn" != NULL */
1657 val = ldb_dn_get_rdn_val(sites_dn);
1658 site_name = talloc_strdup(mem_ctx,
1659 (const char *) val->data);
1661 talloc_free(sites_dn);
1663 break;
1667 if (site_name == NULL) {
1668 /* This is the Windows Server fallback rule: when no subnet
1669 * exists and we have only one site available then use it (it
1670 * is for sure the same as our server site). If more sites do
1671 * exist then we don't know which one to use and set the site
1672 * name to "". */
1673 cnt = samdb_search_count(ldb, sites_container_dn,
1674 "(objectClass=site)");
1675 if (cnt == 1) {
1676 site_name = samdb_server_site_name(ldb, mem_ctx);
1677 } else {
1678 site_name = talloc_strdup(mem_ctx, "");
1680 l_subnet_name = NULL;
1683 if (subnet_name != NULL) {
1684 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1687 talloc_free(sites_container_dn);
1688 talloc_free(subnets_dn);
1689 talloc_free(res);
1691 return site_name;
1695 work out if we are the PDC for the domain of the current open ldb
1697 bool samdb_is_pdc(struct ldb_context *ldb)
1699 const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1700 int ret;
1701 struct ldb_result *dom_res;
1702 TALLOC_CTX *tmp_ctx;
1703 bool is_pdc;
1704 struct ldb_dn *pdc;
1706 tmp_ctx = talloc_new(ldb);
1707 if (tmp_ctx == NULL) {
1708 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1709 return false;
1712 ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1713 if (ret) {
1714 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n",
1715 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
1716 ldb_errstring(ldb)));
1717 goto failed;
1719 if (dom_res->count != 1) {
1720 goto failed;
1723 pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1725 if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1726 is_pdc = true;
1727 } else {
1728 is_pdc = false;
1731 talloc_free(tmp_ctx);
1733 return is_pdc;
1735 failed:
1736 DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1737 talloc_free(tmp_ctx);
1738 return false;
1742 work out if we are a Global Catalog server for the domain of the current open ldb
1744 bool samdb_is_gc(struct ldb_context *ldb)
1746 const char *attrs[] = { "options", NULL };
1747 int ret, options;
1748 struct ldb_result *res;
1749 TALLOC_CTX *tmp_ctx;
1751 tmp_ctx = talloc_new(ldb);
1752 if (tmp_ctx == NULL) {
1753 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1754 return false;
1757 /* Query cn=ntds settings,.... */
1758 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1759 if (ret) {
1760 talloc_free(tmp_ctx);
1761 return false;
1763 if (res->count != 1) {
1764 talloc_free(tmp_ctx);
1765 return false;
1768 options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1769 talloc_free(tmp_ctx);
1771 /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1772 if (options & 0x000000001) {
1773 return true;
1775 return false;
1778 /* Find a domain object in the parents of a particular DN. */
1779 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1780 struct ldb_dn **parent_dn, const char **errstring)
1782 TALLOC_CTX *local_ctx;
1783 struct ldb_dn *sdn = dn;
1784 struct ldb_result *res = NULL;
1785 int ret = 0;
1786 const char *attrs[] = { NULL };
1788 local_ctx = talloc_new(mem_ctx);
1789 if (local_ctx == NULL) return LDB_ERR_OPERATIONS_ERROR;
1791 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1792 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1793 "(|(objectClass=domain)(objectClass=builtinDomain))");
1794 if (ret == LDB_SUCCESS) {
1795 if (res->count == 1) {
1796 break;
1798 } else {
1799 break;
1803 if (ret != LDB_SUCCESS) {
1804 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1805 ldb_dn_get_linearized(dn),
1806 ldb_dn_get_linearized(sdn),
1807 ldb_errstring(ldb));
1808 talloc_free(local_ctx);
1809 return ret;
1811 if (res->count != 1) {
1812 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1813 ldb_dn_get_linearized(dn));
1814 DEBUG(0,(__location__ ": %s\n", *errstring));
1815 talloc_free(local_ctx);
1816 return LDB_ERR_CONSTRAINT_VIOLATION;
1819 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1820 talloc_free(local_ctx);
1821 return ret;
1826 * Performs checks on a user password (plaintext UNIX format - attribute
1827 * "password"). The remaining parameters have to be extracted from the domain
1828 * object in the AD.
1830 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1832 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1833 const uint32_t pwdProperties,
1834 const uint32_t minPwdLength)
1836 /* checks if the "minPwdLength" property is satisfied */
1837 if (minPwdLength > password->length)
1838 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1840 /* checks the password complexity */
1841 if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1842 && (password->data != NULL)
1843 && (!check_password_quality((const char *) password->data)))
1844 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1846 return SAMR_VALIDATION_STATUS_SUCCESS;
1850 * Sets the user password using plaintext UTF16 (attribute "new_password") or
1851 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1852 * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1853 * gives some more informations if the changed failed.
1855 * The caller should have a LDB transaction wrapping this.
1857 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
1858 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1859 * NT_STATUS_PASSWORD_RESTRICTION
1861 NTSTATUS samdb_set_password(struct ldb_context *ctx, TALLOC_CTX *mem_ctx,
1862 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1863 struct ldb_message *mod,
1864 const DATA_BLOB *new_password,
1865 struct samr_Password *param_lmNewHash,
1866 struct samr_Password *param_ntNewHash,
1867 bool user_change,
1868 enum samPwdChangeReason *reject_reason,
1869 struct samr_DomInfo1 **_dominfo)
1871 const char * const user_attrs[] = { "userAccountControl",
1872 "lmPwdHistory",
1873 "ntPwdHistory",
1874 "dBCSPwd", "unicodePwd",
1875 "objectSid",
1876 "pwdLastSet", NULL };
1877 const char * const domain_attrs[] = { "minPwdLength", "pwdProperties",
1878 "pwdHistoryLength",
1879 "maxPwdAge", "minPwdAge", NULL };
1880 NTTIME pwdLastSet;
1881 uint32_t minPwdLength, pwdProperties, pwdHistoryLength;
1882 int64_t maxPwdAge, minPwdAge;
1883 uint32_t userAccountControl;
1884 struct samr_Password *sambaLMPwdHistory, *sambaNTPwdHistory,
1885 *lmPwdHash, *ntPwdHash, *lmNewHash, *ntNewHash;
1886 struct samr_Password local_lmNewHash, local_ntNewHash;
1887 int sambaLMPwdHistory_len, sambaNTPwdHistory_len;
1888 struct dom_sid *domain_sid;
1889 struct ldb_message **res;
1890 bool restrictions;
1891 int count;
1892 time_t now = time(NULL);
1893 NTTIME now_nt;
1894 unsigned int i;
1896 /* we need to know the time to compute password age */
1897 unix_to_nt_time(&now_nt, now);
1899 /* pull all the user parameters */
1900 count = gendb_search_dn(ctx, mem_ctx, user_dn, &res, user_attrs);
1901 if (count != 1) {
1902 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1904 userAccountControl = samdb_result_uint(res[0], "userAccountControl", 0);
1905 sambaLMPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1906 "lmPwdHistory", &sambaLMPwdHistory);
1907 sambaNTPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1908 "ntPwdHistory", &sambaNTPwdHistory);
1909 lmPwdHash = samdb_result_hash(mem_ctx, res[0], "dBCSPwd");
1910 ntPwdHash = samdb_result_hash(mem_ctx, res[0], "unicodePwd");
1911 pwdLastSet = samdb_result_uint64(res[0], "pwdLastSet", 0);
1913 /* Copy parameters */
1914 lmNewHash = param_lmNewHash;
1915 ntNewHash = param_ntNewHash;
1917 /* Only non-trust accounts have restrictions (possibly this
1918 * test is the wrong way around, but I like to be restrictive
1919 * if possible */
1920 restrictions = !(userAccountControl & (UF_INTERDOMAIN_TRUST_ACCOUNT
1921 |UF_WORKSTATION_TRUST_ACCOUNT
1922 |UF_SERVER_TRUST_ACCOUNT));
1924 if (domain_dn != NULL) {
1925 /* pull the domain parameters */
1926 count = gendb_search_dn(ctx, mem_ctx, domain_dn, &res,
1927 domain_attrs);
1928 if (count != 1) {
1929 DEBUG(2, ("samdb_set_password: Domain DN %s is invalid, for user %s\n",
1930 ldb_dn_get_linearized(domain_dn),
1931 ldb_dn_get_linearized(user_dn)));
1932 return NT_STATUS_NO_SUCH_DOMAIN;
1934 } else {
1935 /* work out the domain sid, and pull the domain from there */
1936 domain_sid = samdb_result_sid_prefix(mem_ctx, res[0],
1937 "objectSid");
1938 if (domain_sid == NULL) {
1939 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1942 count = gendb_search(ctx, mem_ctx, NULL, &res, domain_attrs,
1943 "(objectSid=%s)",
1944 ldap_encode_ndr_dom_sid(mem_ctx, domain_sid));
1945 if (count != 1) {
1946 DEBUG(2, ("samdb_set_password: Could not find domain to match SID: %s, for user %s\n",
1947 dom_sid_string(mem_ctx, domain_sid),
1948 ldb_dn_get_linearized(user_dn)));
1949 return NT_STATUS_NO_SUCH_DOMAIN;
1953 minPwdLength = samdb_result_uint(res[0], "minPwdLength", 0);
1954 pwdProperties = samdb_result_uint(res[0], "pwdProperties", 0);
1955 pwdHistoryLength = samdb_result_uint(res[0], "pwdHistoryLength", 0);
1956 maxPwdAge = samdb_result_int64(res[0], "maxPwdAge", 0);
1957 minPwdAge = samdb_result_int64(res[0], "minPwdAge", 0);
1959 if ((userAccountControl & UF_PASSWD_NOTREQD) != 0) {
1960 /* see [MS-ADTS] 2.2.15 */
1961 minPwdLength = 0;
1964 if (_dominfo != NULL) {
1965 struct samr_DomInfo1 *dominfo;
1966 /* on failure we need to fill in the reject reasons */
1967 dominfo = talloc(mem_ctx, struct samr_DomInfo1);
1968 if (dominfo == NULL) {
1969 return NT_STATUS_NO_MEMORY;
1971 dominfo->min_password_length = minPwdLength;
1972 dominfo->password_properties = pwdProperties;
1973 dominfo->password_history_length = pwdHistoryLength;
1974 dominfo->max_password_age = maxPwdAge;
1975 dominfo->min_password_age = minPwdAge;
1976 *_dominfo = dominfo;
1979 if ((restrictions != 0) && (new_password != 0)) {
1980 char *new_pass;
1982 /* checks if the "minPwdLength" property is satisfied */
1983 if ((restrictions != 0)
1984 && (minPwdLength > utf16_len_n(
1985 new_password->data, new_password->length)/2)) {
1986 if (reject_reason) {
1987 *reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
1989 return NT_STATUS_PASSWORD_RESTRICTION;
1992 /* Create the NT hash */
1993 mdfour(local_ntNewHash.hash, new_password->data,
1994 new_password->length);
1996 ntNewHash = &local_ntNewHash;
1998 /* Only check complexity if we can convert it at all. Assuming unconvertable passwords are 'strong' */
1999 if (convert_string_talloc_convenience(mem_ctx,
2000 lp_iconv_convenience(ldb_get_opaque(ctx, "loadparm")),
2001 CH_UTF16, CH_UNIX,
2002 new_password->data, new_password->length,
2003 (void **)&new_pass, NULL, false)) {
2005 /* checks the password complexity */
2006 if ((restrictions != 0)
2007 && ((pwdProperties
2008 & DOMAIN_PASSWORD_COMPLEX) != 0)
2009 && (!check_password_quality(new_pass))) {
2010 if (reject_reason) {
2011 *reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
2013 return NT_STATUS_PASSWORD_RESTRICTION;
2016 /* compute the new lm hashes (for checking history - case insenitivly!) */
2017 if (E_deshash(new_pass, local_lmNewHash.hash)) {
2018 lmNewHash = &local_lmNewHash;
2023 if ((restrictions != 0) && user_change) {
2024 /* are all password changes disallowed? */
2025 if ((pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) != 0) {
2026 if (reject_reason) {
2027 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2029 return NT_STATUS_PASSWORD_RESTRICTION;
2032 /* can this user change the password? */
2033 if ((userAccountControl & UF_PASSWD_CANT_CHANGE) != 0) {
2034 if (reject_reason) {
2035 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2037 return NT_STATUS_PASSWORD_RESTRICTION;
2040 /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
2041 if (pwdLastSet - minPwdAge > now_nt) {
2042 if (reject_reason) {
2043 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2045 return NT_STATUS_PASSWORD_RESTRICTION;
2048 /* check the immediately past password */
2049 if (pwdHistoryLength > 0) {
2050 if (lmNewHash && lmPwdHash && memcmp(lmNewHash->hash,
2051 lmPwdHash->hash, 16) == 0) {
2052 if (reject_reason) {
2053 *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
2055 return NT_STATUS_PASSWORD_RESTRICTION;
2057 if (ntNewHash && ntPwdHash && memcmp(ntNewHash->hash,
2058 ntPwdHash->hash, 16) == 0) {
2059 if (reject_reason) {
2060 *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
2062 return NT_STATUS_PASSWORD_RESTRICTION;
2066 /* check the password history */
2067 sambaLMPwdHistory_len = MIN(sambaLMPwdHistory_len,
2068 pwdHistoryLength);
2069 sambaNTPwdHistory_len = MIN(sambaNTPwdHistory_len,
2070 pwdHistoryLength);
2072 for (i=0; lmNewHash && i<sambaLMPwdHistory_len;i++) {
2073 if (memcmp(lmNewHash->hash, sambaLMPwdHistory[i].hash,
2074 16) == 0) {
2075 if (reject_reason) {
2076 *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
2078 return NT_STATUS_PASSWORD_RESTRICTION;
2081 for (i=0; ntNewHash && i<sambaNTPwdHistory_len;i++) {
2082 if (memcmp(ntNewHash->hash, sambaNTPwdHistory[i].hash,
2083 16) == 0) {
2084 if (reject_reason) {
2085 *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
2087 return NT_STATUS_PASSWORD_RESTRICTION;
2092 #define CHECK_RET(x) do { if (x != 0) return NT_STATUS_NO_MEMORY; } while(0)
2094 /* the password is acceptable. Start forming the new fields */
2095 if (new_password != NULL) {
2096 /* if we know the cleartext UTF16 password, then set it.
2097 * Modules in ldb will set all the appropriate
2098 * hashes */
2099 CHECK_RET(ldb_msg_add_value(mod, "clearTextPassword", new_password, NULL));
2100 } else {
2101 /* we don't have the cleartext, so set what we have of the
2102 * hashes */
2104 if (lmNewHash) {
2105 CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "dBCSPwd", lmNewHash));
2108 if (ntNewHash) {
2109 CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "unicodePwd", ntNewHash));
2113 if (reject_reason) {
2114 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2116 return NT_STATUS_OK;
2121 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2122 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2123 * as parameter if it's a user change or not ("userChange"). The "rejectReason"
2124 * gives some more informations if the changed failed.
2126 * This wrapper function for "samdb_set_password" takes a SID as input rather
2127 * than a user DN.
2129 * This call encapsulates a new LDB transaction for changing the password;
2130 * therefore the user hasn't to start a new one.
2132 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2133 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2134 * NT_STATUS_PASSWORD_RESTRICTION
2136 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2137 const struct dom_sid *user_sid,
2138 const DATA_BLOB *new_password,
2139 struct samr_Password *lmNewHash,
2140 struct samr_Password *ntNewHash,
2141 bool user_change,
2142 enum samPwdChangeReason *reject_reason,
2143 struct samr_DomInfo1 **_dominfo)
2145 NTSTATUS nt_status;
2146 struct ldb_dn *user_dn;
2147 struct ldb_message *msg;
2148 int ret;
2150 ret = ldb_transaction_start(ldb);
2151 if (ret != LDB_SUCCESS) {
2152 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2153 return NT_STATUS_TRANSACTION_ABORTED;
2156 user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2157 "(&(objectSid=%s)(objectClass=user))",
2158 ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2159 if (!user_dn) {
2160 ldb_transaction_cancel(ldb);
2161 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2162 dom_sid_string(mem_ctx, user_sid)));
2163 return NT_STATUS_NO_SUCH_USER;
2166 msg = ldb_msg_new(mem_ctx);
2167 if (msg == NULL) {
2168 ldb_transaction_cancel(ldb);
2169 talloc_free(user_dn);
2170 return NT_STATUS_NO_MEMORY;
2173 msg->dn = ldb_dn_copy(msg, user_dn);
2174 if (!msg->dn) {
2175 ldb_transaction_cancel(ldb);
2176 talloc_free(user_dn);
2177 talloc_free(msg);
2178 return NT_STATUS_NO_MEMORY;
2181 nt_status = samdb_set_password(ldb, mem_ctx,
2182 user_dn, NULL,
2183 msg, new_password,
2184 lmNewHash, ntNewHash,
2185 user_change,
2186 reject_reason, _dominfo);
2187 if (!NT_STATUS_IS_OK(nt_status)) {
2188 ldb_transaction_cancel(ldb);
2189 talloc_free(user_dn);
2190 talloc_free(msg);
2191 return nt_status;
2194 /* modify the samdb record */
2195 ret = dsdb_replace(ldb, msg, 0);
2196 if (ret != LDB_SUCCESS) {
2197 ldb_transaction_cancel(ldb);
2198 talloc_free(user_dn);
2199 talloc_free(msg);
2200 return NT_STATUS_ACCESS_DENIED;
2203 talloc_free(msg);
2205 ret = ldb_transaction_commit(ldb);
2206 if (ret != LDB_SUCCESS) {
2207 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2208 ldb_dn_get_linearized(user_dn),
2209 ldb_errstring(ldb)));
2210 talloc_free(user_dn);
2211 return NT_STATUS_TRANSACTION_ABORTED;
2214 talloc_free(user_dn);
2215 return NT_STATUS_OK;
2219 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
2220 struct dom_sid *sid, struct ldb_dn **ret_dn)
2222 struct ldb_message *msg;
2223 struct ldb_dn *basedn;
2224 char *sidstr;
2225 int ret;
2227 sidstr = dom_sid_string(mem_ctx, sid);
2228 NT_STATUS_HAVE_NO_MEMORY(sidstr);
2230 /* We might have to create a ForeignSecurityPrincipal, even if this user
2231 * is in our own domain */
2233 msg = ldb_msg_new(sidstr);
2234 if (msg == NULL) {
2235 talloc_free(sidstr);
2236 return NT_STATUS_NO_MEMORY;
2239 ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2240 ldb_get_default_basedn(sam_ctx),
2241 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2242 &basedn);
2243 if (ret != LDB_SUCCESS) {
2244 DEBUG(0, ("Failed to find DN for "
2245 "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2246 talloc_free(sidstr);
2247 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2250 /* add core elements to the ldb_message for the alias */
2251 msg->dn = basedn;
2252 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2253 talloc_free(sidstr);
2254 return NT_STATUS_NO_MEMORY;
2257 samdb_msg_add_string(sam_ctx, msg, msg,
2258 "objectClass",
2259 "foreignSecurityPrincipal");
2261 /* create the alias */
2262 ret = ldb_add(sam_ctx, msg);
2263 if (ret != LDB_SUCCESS) {
2264 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2265 "record %s: %s\n",
2266 ldb_dn_get_linearized(msg->dn),
2267 ldb_errstring(sam_ctx)));
2268 talloc_free(sidstr);
2269 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2272 *ret_dn = talloc_steal(mem_ctx, msg->dn);
2273 talloc_free(sidstr);
2275 return NT_STATUS_OK;
2280 Find the DN of a domain, assuming it to be a dotted.dns name
2283 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
2285 unsigned int i;
2286 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2287 const char *binary_encoded;
2288 const char **split_realm;
2289 struct ldb_dn *dn;
2291 if (!tmp_ctx) {
2292 return NULL;
2295 split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2296 if (!split_realm) {
2297 talloc_free(tmp_ctx);
2298 return NULL;
2300 dn = ldb_dn_new(mem_ctx, ldb, NULL);
2301 for (i=0; split_realm[i]; i++) {
2302 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2303 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2304 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2305 binary_encoded, ldb_dn_get_linearized(dn)));
2306 talloc_free(tmp_ctx);
2307 return NULL;
2310 if (!ldb_dn_validate(dn)) {
2311 DEBUG(2, ("Failed to validated DN %s\n",
2312 ldb_dn_get_linearized(dn)));
2313 talloc_free(tmp_ctx);
2314 return NULL;
2316 talloc_free(tmp_ctx);
2317 return dn;
2321 Find the DN of a domain, be it the netbios or DNS name
2323 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2324 const char *domain_name)
2326 const char * const domain_ref_attrs[] = {
2327 "ncName", NULL
2329 const char * const domain_ref2_attrs[] = {
2330 NULL
2332 struct ldb_result *res_domain_ref;
2333 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2334 /* find the domain's DN */
2335 int ret_domain = ldb_search(ldb, mem_ctx,
2336 &res_domain_ref,
2337 samdb_partitions_dn(ldb, mem_ctx),
2338 LDB_SCOPE_ONELEVEL,
2339 domain_ref_attrs,
2340 "(&(nETBIOSName=%s)(objectclass=crossRef))",
2341 escaped_domain);
2342 if (ret_domain != 0) {
2343 return NULL;
2346 if (res_domain_ref->count == 0) {
2347 ret_domain = ldb_search(ldb, mem_ctx,
2348 &res_domain_ref,
2349 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2350 LDB_SCOPE_BASE,
2351 domain_ref2_attrs,
2352 "(objectclass=domain)");
2353 if (ret_domain != 0) {
2354 return NULL;
2357 if (res_domain_ref->count == 1) {
2358 return res_domain_ref->msgs[0]->dn;
2360 return NULL;
2363 if (res_domain_ref->count > 1) {
2364 DEBUG(0,("Found %d records matching domain [%s]\n",
2365 ret_domain, domain_name));
2366 return NULL;
2369 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2375 use a GUID to find a DN
2377 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
2378 TALLOC_CTX *mem_ctx,
2379 const struct GUID *guid, struct ldb_dn **dn)
2381 int ret;
2382 struct ldb_result *res;
2383 const char *attrs[] = { NULL };
2384 char *guid_str = GUID_string(mem_ctx, guid);
2386 if (!guid_str) {
2387 return LDB_ERR_OPERATIONS_ERROR;
2390 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2391 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2392 DSDB_SEARCH_SHOW_EXTENDED_DN |
2393 DSDB_SEARCH_ONE_ONLY,
2394 "objectGUID=%s", guid_str);
2395 talloc_free(guid_str);
2396 if (ret != LDB_SUCCESS) {
2397 return ret;
2400 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2401 talloc_free(res);
2403 return LDB_SUCCESS;
2407 use a DN to find a GUID with a given attribute name
2409 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2410 struct ldb_dn *dn, const char *attribute,
2411 struct GUID *guid)
2413 int ret;
2414 struct ldb_result *res;
2415 const char *attrs[2];
2416 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2418 attrs[0] = attribute;
2419 attrs[1] = NULL;
2421 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2422 if (ret != LDB_SUCCESS) {
2423 talloc_free(tmp_ctx);
2424 return ret;
2426 if (res->count < 1) {
2427 talloc_free(tmp_ctx);
2428 return LDB_ERR_NO_SUCH_OBJECT;
2430 *guid = samdb_result_guid(res->msgs[0], attribute);
2431 talloc_free(tmp_ctx);
2432 return LDB_SUCCESS;
2436 use a DN to find a GUID
2438 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2439 struct ldb_dn *dn, struct GUID *guid)
2441 return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2447 adds the given GUID to the given ldb_message. This value is added
2448 for the given attr_name (may be either "objectGUID" or "parentGUID").
2450 int dsdb_msg_add_guid(struct ldb_message *msg,
2451 struct GUID *guid,
2452 const char *attr_name)
2454 int ret;
2455 struct ldb_val v;
2456 NTSTATUS status;
2457 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
2459 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2460 if (!NT_STATUS_IS_OK(status)) {
2461 ret = LDB_ERR_OPERATIONS_ERROR;
2462 goto done;
2465 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2466 if (ret != LDB_SUCCESS) {
2467 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2468 attr_name));
2469 goto done;
2472 ret = LDB_SUCCESS;
2474 done:
2475 talloc_free(tmp_ctx);
2476 return ret;
2482 use a DN to find a SID
2484 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
2485 struct ldb_dn *dn, struct dom_sid *sid)
2487 int ret;
2488 struct ldb_result *res;
2489 const char *attrs[] = { "objectSID", NULL };
2490 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2491 struct dom_sid *s;
2493 ZERO_STRUCTP(sid);
2495 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2496 if (ret != LDB_SUCCESS) {
2497 talloc_free(tmp_ctx);
2498 return ret;
2500 if (res->count < 1) {
2501 talloc_free(tmp_ctx);
2502 return LDB_ERR_NO_SUCH_OBJECT;
2504 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2505 if (s == NULL) {
2506 talloc_free(tmp_ctx);
2507 return LDB_ERR_NO_SUCH_OBJECT;
2509 *sid = *s;
2510 talloc_free(tmp_ctx);
2511 return LDB_SUCCESS;
2516 load a repsFromTo blob list for a given partition GUID
2517 attr must be "repsFrom" or "repsTo"
2519 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2520 const char *attr, struct repsFromToBlob **r, uint32_t *count)
2522 const char *attrs[] = { attr, NULL };
2523 struct ldb_result *res = NULL;
2524 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2525 unsigned int i;
2526 struct ldb_message_element *el;
2528 *r = NULL;
2529 *count = 0;
2531 if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2532 res->count < 1) {
2533 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2534 talloc_free(tmp_ctx);
2535 return WERR_DS_DRA_INTERNAL_ERROR;
2538 el = ldb_msg_find_element(res->msgs[0], attr);
2539 if (el == NULL) {
2540 /* it's OK to be empty */
2541 talloc_free(tmp_ctx);
2542 return WERR_OK;
2545 *count = el->num_values;
2546 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2547 if (*r == NULL) {
2548 talloc_free(tmp_ctx);
2549 return WERR_DS_DRA_INTERNAL_ERROR;
2552 for (i=0; i<(*count); i++) {
2553 enum ndr_err_code ndr_err;
2554 ndr_err = ndr_pull_struct_blob(&el->values[i],
2555 mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2556 &(*r)[i],
2557 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2558 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2559 talloc_free(tmp_ctx);
2560 return WERR_DS_DRA_INTERNAL_ERROR;
2564 talloc_free(tmp_ctx);
2566 return WERR_OK;
2570 save the repsFromTo blob list for a given partition GUID
2571 attr must be "repsFrom" or "repsTo"
2573 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2574 const char *attr, struct repsFromToBlob *r, uint32_t count)
2576 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2577 struct ldb_message *msg;
2578 struct ldb_message_element *el;
2579 unsigned int i;
2581 msg = ldb_msg_new(tmp_ctx);
2582 msg->dn = dn;
2583 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2584 goto failed;
2587 el->values = talloc_array(msg, struct ldb_val, count);
2588 if (!el->values) {
2589 goto failed;
2592 for (i=0; i<count; i++) {
2593 struct ldb_val v;
2594 enum ndr_err_code ndr_err;
2596 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2597 &r[i],
2598 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2599 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2600 goto failed;
2603 el->num_values++;
2604 el->values[i] = v;
2607 if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2608 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2609 goto failed;
2612 talloc_free(tmp_ctx);
2614 return WERR_OK;
2616 failed:
2617 talloc_free(tmp_ctx);
2618 return WERR_DS_DRA_INTERNAL_ERROR;
2623 load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2624 object for a partition
2626 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2627 uint64_t *uSN, uint64_t *urgent_uSN)
2629 struct ldb_request *req;
2630 int ret;
2631 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2632 struct dsdb_control_current_partition *p_ctrl;
2633 struct ldb_result *res;
2635 res = talloc_zero(tmp_ctx, struct ldb_result);
2636 if (!res) {
2637 talloc_free(tmp_ctx);
2638 return LDB_ERR_OPERATIONS_ERROR;
2641 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2642 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2643 LDB_SCOPE_BASE,
2644 NULL, NULL,
2645 NULL,
2646 res, ldb_search_default_callback,
2647 NULL);
2648 if (ret != LDB_SUCCESS) {
2649 talloc_free(tmp_ctx);
2650 return ret;
2653 p_ctrl = talloc(req, struct dsdb_control_current_partition);
2654 if (p_ctrl == NULL) {
2655 talloc_free(res);
2656 return LDB_ERR_OPERATIONS_ERROR;
2658 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2659 p_ctrl->dn = dn;
2662 ret = ldb_request_add_control(req,
2663 DSDB_CONTROL_CURRENT_PARTITION_OID,
2664 false, p_ctrl);
2665 if (ret != LDB_SUCCESS) {
2666 talloc_free(tmp_ctx);
2667 return ret;
2670 /* Run the new request */
2671 ret = ldb_request(ldb, req);
2673 if (ret == LDB_SUCCESS) {
2674 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2677 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2678 /* it hasn't been created yet, which means
2679 an implicit value of zero */
2680 *uSN = 0;
2681 talloc_free(tmp_ctx);
2682 return LDB_SUCCESS;
2685 if (ret != LDB_SUCCESS) {
2686 talloc_free(tmp_ctx);
2687 return ret;
2690 if (res->count < 1) {
2691 *uSN = 0;
2692 if (urgent_uSN) {
2693 *urgent_uSN = 0;
2695 } else {
2696 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2697 if (urgent_uSN) {
2698 *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2702 talloc_free(tmp_ctx);
2704 return LDB_SUCCESS;
2707 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2708 const struct drsuapi_DsReplicaCursor2 *c2)
2710 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2713 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2714 const struct drsuapi_DsReplicaCursor *c2)
2716 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2721 see if a computer identified by its invocationId is a RODC
2723 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *invocationId, bool *is_rodc)
2725 /* 1) find the DN for this servers NTDSDSA object
2726 2) search for the msDS-isRODC attribute
2727 3) if not present then not a RODC
2728 4) if present and TRUE then is a RODC
2730 struct ldb_dn *config_dn;
2731 const char *attrs[] = { "msDS-isRODC", NULL };
2732 int ret;
2733 struct ldb_result *res;
2734 TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
2736 config_dn = ldb_get_config_basedn(sam_ctx);
2737 if (!config_dn) {
2738 talloc_free(tmp_ctx);
2739 return LDB_ERR_OPERATIONS_ERROR;
2742 ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
2743 DSDB_SEARCH_ONE_ONLY, "invocationID=%s", GUID_string(tmp_ctx, invocationId));
2744 if (ret != LDB_SUCCESS) {
2745 talloc_free(tmp_ctx);
2746 return ret;
2749 ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
2750 *is_rodc = (ret == 1);
2752 talloc_free(tmp_ctx);
2753 return LDB_SUCCESS;
2758 see if we are a RODC
2760 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
2762 const struct GUID *invocationId;
2763 invocationId = samdb_ntds_invocation_id(sam_ctx);
2764 if (!invocationId) {
2765 return LDB_ERR_OPERATIONS_ERROR;
2767 return samdb_is_rodc(sam_ctx, invocationId, am_rodc);
2773 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
2775 flags are DS_NTDS_OPTION_*
2777 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2779 TALLOC_CTX *tmp_ctx;
2780 const char *attrs[] = { "options", NULL };
2781 int ret;
2782 struct ldb_result *res;
2784 tmp_ctx = talloc_new(ldb);
2785 if (tmp_ctx == NULL) {
2786 goto failed;
2789 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2790 if (ret) {
2791 goto failed;
2794 if (res->count != 1) {
2795 goto failed;
2798 *options = samdb_result_uint(res->msgs[0], "options", 0);
2800 talloc_free(tmp_ctx);
2802 return LDB_SUCCESS;
2804 failed:
2805 DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
2806 talloc_free(tmp_ctx);
2807 return LDB_ERR_NO_SUCH_OBJECT;
2810 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
2812 const char *attrs[] = { "objectCategory", NULL };
2813 int ret;
2814 struct ldb_result *res;
2816 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2817 if (ret) {
2818 goto failed;
2821 if (res->count != 1) {
2822 goto failed;
2825 return samdb_result_string(res->msgs[0], "objectCategory", NULL);
2827 failed:
2828 DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
2829 return NULL;
2833 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
2834 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
2836 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
2838 char **tokens, *ret;
2839 size_t i;
2841 tokens = str_list_make(mem_ctx, cn, " -_");
2842 if (tokens == NULL)
2843 return NULL;
2845 /* "tolower()" and "toupper()" should also work properly on 0x00 */
2846 tokens[0][0] = tolower(tokens[0][0]);
2847 for (i = 1; i < str_list_length((const char **)tokens); i++)
2848 tokens[i][0] = toupper(tokens[i][0]);
2850 ret = talloc_strdup(mem_ctx, tokens[0]);
2851 for (i = 1; i < str_list_length((const char **)tokens); i++)
2852 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
2854 talloc_free(tokens);
2856 return ret;
2860 return domain functional level
2861 returns DS_DOMAIN_FUNCTION_*
2863 int dsdb_functional_level(struct ldb_context *ldb)
2865 int *domainFunctionality =
2866 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
2867 if (!domainFunctionality) {
2868 DEBUG(0,(__location__ ": WARNING: domainFunctionality not setup\n"));
2869 return DS_DOMAIN_FUNCTION_2000;
2871 return *domainFunctionality;
2875 set a GUID in an extended DN structure
2877 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
2879 struct ldb_val v;
2880 NTSTATUS status;
2881 int ret;
2883 status = GUID_to_ndr_blob(guid, dn, &v);
2884 if (!NT_STATUS_IS_OK(status)) {
2885 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
2888 ret = ldb_dn_set_extended_component(dn, component_name, &v);
2889 data_blob_free(&v);
2890 return ret;
2894 return a GUID from a extended DN structure
2896 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
2898 const struct ldb_val *v;
2900 v = ldb_dn_get_extended_component(dn, component_name);
2901 if (v == NULL) {
2902 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2905 return GUID_from_ndr_blob(v, guid);
2909 return a uint64_t from a extended DN structure
2911 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
2913 const struct ldb_val *v;
2914 char *s;
2916 v = ldb_dn_get_extended_component(dn, component_name);
2917 if (v == NULL) {
2918 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2920 s = talloc_strndup(dn, (const char *)v->data, v->length);
2921 NT_STATUS_HAVE_NO_MEMORY(s);
2923 *val = strtoull(s, NULL, 0);
2925 talloc_free(s);
2926 return NT_STATUS_OK;
2930 return a NTTIME from a extended DN structure
2932 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
2934 return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
2938 return a uint32_t from a extended DN structure
2940 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
2942 const struct ldb_val *v;
2943 char *s;
2945 v = ldb_dn_get_extended_component(dn, component_name);
2946 if (v == NULL) {
2947 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2950 s = talloc_strndup(dn, (const char *)v->data, v->length);
2951 NT_STATUS_HAVE_NO_MEMORY(s);
2953 *val = strtoul(s, NULL, 0);
2955 talloc_free(s);
2956 return NT_STATUS_OK;
2960 return a dom_sid from a extended DN structure
2962 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
2964 const struct ldb_val *sid_blob;
2965 struct TALLOC_CTX *tmp_ctx;
2966 enum ndr_err_code ndr_err;
2968 sid_blob = ldb_dn_get_extended_component(dn, "SID");
2969 if (!sid_blob) {
2970 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2973 tmp_ctx = talloc_new(NULL);
2975 ndr_err = ndr_pull_struct_blob_all(sid_blob, tmp_ctx, NULL, sid,
2976 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
2977 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2978 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
2979 talloc_free(tmp_ctx);
2980 return status;
2983 talloc_free(tmp_ctx);
2984 return NT_STATUS_OK;
2989 return RMD_FLAGS directly from a ldb_dn
2990 returns 0 if not found
2992 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
2994 const struct ldb_val *v;
2995 char buf[32];
2996 v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
2997 if (!v || v->length > sizeof(buf)-1) return 0;
2998 strncpy(buf, (const char *)v->data, v->length);
2999 buf[v->length] = 0;
3000 return strtoul(buf, NULL, 10);
3004 return RMD_FLAGS directly from a ldb_val for a DN
3005 returns 0 if RMD_FLAGS is not found
3007 uint32_t dsdb_dn_val_rmd_flags(struct ldb_val *val)
3009 const char *p;
3010 uint32_t flags;
3011 char *end;
3013 if (val->length < 13) {
3014 return 0;
3016 p = memmem(val->data, val->length-2, "<RMD_FLAGS=", 11);
3017 if (!p) {
3018 return 0;
3020 flags = strtoul(p+11, &end, 10);
3021 if (!end || *end != '>') {
3022 /* it must end in a > */
3023 return 0;
3025 return flags;
3029 return true if a ldb_val containing a DN in storage form is deleted
3031 bool dsdb_dn_is_deleted_val(struct ldb_val *val)
3033 return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3037 return true if a ldb_val containing a DN in storage form is
3038 in the upgraded w2k3 linked attribute format
3040 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3042 return memmem(val->data, val->length, "<RMD_ADDTIME=", 13) != NULL;
3046 return a DN for a wellknown GUID
3048 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3049 struct ldb_dn *nc_root, const char *wk_guid,
3050 struct ldb_dn **wkguid_dn)
3052 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3053 const char *attrs[] = { NULL };
3054 int ret;
3055 struct ldb_dn *dn;
3056 struct ldb_result *res;
3058 /* construct the magic WKGUID DN */
3059 dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3060 wk_guid, ldb_dn_get_linearized(nc_root));
3061 if (!wkguid_dn) {
3062 talloc_free(tmp_ctx);
3063 return LDB_ERR_OPERATIONS_ERROR;
3066 ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
3067 if (ret != LDB_SUCCESS) {
3068 talloc_free(tmp_ctx);
3069 return ret;
3072 (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3073 talloc_free(tmp_ctx);
3074 return LDB_SUCCESS;
3078 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3080 return ldb_dn_compare(*dn1, *dn2);
3084 find a NC root given a DN within the NC
3086 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3087 struct ldb_dn **nc_root)
3089 const char *root_attrs[] = { "namingContexts", NULL };
3090 TALLOC_CTX *tmp_ctx;
3091 int ret;
3092 struct ldb_message_element *el;
3093 struct ldb_result *root_res;
3094 int i;
3095 struct ldb_dn **nc_dns;
3097 tmp_ctx = talloc_new(samdb);
3098 if (tmp_ctx == NULL) {
3099 return LDB_ERR_OPERATIONS_ERROR;
3102 ret = ldb_search(samdb, tmp_ctx, &root_res,
3103 ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3104 if (ret) {
3105 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3106 talloc_free(tmp_ctx);
3107 return ret;
3110 el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3111 if (!el) {
3112 DEBUG(1,("Finding namingContexts element in root_res failed: %s\n",
3113 ldb_errstring(samdb)));
3114 talloc_free(tmp_ctx);
3115 return LDB_ERR_NO_SUCH_ATTRIBUTE;
3118 nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3119 if (!nc_dns) {
3120 talloc_free(tmp_ctx);
3121 return LDB_ERR_OPERATIONS_ERROR;
3124 for (i=0; i<el->num_values; i++) {
3125 nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3126 if (nc_dns[i] == NULL) {
3127 talloc_free(tmp_ctx);
3128 return LDB_ERR_OPERATIONS_ERROR;
3132 TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3134 for (i=0; i<el->num_values; i++) {
3135 if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3136 (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3137 talloc_free(tmp_ctx);
3138 return LDB_SUCCESS;
3142 talloc_free(tmp_ctx);
3143 return LDB_ERR_NO_SUCH_OBJECT;
3148 find the deleted objects DN for any object, by looking for the NC
3149 root, then looking up the wellknown GUID
3151 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3152 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3153 struct ldb_dn **do_dn)
3155 struct ldb_dn *nc_root;
3156 int ret;
3158 ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3159 if (ret != LDB_SUCCESS) {
3160 return ret;
3163 ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3164 talloc_free(nc_root);
3165 return ret;
3169 return the tombstoneLifetime, in days
3171 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3173 struct ldb_dn *dn;
3174 dn = ldb_get_config_basedn(ldb);
3175 if (!dn) {
3176 return LDB_ERR_NO_SUCH_OBJECT;
3178 dn = ldb_dn_copy(ldb, dn);
3179 if (!dn) {
3180 return LDB_ERR_OPERATIONS_ERROR;
3182 /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3183 be a wellknown GUID for this */
3184 if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3185 talloc_free(dn);
3186 return LDB_ERR_OPERATIONS_ERROR;
3189 *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3190 talloc_free(dn);
3191 return LDB_SUCCESS;
3195 compare a ldb_val to a string case insensitively
3197 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3199 size_t len = strlen(s);
3200 int ret;
3201 if (len > v->length) return 1;
3202 ret = strncasecmp(s, (const char *)v->data, v->length);
3203 if (ret != 0) return ret;
3204 if (v->length > len && v->data[len] != 0) {
3205 return -1;
3207 return 0;
3212 load the UDV for a partition in v2 format
3213 The list is returned sorted, and with our local cursor added
3215 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3216 struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3218 static const char *attrs[] = { "replUpToDateVector", NULL };
3219 struct ldb_result *r;
3220 const struct ldb_val *ouv_value;
3221 unsigned int i;
3222 int ret;
3223 uint64_t highest_usn;
3224 const struct GUID *our_invocation_id;
3225 struct timeval now = timeval_current();
3227 ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3228 if (ret != LDB_SUCCESS) {
3229 return ret;
3232 ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3233 if (ouv_value) {
3234 enum ndr_err_code ndr_err;
3235 struct replUpToDateVectorBlob ouv;
3237 ndr_err = ndr_pull_struct_blob(ouv_value, r,
3238 lp_iconv_convenience(ldb_get_opaque(samdb, "loadparm")), &ouv,
3239 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3240 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3241 talloc_free(r);
3242 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3244 if (ouv.version != 2) {
3245 /* we always store as version 2, and
3246 * replUpToDateVector is not replicated
3248 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3251 *count = ouv.ctr.ctr2.count;
3252 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3253 } else {
3254 *count = 0;
3255 *cursors = NULL;
3258 talloc_free(r);
3260 our_invocation_id = samdb_ntds_invocation_id(samdb);
3261 if (!our_invocation_id) {
3262 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3263 talloc_free(*cursors);
3264 return LDB_ERR_OPERATIONS_ERROR;
3267 ret = dsdb_load_partition_usn(samdb, dn, &highest_usn, NULL);
3268 if (ret != LDB_SUCCESS) {
3269 /* nothing to add - this can happen after a vampire */
3270 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3271 return LDB_SUCCESS;
3274 for (i=0; i<*count; i++) {
3275 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3276 (*cursors)[i].highest_usn = highest_usn;
3277 (*cursors)[i].last_sync_success = timeval_to_nttime(&now);
3278 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3279 return LDB_SUCCESS;
3283 (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3284 if (! *cursors) {
3285 return LDB_ERR_OPERATIONS_ERROR;
3288 (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3289 (*cursors)[*count].highest_usn = highest_usn;
3290 (*cursors)[*count].last_sync_success = timeval_to_nttime(&now);
3291 (*count)++;
3293 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3295 return LDB_SUCCESS;
3299 load the UDV for a partition in version 1 format
3300 The list is returned sorted, and with our local cursor added
3302 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3303 struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3305 struct drsuapi_DsReplicaCursor2 *v2;
3306 unsigned int i;
3307 int ret;
3309 ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3310 if (ret != LDB_SUCCESS) {
3311 return ret;
3314 if (*count == 0) {
3315 talloc_free(v2);
3316 *cursors = NULL;
3317 return LDB_SUCCESS;
3320 *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3321 if (*cursors == NULL) {
3322 talloc_free(v2);
3323 return LDB_ERR_OPERATIONS_ERROR;
3326 for (i=0; i<*count; i++) {
3327 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3328 (*cursors)[i].highest_usn = v2[i].highest_usn;
3330 talloc_free(v2);
3331 return LDB_SUCCESS;
3335 add a set of controls to a ldb_request structure based on a set of
3336 flags. See util.h for a list of available flags
3338 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3340 int ret;
3341 if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3342 struct ldb_search_options_control *options;
3343 /* Using the phantom root control allows us to search all partitions */
3344 options = talloc(req, struct ldb_search_options_control);
3345 if (options == NULL) {
3346 return LDB_ERR_OPERATIONS_ERROR;
3348 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3350 ret = ldb_request_add_control(req,
3351 LDB_CONTROL_SEARCH_OPTIONS_OID,
3352 true, options);
3353 if (ret != LDB_SUCCESS) {
3354 return ret;
3358 if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3359 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3360 if (ret != LDB_SUCCESS) {
3361 return ret;
3365 if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3366 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, true, NULL);
3367 if (ret != LDB_SUCCESS) {
3368 return ret;
3372 if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3373 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3374 if (!extended_ctrl) {
3375 return LDB_ERR_OPERATIONS_ERROR;
3377 extended_ctrl->type = 1;
3379 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3380 if (ret != LDB_SUCCESS) {
3381 return ret;
3385 if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3386 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3387 if (ret != LDB_SUCCESS) {
3388 return ret;
3392 if (dsdb_flags & DSDB_MODIFY_RELAX) {
3393 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3394 if (ret != LDB_SUCCESS) {
3395 return ret;
3399 if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3400 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3401 if (ret != LDB_SUCCESS) {
3402 return ret;
3406 if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3407 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3408 if (ret != LDB_SUCCESS) {
3409 return ret;
3413 return LDB_SUCCESS;
3417 a modify with a set of controls
3419 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3420 uint32_t dsdb_flags)
3422 struct ldb_request *req;
3423 int ret;
3425 ret = ldb_build_mod_req(&req, ldb, ldb,
3426 message,
3427 NULL,
3428 NULL,
3429 ldb_op_default_callback,
3430 NULL);
3432 if (ret != LDB_SUCCESS) return ret;
3434 ret = dsdb_request_add_controls(req, dsdb_flags);
3435 if (ret != LDB_SUCCESS) {
3436 talloc_free(req);
3437 return ret;
3440 ret = dsdb_autotransaction_request(ldb, req);
3442 talloc_free(req);
3443 return ret;
3447 like dsdb_modify() but set all the element flags to
3448 LDB_FLAG_MOD_REPLACE
3450 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3452 unsigned int i;
3454 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3455 for (i=0;i<msg->num_elements;i++) {
3456 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3459 return dsdb_modify(ldb, msg, dsdb_flags);
3464 search for attrs on one DN, allowing for dsdb_flags controls
3466 int dsdb_search_dn(struct ldb_context *ldb,
3467 TALLOC_CTX *mem_ctx,
3468 struct ldb_result **_res,
3469 struct ldb_dn *basedn,
3470 const char * const *attrs,
3471 uint32_t dsdb_flags)
3473 int ret;
3474 struct ldb_request *req;
3475 struct ldb_result *res;
3477 res = talloc_zero(mem_ctx, struct ldb_result);
3478 if (!res) {
3479 return LDB_ERR_OPERATIONS_ERROR;
3482 ret = ldb_build_search_req(&req, ldb, res,
3483 basedn,
3484 LDB_SCOPE_BASE,
3485 NULL,
3486 attrs,
3487 NULL,
3488 res,
3489 ldb_search_default_callback,
3490 NULL);
3491 if (ret != LDB_SUCCESS) {
3492 talloc_free(res);
3493 return ret;
3496 ret = dsdb_request_add_controls(req, dsdb_flags);
3497 if (ret != LDB_SUCCESS) {
3498 talloc_free(res);
3499 return ret;
3502 ret = ldb_request(ldb, req);
3503 if (ret == LDB_SUCCESS) {
3504 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3507 talloc_free(req);
3508 if (ret != LDB_SUCCESS) {
3509 talloc_free(res);
3510 return ret;
3513 *_res = res;
3514 return LDB_SUCCESS;
3518 general search with dsdb_flags for controls
3520 int dsdb_search(struct ldb_context *ldb,
3521 TALLOC_CTX *mem_ctx,
3522 struct ldb_result **_res,
3523 struct ldb_dn *basedn,
3524 enum ldb_scope scope,
3525 const char * const *attrs,
3526 uint32_t dsdb_flags,
3527 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3529 int ret;
3530 struct ldb_request *req;
3531 struct ldb_result *res;
3532 va_list ap;
3533 char *expression = NULL;
3534 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3536 res = talloc_zero(tmp_ctx, struct ldb_result);
3537 if (!res) {
3538 talloc_free(tmp_ctx);
3539 return LDB_ERR_OPERATIONS_ERROR;
3542 if (exp_fmt) {
3543 va_start(ap, exp_fmt);
3544 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3545 va_end(ap);
3547 if (!expression) {
3548 talloc_free(tmp_ctx);
3549 return LDB_ERR_OPERATIONS_ERROR;
3553 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3554 basedn,
3555 scope,
3556 expression,
3557 attrs,
3558 NULL,
3559 res,
3560 ldb_search_default_callback,
3561 NULL);
3562 if (ret != LDB_SUCCESS) {
3563 talloc_free(tmp_ctx);
3564 return ret;
3567 ret = dsdb_request_add_controls(req, dsdb_flags);
3568 if (ret != LDB_SUCCESS) {
3569 talloc_free(tmp_ctx);
3570 return ret;
3573 ret = ldb_request(ldb, req);
3574 if (ret == LDB_SUCCESS) {
3575 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3578 if (ret != LDB_SUCCESS) {
3579 talloc_free(tmp_ctx);
3580 return ret;
3583 if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
3584 if (res->count == 0) {
3585 talloc_free(tmp_ctx);
3586 return LDB_ERR_NO_SUCH_OBJECT;
3588 if (res->count != 1) {
3589 talloc_free(tmp_ctx);
3590 return LDB_ERR_CONSTRAINT_VIOLATION;
3594 *_res = talloc_steal(mem_ctx, res);
3595 talloc_free(tmp_ctx);
3597 return LDB_SUCCESS;
3602 general search with dsdb_flags for controls
3603 returns exactly 1 record or an error
3605 int dsdb_search_one(struct ldb_context *ldb,
3606 TALLOC_CTX *mem_ctx,
3607 struct ldb_message **msg,
3608 struct ldb_dn *basedn,
3609 enum ldb_scope scope,
3610 const char * const *attrs,
3611 uint32_t dsdb_flags,
3612 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3614 int ret;
3615 struct ldb_result *res;
3616 va_list ap;
3617 char *expression = NULL;
3618 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3620 dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
3622 res = talloc_zero(tmp_ctx, struct ldb_result);
3623 if (!res) {
3624 talloc_free(tmp_ctx);
3625 return LDB_ERR_OPERATIONS_ERROR;
3628 if (exp_fmt) {
3629 va_start(ap, exp_fmt);
3630 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3631 va_end(ap);
3633 if (!expression) {
3634 talloc_free(tmp_ctx);
3635 return LDB_ERR_OPERATIONS_ERROR;
3639 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
3640 dsdb_flags, "%s", expression);
3641 if (ret != LDB_SUCCESS) {
3642 talloc_free(tmp_ctx);
3643 return ret;
3646 *msg = talloc_steal(mem_ctx, res->msgs[0]);
3647 talloc_free(tmp_ctx);
3649 return LDB_SUCCESS;
3652 /* returns back the forest DNS name */
3653 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
3655 const char *forest_name = ldb_dn_canonical_string(mem_ctx,
3656 ldb_get_root_basedn(ldb));
3657 char *p;
3659 if (forest_name == NULL) {
3660 return NULL;
3663 p = strchr(forest_name, '/');
3664 if (p) {
3665 *p = '\0';
3668 return forest_name;
3672 validate that an DSA GUID belongs to the specified user sid.
3673 The user SID must be a domain controller account (either RODC or
3674 RWDC)
3676 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
3677 const struct GUID *dsa_guid,
3678 const struct dom_sid *sid)
3680 /* strategy:
3681 - find DN of record with the DSA GUID in the
3682 configuration partition (objectGUID)
3683 - remove "NTDS Settings" component from DN
3684 - do a base search on that DN for serverReference with
3685 extended-dn enabled
3686 - extract objectSID from resulting serverReference
3687 attribute
3688 - check this sid matches the sid argument
3690 struct ldb_dn *config_dn;
3691 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3692 struct ldb_message *msg;
3693 const char *attrs1[] = { NULL };
3694 const char *attrs2[] = { "serverReference", NULL };
3695 int ret;
3696 struct ldb_dn *dn, *account_dn;
3697 struct dom_sid sid2;
3698 NTSTATUS status;
3700 config_dn = ldb_get_config_basedn(ldb);
3702 ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
3703 attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
3704 if (ret != LDB_SUCCESS) {
3705 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
3706 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3707 talloc_free(tmp_ctx);
3708 return LDB_ERR_OPERATIONS_ERROR;
3710 dn = msg->dn;
3712 if (!ldb_dn_remove_child_components(dn, 1)) {
3713 talloc_free(tmp_ctx);
3714 return LDB_ERR_OPERATIONS_ERROR;
3717 ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
3718 attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
3719 "(objectClass=server)");
3720 if (ret != LDB_SUCCESS) {
3721 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
3722 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3723 talloc_free(tmp_ctx);
3724 return LDB_ERR_OPERATIONS_ERROR;
3727 account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
3728 if (account_dn == NULL) {
3729 DEBUG(1,(__location__ ": Failed to find account_dn for DSA with objectGUID %s, sid %s\n",
3730 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3731 talloc_free(tmp_ctx);
3732 return LDB_ERR_OPERATIONS_ERROR;
3735 status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
3736 if (!NT_STATUS_IS_OK(status)) {
3737 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
3738 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3739 talloc_free(tmp_ctx);
3740 return LDB_ERR_OPERATIONS_ERROR;
3743 if (!dom_sid_equal(sid, &sid2)) {
3744 /* someone is trying to spoof another account */
3745 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
3746 GUID_string(tmp_ctx, dsa_guid),
3747 dom_sid_string(tmp_ctx, sid),
3748 dom_sid_string(tmp_ctx, &sid2)));
3749 talloc_free(tmp_ctx);
3750 return LDB_ERR_OPERATIONS_ERROR;
3753 talloc_free(tmp_ctx);
3754 return LDB_SUCCESS;
3757 const char *rodc_fas_list[] = {"ms-PKI-DPAPIMasterKeys",
3758 "ms-PKI-AccountCredentials",
3759 "ms-PKI-RoamingTimeStamp",
3760 "ms-FVE-KeyPackage",
3761 "ms-FVE-RecoveryGuid",
3762 "ms-FVE-RecoveryInformation",
3763 "ms-FVE-RecoveryPassword",
3764 "ms-FVE-VolumeGuid",
3765 "ms-TPM-OwnerInformation",
3766 NULL};
3768 check if the attribute belongs to the RODC filtered attribute set
3770 bool dsdb_attr_in_rodc_fas(uint32_t replica_flags, const struct dsdb_attribute *sa)
3772 int rodc_filtered_flags = SEARCH_FLAG_RODC_ATTRIBUTE | SEARCH_FLAG_CONFIDENTIAL;
3773 bool drs_write_replica = ((replica_flags & DRSUAPI_DRS_WRIT_REP) == 0);
3775 if (drs_write_replica && (sa->searchFlags & rodc_filtered_flags)) {
3776 return true;
3778 if (drs_write_replica && is_attr_in_list(rodc_fas_list, sa->cn)) {
3779 return true;
3781 return false;