s4:samdb_set_password - return "NT_STATUS_WRONG_PASSWORD" when a user account doesn...
[Samba.git] / source4 / dsdb / common / util.c
blobbe8e3a9d11c2235dec7ac2142083dd3765c0ae3e
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_module.h"
28 #include "ldb_errors.h"
29 #include "../lib/util/util_ldb.h"
30 #include "../lib/crypto/crypto.h"
31 #include "dsdb/samdb/samdb.h"
32 #include "libcli/security/security.h"
33 #include "librpc/gen_ndr/ndr_security.h"
34 #include "librpc/gen_ndr/ndr_misc.h"
35 #include "../libds/common/flags.h"
36 #include "dsdb/common/proto.h"
37 #include "libcli/ldap/ldap_ndr.h"
38 #include "param/param.h"
39 #include "libcli/auth/libcli_auth.h"
40 #include "librpc/gen_ndr/ndr_drsblobs.h"
41 #include "system/locale.h"
42 #include "lib/util/tsort.h"
43 #include "dsdb/common/util.h"
44 #include "lib/socket/socket.h"
45 #include "dsdb/samdb/ldb_modules/util.h"
48 search the sam for the specified attributes in a specific domain, filter on
49 objectSid being in domain_sid.
51 int samdb_search_domain(struct ldb_context *sam_ldb,
52 TALLOC_CTX *mem_ctx,
53 struct ldb_dn *basedn,
54 struct ldb_message ***res,
55 const char * const *attrs,
56 const struct dom_sid *domain_sid,
57 const char *format, ...) _PRINTF_ATTRIBUTE(7,8)
59 va_list ap;
60 int i, count;
62 va_start(ap, format);
63 count = gendb_search_v(sam_ldb, mem_ctx, basedn,
64 res, attrs, format, ap);
65 va_end(ap);
67 i=0;
69 while (i<count) {
70 struct dom_sid *entry_sid;
72 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
74 if ((entry_sid == NULL) ||
75 (!dom_sid_in_domain(domain_sid, entry_sid))) {
76 /* Delete that entry from the result set */
77 (*res)[i] = (*res)[count-1];
78 count -= 1;
79 talloc_free(entry_sid);
80 continue;
82 talloc_free(entry_sid);
83 i += 1;
86 return count;
90 search the sam for a single string attribute in exactly 1 record
92 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
93 TALLOC_CTX *mem_ctx,
94 struct ldb_dn *basedn,
95 const char *attr_name,
96 const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
98 int count;
99 const char *attrs[2] = { NULL, NULL };
100 struct ldb_message **res = NULL;
102 attrs[0] = attr_name;
104 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
105 if (count > 1) {
106 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
107 attr_name, format, count));
109 if (count != 1) {
110 talloc_free(res);
111 return NULL;
114 return samdb_result_string(res[0], attr_name, NULL);
118 search the sam for a single string attribute in exactly 1 record
120 const char *samdb_search_string(struct ldb_context *sam_ldb,
121 TALLOC_CTX *mem_ctx,
122 struct ldb_dn *basedn,
123 const char *attr_name,
124 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
126 va_list ap;
127 const char *str;
129 va_start(ap, format);
130 str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
131 va_end(ap);
133 return str;
136 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
137 TALLOC_CTX *mem_ctx,
138 struct ldb_dn *basedn,
139 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
141 va_list ap;
142 struct ldb_dn *ret;
143 struct ldb_message **res = NULL;
144 int count;
146 va_start(ap, format);
147 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
148 va_end(ap);
150 if (count != 1) return NULL;
152 ret = talloc_steal(mem_ctx, res[0]->dn);
153 talloc_free(res);
155 return ret;
159 search the sam for a dom_sid attribute in exactly 1 record
161 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
162 TALLOC_CTX *mem_ctx,
163 struct ldb_dn *basedn,
164 const char *attr_name,
165 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
167 va_list ap;
168 int count;
169 struct ldb_message **res;
170 const char *attrs[2] = { NULL, NULL };
171 struct dom_sid *sid;
173 attrs[0] = attr_name;
175 va_start(ap, format);
176 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
177 va_end(ap);
178 if (count > 1) {
179 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
180 attr_name, format, count));
182 if (count != 1) {
183 talloc_free(res);
184 return NULL;
186 sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
187 talloc_free(res);
188 return sid;
192 return the count of the number of records in the sam matching the query
194 int samdb_search_count(struct ldb_context *sam_ldb,
195 struct ldb_dn *basedn,
196 const char *format, ...) _PRINTF_ATTRIBUTE(3,4)
198 va_list ap;
199 struct ldb_message **res;
200 const char *attrs[] = { NULL };
201 int ret;
202 TALLOC_CTX *tmp_ctx = talloc_new(sam_ldb);
204 va_start(ap, format);
205 ret = gendb_search_v(sam_ldb, tmp_ctx, basedn, &res, attrs, format, ap);
206 va_end(ap);
207 talloc_free(tmp_ctx);
209 return ret;
214 search the sam for a single integer attribute in exactly 1 record
216 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
217 TALLOC_CTX *mem_ctx,
218 unsigned int default_value,
219 struct ldb_dn *basedn,
220 const char *attr_name,
221 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
223 va_list ap;
224 int count;
225 struct ldb_message **res;
226 const char *attrs[2] = { NULL, NULL };
228 attrs[0] = attr_name;
230 va_start(ap, format);
231 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
232 va_end(ap);
234 if (count != 1) {
235 return default_value;
238 return samdb_result_uint(res[0], attr_name, default_value);
242 search the sam for a single signed 64 bit integer attribute in exactly 1 record
244 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
245 TALLOC_CTX *mem_ctx,
246 int64_t default_value,
247 struct ldb_dn *basedn,
248 const char *attr_name,
249 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
251 va_list ap;
252 int count;
253 struct ldb_message **res;
254 const char *attrs[2] = { NULL, NULL };
256 attrs[0] = attr_name;
258 va_start(ap, format);
259 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
260 va_end(ap);
262 if (count != 1) {
263 return default_value;
266 return samdb_result_int64(res[0], attr_name, default_value);
270 search the sam for multipe records each giving a single string attribute
271 return the number of matches, or -1 on error
273 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
274 TALLOC_CTX *mem_ctx,
275 struct ldb_dn *basedn,
276 const char ***strs,
277 const char *attr_name,
278 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
280 va_list ap;
281 int count, i;
282 const char *attrs[2] = { NULL, NULL };
283 struct ldb_message **res = NULL;
285 attrs[0] = attr_name;
287 va_start(ap, format);
288 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
289 va_end(ap);
291 if (count <= 0) {
292 return count;
295 /* make sure its single valued */
296 for (i=0;i<count;i++) {
297 if (res[i]->num_elements != 1) {
298 DEBUG(1,("samdb: search for %s %s not single valued\n",
299 attr_name, format));
300 talloc_free(res);
301 return -1;
305 *strs = talloc_array(mem_ctx, const char *, count+1);
306 if (! *strs) {
307 talloc_free(res);
308 return -1;
311 for (i=0;i<count;i++) {
312 (*strs)[i] = samdb_result_string(res[i], attr_name, NULL);
314 (*strs)[count] = NULL;
316 return count;
320 pull a uint from a result set.
322 unsigned int samdb_result_uint(const struct ldb_message *msg, const char *attr, unsigned int default_value)
324 return ldb_msg_find_attr_as_uint(msg, attr, default_value);
328 pull a (signed) int64 from a result set.
330 int64_t samdb_result_int64(const struct ldb_message *msg, const char *attr, int64_t default_value)
332 return ldb_msg_find_attr_as_int64(msg, attr, default_value);
336 pull a string from a result set.
338 const char *samdb_result_string(const struct ldb_message *msg, const char *attr,
339 const char *default_value)
341 return ldb_msg_find_attr_as_string(msg, attr, default_value);
344 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
345 const char *attr, struct ldb_dn *default_value)
347 struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
348 if (!ret_dn) {
349 return default_value;
351 return ret_dn;
355 pull a rid from a objectSid in a result set.
357 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
358 const char *attr, uint32_t default_value)
360 struct dom_sid *sid;
361 uint32_t rid;
363 sid = samdb_result_dom_sid(mem_ctx, msg, attr);
364 if (sid == NULL) {
365 return default_value;
367 rid = sid->sub_auths[sid->num_auths-1];
368 talloc_free(sid);
369 return rid;
373 pull a dom_sid structure from a objectSid in a result set.
375 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
376 const char *attr)
378 const struct ldb_val *v;
379 struct dom_sid *sid;
380 enum ndr_err_code ndr_err;
381 v = ldb_msg_find_ldb_val(msg, attr);
382 if (v == NULL) {
383 return NULL;
385 sid = talloc(mem_ctx, struct dom_sid);
386 if (sid == NULL) {
387 return NULL;
389 ndr_err = ndr_pull_struct_blob(v, sid, sid,
390 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
391 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
392 talloc_free(sid);
393 return NULL;
395 return sid;
399 pull a guid structure from a objectGUID in a result set.
401 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
403 const struct ldb_val *v;
404 struct GUID guid;
405 NTSTATUS status;
407 v = ldb_msg_find_ldb_val(msg, attr);
408 if (!v) return GUID_zero();
410 status = GUID_from_ndr_blob(v, &guid);
411 if (!NT_STATUS_IS_OK(status)) {
412 return GUID_zero();
415 return guid;
419 pull a sid prefix from a objectSid in a result set.
420 this is used to find the domain sid for a user
422 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
423 const char *attr)
425 struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
426 if (!sid || sid->num_auths < 1) return NULL;
427 sid->num_auths--;
428 return sid;
432 pull a NTTIME in a result set.
434 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
435 NTTIME default_value)
437 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
441 * Windows stores 0 for lastLogoff.
442 * But when a MS DC return the lastLogoff (as Logoff Time)
443 * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
444 * cause windows 2008 and newer version to fail for SMB requests
446 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
448 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
450 if (ret == 0)
451 ret = 0x7FFFFFFFFFFFFFFFULL;
453 return ret;
457 * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
458 * indicate an account doesn't expire.
460 * When Windows initially creates an account, it sets
461 * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF). However,
462 * when changing from an account having a specific expiration date to
463 * that account never expiring, it sets accountExpires = 0.
465 * Consolidate that logic here to allow clearer logic for account expiry in
466 * the rest of the code.
468 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
470 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
473 if (ret == 0)
474 ret = 0x7FFFFFFFFFFFFFFFULL;
476 return ret;
480 pull a uint64_t from a result set.
482 uint64_t samdb_result_uint64(const struct ldb_message *msg, const char *attr,
483 uint64_t default_value)
485 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
490 construct the allow_password_change field from the PwdLastSet attribute and the
491 domain password settings
493 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb,
494 TALLOC_CTX *mem_ctx,
495 struct ldb_dn *domain_dn,
496 struct ldb_message *msg,
497 const char *attr)
499 uint64_t attr_time = samdb_result_uint64(msg, attr, 0);
500 int64_t minPwdAge;
502 if (attr_time == 0) {
503 return 0;
506 minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
508 /* yes, this is a -= not a += as minPwdAge is stored as the negative
509 of the number of 100-nano-seconds */
510 attr_time -= minPwdAge;
512 return attr_time;
516 construct the force_password_change field from the PwdLastSet
517 attribute, the userAccountControl and the domain password settings
519 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb,
520 TALLOC_CTX *mem_ctx,
521 struct ldb_dn *domain_dn,
522 struct ldb_message *msg)
524 int64_t attr_time = samdb_result_int64(msg, "pwdLastSet", 0);
525 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg,
526 "userAccountControl",
528 int64_t maxPwdAge;
530 /* Machine accounts don't expire, and there is a flag for 'no expiry' */
531 if (!(userAccountControl & UF_NORMAL_ACCOUNT)
532 || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
533 return 0x7FFFFFFFFFFFFFFFULL;
536 if (attr_time == 0) {
537 return 0;
539 if (attr_time == -1) {
540 return 0x7FFFFFFFFFFFFFFFULL;
543 maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
544 "maxPwdAge", NULL);
545 if (maxPwdAge == 0) {
546 return 0x7FFFFFFFFFFFFFFFULL;
547 } else {
548 attr_time -= maxPwdAge;
551 return attr_time;
555 pull a samr_Password structutre from a result set.
557 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
559 struct samr_Password *hash = NULL;
560 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
561 if (val && (val->length >= sizeof(hash->hash))) {
562 hash = talloc(mem_ctx, struct samr_Password);
563 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
565 return hash;
569 pull an array of samr_Password structures from a result set.
571 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
572 const char *attr, struct samr_Password **hashes)
574 unsigned int count, i;
575 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
577 *hashes = NULL;
578 if (!val) {
579 return 0;
581 count = val->length / 16;
582 if (count == 0) {
583 return 0;
586 *hashes = talloc_array(mem_ctx, struct samr_Password, count);
587 if (! *hashes) {
588 return 0;
591 for (i=0;i<count;i++) {
592 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
595 return count;
598 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct ldb_message *msg,
599 struct samr_Password **lm_pwd, struct samr_Password **nt_pwd)
601 struct samr_Password *lmPwdHash, *ntPwdHash;
602 if (nt_pwd) {
603 unsigned int num_nt;
604 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
605 if (num_nt == 0) {
606 *nt_pwd = NULL;
607 } else if (num_nt > 1) {
608 return NT_STATUS_INTERNAL_DB_CORRUPTION;
609 } else {
610 *nt_pwd = &ntPwdHash[0];
613 if (lm_pwd) {
614 /* Ensure that if we have turned off LM
615 * authentication, that we never use the LM hash, even
616 * if we store it */
617 if (lpcfg_lanman_auth(lp_ctx)) {
618 unsigned int num_lm;
619 num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
620 if (num_lm == 0) {
621 *lm_pwd = NULL;
622 } else if (num_lm > 1) {
623 return NT_STATUS_INTERNAL_DB_CORRUPTION;
624 } else {
625 *lm_pwd = &lmPwdHash[0];
627 } else {
628 *lm_pwd = NULL;
631 return NT_STATUS_OK;
635 pull a samr_LogonHours structutre from a result set.
637 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
639 struct samr_LogonHours hours;
640 size_t units_per_week = 168;
641 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
643 ZERO_STRUCT(hours);
645 if (val) {
646 units_per_week = val->length * 8;
649 hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
650 if (!hours.bits) {
651 return hours;
653 hours.units_per_week = units_per_week;
654 memset(hours.bits, 0xFF, units_per_week/8);
655 if (val) {
656 memcpy(hours.bits, val->data, val->length);
659 return hours;
663 pull a set of account_flags from a result set.
665 This requires that the attributes:
666 pwdLastSet
667 userAccountControl
668 be included in 'msg'
670 uint32_t samdb_result_acct_flags(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
671 struct ldb_message *msg, struct ldb_dn *domain_dn)
673 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
674 uint32_t acct_flags = ds_uf2acb(userAccountControl);
675 NTTIME must_change_time;
676 NTTIME now;
678 must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx,
679 domain_dn, msg);
681 /* Test account expire time */
682 unix_to_nt_time(&now, time(NULL));
683 /* check for expired password */
684 if (must_change_time < now) {
685 acct_flags |= ACB_PW_EXPIRED;
687 return acct_flags;
690 struct lsa_BinaryString samdb_result_parameters(TALLOC_CTX *mem_ctx,
691 struct ldb_message *msg,
692 const char *attr)
694 struct lsa_BinaryString s;
695 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
697 ZERO_STRUCT(s);
699 if (!val) {
700 return s;
703 s.array = talloc_array(mem_ctx, uint16_t, val->length/2);
704 if (!s.array) {
705 return s;
707 s.length = s.size = val->length;
708 memcpy(s.array, val->data, val->length);
710 return s;
713 /* Find an attribute, with a particular value */
715 /* The current callers of this function expect a very specific
716 * behaviour: In particular, objectClass subclass equivilance is not
717 * wanted. This means that we should not lookup the schema for the
718 * comparison function */
719 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
720 const struct ldb_message *msg,
721 const char *name, const char *value)
723 unsigned int i;
724 struct ldb_message_element *el = ldb_msg_find_element(msg, name);
726 if (!el) {
727 return NULL;
730 for (i=0;i<el->num_values;i++) {
731 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
732 return el;
736 return NULL;
740 * This is intended for use by the "password hash" module since there
741 * password changes can be specified through one message element with the
742 * new password (to set) and another one with the old password (to unset).
744 * The first which sets a password (new value) can have flags
745 * (LDB_FLAG_MOD_ADD, LDB_FLAG_MOD_REPLACE) but also none (on "add" operations
746 * for entries). The latter (old value) has always specified
747 * LDB_FLAG_MOD_DELETE.
749 * Returns LDB_ERR_NO_SUCH_ATTRIBUTE if the attribute which should be deleted
750 * doesn't contain only one value (this is the Windows Server behaviour)
751 * otherwise LDB_SUCCESS.
753 int samdb_msg_find_old_and_new_ldb_val(const struct ldb_message *msg,
754 const char *name,
755 const struct ldb_val **new_val,
756 const struct ldb_val **old_val)
758 unsigned int i;
760 *new_val = NULL;
761 *old_val = NULL;
763 if (msg == NULL) {
764 return LDB_SUCCESS;
767 for (i = 0; i < msg->num_elements; i++) {
768 if (ldb_attr_cmp(msg->elements[i].name, name) == 0) {
769 if (msg->elements[i].flags == LDB_FLAG_MOD_DELETE) {
770 *old_val = &msg->elements[i].values[0];
771 } else {
772 *new_val = &msg->elements[i].values[0];
777 return LDB_SUCCESS;
780 int samdb_find_or_add_value(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
782 if (samdb_find_attribute(ldb, msg, name, set_value) == NULL) {
783 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
785 return LDB_SUCCESS;
788 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
790 struct ldb_message_element *el;
792 el = ldb_msg_find_element(msg, name);
793 if (el) {
794 return LDB_SUCCESS;
797 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
803 add a string element to a message
805 int samdb_msg_add_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
806 const char *attr_name, const char *str)
808 char *s = talloc_strdup(mem_ctx, str);
809 char *a = talloc_strdup(mem_ctx, attr_name);
810 if (s == NULL || a == NULL) {
811 return ldb_oom(sam_ldb);
813 return ldb_msg_add_string(msg, a, s);
817 add a dom_sid element to a message
819 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
820 const char *attr_name, struct dom_sid *sid)
822 struct ldb_val v;
823 enum ndr_err_code ndr_err;
825 ndr_err = ndr_push_struct_blob(&v, mem_ctx,
826 sid,
827 (ndr_push_flags_fn_t)ndr_push_dom_sid);
828 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
829 return ldb_operr(sam_ldb);
831 return ldb_msg_add_value(msg, attr_name, &v, NULL);
836 add a delete element operation to a message
838 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
839 const char *attr_name)
841 /* we use an empty replace rather than a delete, as it allows for
842 dsdb_replace() to be used everywhere */
843 return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
847 add an add attribute value to a message or enhance an existing attribute
848 which has the same name and the add flag set.
850 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
851 struct ldb_message *msg, const char *attr_name,
852 const char *value)
854 struct ldb_message_element *el;
855 struct ldb_val val, *vals;
856 char *v;
857 unsigned int i;
858 bool found = false;
859 int ret;
861 v = talloc_strdup(mem_ctx, value);
862 if (v == NULL) {
863 return ldb_oom(sam_ldb);
866 val.data = (uint8_t *) v;
867 val.length = strlen(v);
869 if (val.length == 0) {
870 /* allow empty strings as non-existent attributes */
871 return LDB_SUCCESS;
874 for (i = 0; i < msg->num_elements; i++) {
875 el = &msg->elements[i];
876 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
877 (el->flags == LDB_FLAG_MOD_ADD)) {
878 found = true;
879 break;
882 if (!found) {
883 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
884 &el);
885 if (ret != LDB_SUCCESS) {
886 return ret;
890 vals = talloc_realloc(msg, el->values, struct ldb_val,
891 el->num_values + 1);
892 if (vals == NULL) {
893 return ldb_oom(sam_ldb);
895 el->values = vals;
896 el->values[el->num_values] = val;
897 ++(el->num_values);
899 return LDB_SUCCESS;
903 add a delete attribute value to a message or enhance an existing attribute
904 which has the same name and the delete flag set.
906 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
907 struct ldb_message *msg, const char *attr_name,
908 const char *value)
910 struct ldb_message_element *el;
911 struct ldb_val val, *vals;
912 char *v;
913 unsigned int i;
914 bool found = false;
915 int ret;
917 v = talloc_strdup(mem_ctx, value);
918 if (v == NULL) {
919 return ldb_oom(sam_ldb);
922 val.data = (uint8_t *) v;
923 val.length = strlen(v);
925 if (val.length == 0) {
926 /* allow empty strings as non-existent attributes */
927 return LDB_SUCCESS;
930 for (i = 0; i < msg->num_elements; i++) {
931 el = &msg->elements[i];
932 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
933 (el->flags == LDB_FLAG_MOD_DELETE)) {
934 found = true;
935 break;
938 if (!found) {
939 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
940 &el);
941 if (ret != LDB_SUCCESS) {
942 return ret;
946 vals = talloc_realloc(msg, el->values, struct ldb_val,
947 el->num_values + 1);
948 if (vals == NULL) {
949 return ldb_oom(sam_ldb);
951 el->values = vals;
952 el->values[el->num_values] = val;
953 ++(el->num_values);
955 return LDB_SUCCESS;
959 add a int element to a message
961 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
962 const char *attr_name, int v)
964 const char *s = talloc_asprintf(mem_ctx, "%d", v);
965 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
969 add a unsigned int element to a message
971 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
972 const char *attr_name, unsigned int v)
974 return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
978 add a (signed) int64_t element to a message
980 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
981 const char *attr_name, int64_t v)
983 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
984 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
988 add a uint64_t element to a message
990 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
991 const char *attr_name, uint64_t v)
993 return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
997 add a samr_Password element to a message
999 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1000 const char *attr_name, struct samr_Password *hash)
1002 struct ldb_val val;
1003 val.data = talloc_memdup(mem_ctx, hash->hash, 16);
1004 if (!val.data) {
1005 return ldb_oom(sam_ldb);
1007 val.length = 16;
1008 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1012 add a samr_Password array to a message
1014 int samdb_msg_add_hashes(struct ldb_context *ldb,
1015 TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1016 const char *attr_name, struct samr_Password *hashes,
1017 unsigned int count)
1019 struct ldb_val val;
1020 unsigned int i;
1021 val.data = talloc_array_size(mem_ctx, 16, count);
1022 val.length = count*16;
1023 if (!val.data) {
1024 return ldb_oom(ldb);
1026 for (i=0;i<count;i++) {
1027 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
1029 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1033 add a acct_flags element to a message
1035 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1036 const char *attr_name, uint32_t v)
1038 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1042 add a logon_hours element to a message
1044 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1045 const char *attr_name, struct samr_LogonHours *hours)
1047 struct ldb_val val;
1048 val.length = hours->units_per_week / 8;
1049 val.data = hours->bits;
1050 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1054 add a parameters element to a message
1056 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1057 const char *attr_name, struct lsa_BinaryString *parameters)
1059 struct ldb_val val;
1060 val.length = parameters->length;
1061 val.data = (uint8_t *)parameters->array;
1062 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1065 add a general value element to a message
1067 int samdb_msg_add_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1068 const char *attr_name, const struct ldb_val *val)
1070 return ldb_msg_add_value(msg, attr_name, val, NULL);
1074 sets a general value element to a message
1076 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1077 const char *attr_name, const struct ldb_val *val)
1079 struct ldb_message_element *el;
1081 el = ldb_msg_find_element(msg, attr_name);
1082 if (el) {
1083 el->num_values = 0;
1085 return ldb_msg_add_value(msg, attr_name, val, NULL);
1089 set a string element in a message
1091 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1092 const char *attr_name, const char *str)
1094 struct ldb_message_element *el;
1096 el = ldb_msg_find_element(msg, attr_name);
1097 if (el) {
1098 el->num_values = 0;
1100 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, str);
1104 * Handle ldb_request in transaction
1106 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1107 struct ldb_request *req)
1109 int ret;
1111 ret = ldb_transaction_start(sam_ldb);
1112 if (ret != LDB_SUCCESS) {
1113 return ret;
1116 ret = ldb_request(sam_ldb, req);
1117 if (ret == LDB_SUCCESS) {
1118 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1121 if (ret == LDB_SUCCESS) {
1122 return ldb_transaction_commit(sam_ldb);
1124 ldb_transaction_cancel(sam_ldb);
1126 return ret;
1130 return a default security descriptor
1132 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1134 struct security_descriptor *sd;
1136 sd = security_descriptor_initialise(mem_ctx);
1138 return sd;
1141 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1143 struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1144 struct ldb_dn *aggregate_dn;
1145 if (!schema_dn) {
1146 return NULL;
1149 aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1150 if (!aggregate_dn) {
1151 return NULL;
1153 if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1154 return NULL;
1156 return aggregate_dn;
1159 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1161 struct ldb_dn *new_dn;
1163 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1164 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1165 talloc_free(new_dn);
1166 return NULL;
1168 return new_dn;
1171 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1173 struct ldb_dn *new_dn;
1175 new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1176 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1177 talloc_free(new_dn);
1178 return NULL;
1180 return new_dn;
1183 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1185 struct ldb_dn *new_dn;
1187 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1188 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1189 talloc_free(new_dn);
1190 return NULL;
1192 return new_dn;
1196 work out the domain sid for the current open ldb
1198 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1200 TALLOC_CTX *tmp_ctx;
1201 const struct dom_sid *domain_sid;
1202 const char *attrs[] = {
1203 "objectSid",
1204 NULL
1206 struct ldb_result *res;
1207 int ret;
1209 /* see if we have a cached copy */
1210 domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1211 if (domain_sid) {
1212 return domain_sid;
1215 tmp_ctx = talloc_new(ldb);
1216 if (tmp_ctx == NULL) {
1217 goto failed;
1220 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1222 if (ret != LDB_SUCCESS) {
1223 goto failed;
1226 if (res->count != 1) {
1227 goto failed;
1230 domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1231 if (domain_sid == NULL) {
1232 goto failed;
1235 /* cache the domain_sid in the ldb */
1236 if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1237 goto failed;
1240 talloc_steal(ldb, domain_sid);
1241 talloc_free(tmp_ctx);
1243 return domain_sid;
1245 failed:
1246 talloc_free(tmp_ctx);
1247 return NULL;
1251 get domain sid from cache
1253 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1255 return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1258 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1260 TALLOC_CTX *tmp_ctx;
1261 struct dom_sid *dom_sid_new;
1262 struct dom_sid *dom_sid_old;
1264 /* see if we have a cached copy */
1265 dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1266 "cache.domain_sid"), struct dom_sid);
1268 tmp_ctx = talloc_new(ldb);
1269 if (tmp_ctx == NULL) {
1270 goto failed;
1273 dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1274 if (!dom_sid_new) {
1275 goto failed;
1278 /* cache the domain_sid in the ldb */
1279 if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1280 goto failed;
1283 talloc_steal(ldb, dom_sid_new);
1284 talloc_free(tmp_ctx);
1285 talloc_free(dom_sid_old);
1287 return true;
1289 failed:
1290 DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1291 talloc_free(tmp_ctx);
1292 return false;
1295 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1297 TALLOC_CTX *tmp_ctx;
1298 struct ldb_dn *ntds_settings_dn_new;
1299 struct ldb_dn *ntds_settings_dn_old;
1301 /* see if we have a cached copy */
1302 ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb,
1303 "cache.ntds_settings_dn"), struct ldb_dn);
1305 tmp_ctx = talloc_new(ldb);
1306 if (tmp_ctx == NULL) {
1307 goto failed;
1310 ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1311 if (!ntds_settings_dn_new) {
1312 goto failed;
1315 /* cache the domain_sid in the ldb */
1316 if (ldb_set_opaque(ldb, "cache.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1317 goto failed;
1320 talloc_steal(ldb, ntds_settings_dn_new);
1321 talloc_free(tmp_ctx);
1322 talloc_free(ntds_settings_dn_old);
1324 return true;
1326 failed:
1327 DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1328 talloc_free(tmp_ctx);
1329 return false;
1332 /* Obtain the short name of the flexible single master operator
1333 * (FSMO), such as the PDC Emulator */
1334 const char *samdb_result_fsmo_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
1335 const char *attr)
1337 /* Format is cn=NTDS Settings,cn=<NETBIOS name of FSMO>,.... */
1338 struct ldb_dn *fsmo_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
1339 const struct ldb_val *val = ldb_dn_get_component_val(fsmo_dn, 1);
1340 const char *name = ldb_dn_get_component_name(fsmo_dn, 1);
1342 if (!name || (ldb_attr_cmp(name, "cn") != 0)) {
1343 /* Ensure this matches the format. This gives us a
1344 * bit more confidence that a 'cn' value will be a
1345 * ascii string */
1346 return NULL;
1348 if (val) {
1349 return (char *)val->data;
1351 return NULL;
1355 work out the ntds settings dn for the current open ldb
1357 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1359 TALLOC_CTX *tmp_ctx;
1360 const char *root_attrs[] = { "dsServiceName", NULL };
1361 int ret;
1362 struct ldb_result *root_res;
1363 struct ldb_dn *settings_dn;
1365 /* see if we have a cached copy */
1366 settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "cache.ntds_settings_dn");
1367 if (settings_dn) {
1368 return settings_dn;
1371 tmp_ctx = talloc_new(ldb);
1372 if (tmp_ctx == NULL) {
1373 goto failed;
1376 ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1377 if (ret) {
1378 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1379 ldb_errstring(ldb)));
1380 goto failed;
1383 if (root_res->count != 1) {
1384 goto failed;
1387 settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1389 /* cache the domain_sid in the ldb */
1390 if (ldb_set_opaque(ldb, "cache.settings_dn", settings_dn) != LDB_SUCCESS) {
1391 goto failed;
1394 talloc_steal(ldb, settings_dn);
1395 talloc_free(tmp_ctx);
1397 return settings_dn;
1399 failed:
1400 DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1401 talloc_free(tmp_ctx);
1402 return NULL;
1406 work out the ntds settings invocationId for the current open ldb
1408 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1410 TALLOC_CTX *tmp_ctx;
1411 const char *attrs[] = { "invocationId", NULL };
1412 int ret;
1413 struct ldb_result *res;
1414 struct GUID *invocation_id;
1416 /* see if we have a cached copy */
1417 invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1418 if (invocation_id) {
1419 return invocation_id;
1422 tmp_ctx = talloc_new(ldb);
1423 if (tmp_ctx == NULL) {
1424 goto failed;
1427 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1428 if (ret) {
1429 goto failed;
1432 if (res->count != 1) {
1433 goto failed;
1436 invocation_id = talloc(tmp_ctx, struct GUID);
1437 if (!invocation_id) {
1438 goto failed;
1441 *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1443 /* cache the domain_sid in the ldb */
1444 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1445 goto failed;
1448 talloc_steal(ldb, invocation_id);
1449 talloc_free(tmp_ctx);
1451 return invocation_id;
1453 failed:
1454 DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1455 talloc_free(tmp_ctx);
1456 return NULL;
1459 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1461 TALLOC_CTX *tmp_ctx;
1462 struct GUID *invocation_id_new;
1463 struct GUID *invocation_id_old;
1465 /* see if we have a cached copy */
1466 invocation_id_old = (struct GUID *)ldb_get_opaque(ldb,
1467 "cache.invocation_id");
1469 tmp_ctx = talloc_new(ldb);
1470 if (tmp_ctx == NULL) {
1471 goto failed;
1474 invocation_id_new = talloc(tmp_ctx, struct GUID);
1475 if (!invocation_id_new) {
1476 goto failed;
1479 *invocation_id_new = *invocation_id_in;
1481 /* cache the domain_sid in the ldb */
1482 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1483 goto failed;
1486 talloc_steal(ldb, invocation_id_new);
1487 talloc_free(tmp_ctx);
1488 talloc_free(invocation_id_old);
1490 return true;
1492 failed:
1493 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1494 talloc_free(tmp_ctx);
1495 return false;
1499 work out the ntds settings objectGUID for the current open ldb
1501 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1503 TALLOC_CTX *tmp_ctx;
1504 const char *attrs[] = { "objectGUID", NULL };
1505 int ret;
1506 struct ldb_result *res;
1507 struct GUID *ntds_guid;
1509 /* see if we have a cached copy */
1510 ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1511 if (ntds_guid) {
1512 return ntds_guid;
1515 tmp_ctx = talloc_new(ldb);
1516 if (tmp_ctx == NULL) {
1517 goto failed;
1520 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1521 if (ret) {
1522 goto failed;
1525 if (res->count != 1) {
1526 goto failed;
1529 ntds_guid = talloc(tmp_ctx, struct GUID);
1530 if (!ntds_guid) {
1531 goto failed;
1534 *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1536 /* cache the domain_sid in the ldb */
1537 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1538 goto failed;
1541 talloc_steal(ldb, ntds_guid);
1542 talloc_free(tmp_ctx);
1544 return ntds_guid;
1546 failed:
1547 DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1548 talloc_free(tmp_ctx);
1549 return NULL;
1552 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1554 TALLOC_CTX *tmp_ctx;
1555 struct GUID *ntds_guid_new;
1556 struct GUID *ntds_guid_old;
1558 /* see if we have a cached copy */
1559 ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1561 tmp_ctx = talloc_new(ldb);
1562 if (tmp_ctx == NULL) {
1563 goto failed;
1566 ntds_guid_new = talloc(tmp_ctx, struct GUID);
1567 if (!ntds_guid_new) {
1568 goto failed;
1571 *ntds_guid_new = *ntds_guid_in;
1573 /* cache the domain_sid in the ldb */
1574 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1575 goto failed;
1578 talloc_steal(ldb, ntds_guid_new);
1579 talloc_free(tmp_ctx);
1580 talloc_free(ntds_guid_old);
1582 return true;
1584 failed:
1585 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1586 talloc_free(tmp_ctx);
1587 return false;
1591 work out the server dn for the current open ldb
1593 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1595 return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1599 work out the server dn for the current open ldb
1601 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1603 struct ldb_dn *server_dn;
1604 struct ldb_dn *servers_dn;
1605 struct ldb_dn *server_site_dn;
1607 /* TODO: there must be a saner way to do this!! */
1608 server_dn = samdb_server_dn(ldb, mem_ctx);
1609 if (!server_dn) return NULL;
1611 servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1612 talloc_free(server_dn);
1613 if (!servers_dn) return NULL;
1615 server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1616 talloc_free(servers_dn);
1618 return server_site_dn;
1622 find a 'reference' DN that points at another object
1623 (eg. serverReference, rIDManagerReference etc)
1625 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1626 const char *attribute, struct ldb_dn **dn)
1628 const char *attrs[2];
1629 struct ldb_result *res;
1630 int ret;
1632 attrs[0] = attribute;
1633 attrs[1] = NULL;
1635 ret = ldb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, NULL);
1636 if (ret != LDB_SUCCESS) {
1637 return ret;
1639 if (res->count != 1) {
1640 talloc_free(res);
1641 return LDB_ERR_NO_SUCH_OBJECT;
1644 *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1645 if (!*dn) {
1646 talloc_free(res);
1647 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1650 talloc_free(res);
1651 return LDB_SUCCESS;
1655 find our machine account via the serverReference attribute in the
1656 server DN
1658 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1660 struct ldb_dn *server_dn;
1661 int ret;
1663 server_dn = samdb_server_dn(ldb, mem_ctx);
1664 if (server_dn == NULL) {
1665 return LDB_ERR_NO_SUCH_OBJECT;
1668 ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1669 talloc_free(server_dn);
1671 return ret;
1675 find the RID Manager$ DN via the rIDManagerReference attribute in the
1676 base DN
1678 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1680 return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1681 "rIDManagerReference", dn);
1685 find the RID Set DN via the rIDSetReferences attribute in our
1686 machine account DN
1688 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1690 struct ldb_dn *server_ref_dn;
1691 int ret;
1693 ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1694 if (ret != LDB_SUCCESS) {
1695 return ret;
1697 ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1698 talloc_free(server_ref_dn);
1699 return ret;
1702 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1704 const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1705 mem_ctx));
1707 if (val == NULL) {
1708 return NULL;
1711 return (const char *) val->data;
1715 * Finds the client site by using the client's IP address.
1716 * The "subnet_name" returns the name of the subnet if parameter != NULL
1718 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1719 const char *ip_address, char **subnet_name)
1721 const char *attrs[] = { "cn", "siteObject", NULL };
1722 struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1723 struct ldb_result *res;
1724 const struct ldb_val *val;
1725 const char *site_name = NULL, *l_subnet_name = NULL;
1726 const char *allow_list[2] = { NULL, NULL };
1727 unsigned int i, count;
1728 int cnt, ret;
1731 * if we don't have a client ip e.g. ncalrpc
1732 * the server site is the client site
1734 if (ip_address == NULL) {
1735 return samdb_server_site_name(ldb, mem_ctx);
1738 sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1739 if (sites_container_dn == NULL) {
1740 return NULL;
1743 subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1744 if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1745 talloc_free(sites_container_dn);
1746 talloc_free(subnets_dn);
1747 return NULL;
1750 ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1751 attrs, NULL);
1752 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1753 count = 0;
1754 } else if (ret != LDB_SUCCESS) {
1755 talloc_free(sites_container_dn);
1756 talloc_free(subnets_dn);
1757 return NULL;
1758 } else {
1759 count = res->count;
1762 for (i = 0; i < count; i++) {
1763 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1764 NULL);
1766 allow_list[0] = l_subnet_name;
1768 if (allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1769 sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1770 res->msgs[i],
1771 "siteObject");
1772 if (sites_dn == NULL) {
1773 /* No reference, maybe another subnet matches */
1774 continue;
1777 /* "val" cannot be NULL here since "sites_dn" != NULL */
1778 val = ldb_dn_get_rdn_val(sites_dn);
1779 site_name = talloc_strdup(mem_ctx,
1780 (const char *) val->data);
1782 talloc_free(sites_dn);
1784 break;
1788 if (site_name == NULL) {
1789 /* This is the Windows Server fallback rule: when no subnet
1790 * exists and we have only one site available then use it (it
1791 * is for sure the same as our server site). If more sites do
1792 * exist then we don't know which one to use and set the site
1793 * name to "". */
1794 cnt = samdb_search_count(ldb, sites_container_dn,
1795 "(objectClass=site)");
1796 if (cnt == 1) {
1797 site_name = samdb_server_site_name(ldb, mem_ctx);
1798 } else {
1799 site_name = talloc_strdup(mem_ctx, "");
1801 l_subnet_name = NULL;
1804 if (subnet_name != NULL) {
1805 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1808 talloc_free(sites_container_dn);
1809 talloc_free(subnets_dn);
1810 talloc_free(res);
1812 return site_name;
1816 work out if we are the PDC for the domain of the current open ldb
1818 bool samdb_is_pdc(struct ldb_context *ldb)
1820 const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1821 int ret;
1822 struct ldb_result *dom_res;
1823 TALLOC_CTX *tmp_ctx;
1824 bool is_pdc;
1825 struct ldb_dn *pdc;
1827 tmp_ctx = talloc_new(ldb);
1828 if (tmp_ctx == NULL) {
1829 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1830 return false;
1833 ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1834 if (ret != LDB_SUCCESS) {
1835 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n",
1836 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
1837 ldb_errstring(ldb)));
1838 goto failed;
1840 if (dom_res->count != 1) {
1841 goto failed;
1844 pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1846 if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1847 is_pdc = true;
1848 } else {
1849 is_pdc = false;
1852 talloc_free(tmp_ctx);
1854 return is_pdc;
1856 failed:
1857 DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1858 talloc_free(tmp_ctx);
1859 return false;
1863 work out if we are a Global Catalog server for the domain of the current open ldb
1865 bool samdb_is_gc(struct ldb_context *ldb)
1867 const char *attrs[] = { "options", NULL };
1868 int ret, options;
1869 struct ldb_result *res;
1870 TALLOC_CTX *tmp_ctx;
1872 tmp_ctx = talloc_new(ldb);
1873 if (tmp_ctx == NULL) {
1874 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1875 return false;
1878 /* Query cn=ntds settings,.... */
1879 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1880 if (ret != LDB_SUCCESS) {
1881 talloc_free(tmp_ctx);
1882 return false;
1884 if (res->count != 1) {
1885 talloc_free(tmp_ctx);
1886 return false;
1889 options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1890 talloc_free(tmp_ctx);
1892 /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1893 if (options & 0x000000001) {
1894 return true;
1896 return false;
1899 /* Find a domain object in the parents of a particular DN. */
1900 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1901 struct ldb_dn **parent_dn, const char **errstring)
1903 TALLOC_CTX *local_ctx;
1904 struct ldb_dn *sdn = dn;
1905 struct ldb_result *res = NULL;
1906 int ret = LDB_SUCCESS;
1907 const char *attrs[] = { NULL };
1909 local_ctx = talloc_new(mem_ctx);
1910 if (local_ctx == NULL) return ldb_oom(ldb);
1912 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1913 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1914 "(|(objectClass=domain)(objectClass=builtinDomain))");
1915 if (ret == LDB_SUCCESS) {
1916 if (res->count == 1) {
1917 break;
1919 } else {
1920 break;
1924 if (ret != LDB_SUCCESS) {
1925 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1926 ldb_dn_get_linearized(dn),
1927 ldb_dn_get_linearized(sdn),
1928 ldb_errstring(ldb));
1929 talloc_free(local_ctx);
1930 return ret;
1932 if (res->count != 1) {
1933 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1934 ldb_dn_get_linearized(dn));
1935 DEBUG(0,(__location__ ": %s\n", *errstring));
1936 talloc_free(local_ctx);
1937 return LDB_ERR_CONSTRAINT_VIOLATION;
1940 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1941 talloc_free(local_ctx);
1942 return ret;
1947 * Performs checks on a user password (plaintext UNIX format - attribute
1948 * "password"). The remaining parameters have to be extracted from the domain
1949 * object in the AD.
1951 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1953 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1954 const uint32_t pwdProperties,
1955 const uint32_t minPwdLength)
1957 /* checks if the "minPwdLength" property is satisfied */
1958 if (minPwdLength > password->length)
1959 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1961 /* checks the password complexity */
1962 if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1963 && (password->data != NULL)
1964 && (!check_password_quality((const char *) password->data)))
1965 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1967 return SAMR_VALIDATION_STATUS_SUCCESS;
1971 * Callback for "samdb_set_password" password change
1973 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
1975 int ret;
1977 if (!ares) {
1978 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1981 if (ares->error != LDB_SUCCESS) {
1982 ret = ares->error;
1983 req->context = talloc_steal(req,
1984 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1985 talloc_free(ares);
1986 return ldb_request_done(req, ret);
1989 if (ares->type != LDB_REPLY_DONE) {
1990 talloc_free(ares);
1991 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1994 req->context = talloc_steal(req,
1995 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1996 talloc_free(ares);
1997 return ldb_request_done(req, LDB_SUCCESS);
2001 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2002 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2003 * as parameter if it's a user change or not ("userChange"). The "rejectReason"
2004 * gives some more informations if the changed failed.
2006 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2007 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2008 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2010 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2011 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2012 const DATA_BLOB *new_password,
2013 struct samr_Password *lmNewHash,
2014 struct samr_Password *ntNewHash,
2015 bool user_change,
2016 enum samPwdChangeReason *reject_reason,
2017 struct samr_DomInfo1 **_dominfo)
2019 struct ldb_message *msg;
2020 struct ldb_message_element *el;
2021 struct ldb_request *req;
2022 struct dsdb_control_password_change_status *pwd_stat = NULL;
2023 int ret;
2024 NTSTATUS status;
2026 #define CHECK_RET(x) \
2027 if (x != LDB_SUCCESS) { \
2028 talloc_free(msg); \
2029 return NT_STATUS_NO_MEMORY; \
2032 msg = ldb_msg_new(mem_ctx);
2033 if (msg == NULL) {
2034 return NT_STATUS_NO_MEMORY;
2036 msg->dn = user_dn;
2037 if ((new_password != NULL)
2038 && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2039 /* we have the password as plaintext UTF16 */
2040 CHECK_RET(samdb_msg_add_value(ldb, mem_ctx, msg,
2041 "clearTextPassword", new_password));
2042 el = ldb_msg_find_element(msg, "clearTextPassword");
2043 el->flags = LDB_FLAG_MOD_REPLACE;
2044 } else if ((new_password == NULL)
2045 && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2046 /* we have a password as LM and/or NT hash */
2047 if (lmNewHash != NULL) {
2048 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2049 "dBCSPwd", lmNewHash));
2050 el = ldb_msg_find_element(msg, "dBCSPwd");
2051 el->flags = LDB_FLAG_MOD_REPLACE;
2053 if (ntNewHash != NULL) {
2054 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2055 "unicodePwd", ntNewHash));
2056 el = ldb_msg_find_element(msg, "unicodePwd");
2057 el->flags = LDB_FLAG_MOD_REPLACE;
2059 } else {
2060 /* the password wasn't specified correctly */
2061 talloc_free(msg);
2062 return NT_STATUS_INVALID_PARAMETER;
2065 /* build modify request */
2066 ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2067 samdb_set_password_callback, NULL);
2068 if (ret != LDB_SUCCESS) {
2069 talloc_free(msg);
2070 return NT_STATUS_NO_MEMORY;
2073 if (user_change) {
2074 /* a user password change and we've checked already the old
2075 * password somewhere else (callers responsability) */
2076 ret = ldb_request_add_control(req,
2077 DSDB_CONTROL_PASSWORD_CHANGE_OLD_PW_CHECKED_OID,
2078 true, NULL);
2079 if (ret != LDB_SUCCESS) {
2080 talloc_free(req);
2081 talloc_free(msg);
2082 return NT_STATUS_NO_MEMORY;
2085 ret = ldb_request_add_control(req,
2086 DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2087 true, NULL);
2088 if (ret != LDB_SUCCESS) {
2089 talloc_free(req);
2090 talloc_free(msg);
2091 return NT_STATUS_NO_MEMORY;
2093 ret = ldb_request_add_control(req,
2094 DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2095 true, NULL);
2096 if (ret != LDB_SUCCESS) {
2097 talloc_free(req);
2098 talloc_free(msg);
2099 return NT_STATUS_NO_MEMORY;
2102 ret = dsdb_autotransaction_request(ldb, req);
2104 if (req->context != NULL) {
2105 pwd_stat = talloc_steal(mem_ctx,
2106 ((struct ldb_control *)req->context)->data);
2109 talloc_free(req);
2110 talloc_free(msg);
2112 /* Sets the domain info (if requested) */
2113 if (_dominfo != NULL) {
2114 struct samr_DomInfo1 *dominfo;
2116 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2117 if (dominfo == NULL) {
2118 return NT_STATUS_NO_MEMORY;
2121 if (pwd_stat != NULL) {
2122 dominfo->min_password_length = pwd_stat->domain_data.minPwdLength;
2123 dominfo->password_properties = pwd_stat->domain_data.pwdProperties;
2124 dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2125 dominfo->max_password_age = pwd_stat->domain_data.maxPwdAge;
2126 dominfo->min_password_age = pwd_stat->domain_data.minPwdAge;
2129 *_dominfo = dominfo;
2132 if (reject_reason != NULL) {
2133 if (pwd_stat != NULL) {
2134 *reject_reason = pwd_stat->reject_reason;
2135 } else {
2136 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2140 if (pwd_stat != NULL) {
2141 talloc_free(pwd_stat);
2144 /* TODO: Error results taken from "password_hash" module. Are they
2145 correct? */
2146 if (ret == LDB_ERR_UNWILLING_TO_PERFORM) {
2147 status = NT_STATUS_WRONG_PASSWORD;
2148 } else if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2149 status = NT_STATUS_PASSWORD_RESTRICTION;
2150 } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2151 status = NT_STATUS_WRONG_PASSWORD;
2152 } else if (ret != LDB_SUCCESS) {
2153 status = NT_STATUS_UNSUCCESSFUL;
2154 } else {
2155 status = NT_STATUS_OK;
2158 return status;
2162 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2163 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2164 * as parameter if it's a user change or not ("userChange"). The "rejectReason"
2165 * gives some more informations if the changed failed.
2167 * This wrapper function for "samdb_set_password" takes a SID as input rather
2168 * than a user DN.
2170 * This call encapsulates a new LDB transaction for changing the password;
2171 * therefore the user hasn't to start a new one.
2173 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2174 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2175 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2177 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2178 const struct dom_sid *user_sid,
2179 const DATA_BLOB *new_password,
2180 struct samr_Password *lmNewHash,
2181 struct samr_Password *ntNewHash,
2182 bool user_change,
2183 enum samPwdChangeReason *reject_reason,
2184 struct samr_DomInfo1 **_dominfo)
2186 NTSTATUS nt_status;
2187 struct ldb_dn *user_dn;
2188 int ret;
2190 ret = ldb_transaction_start(ldb);
2191 if (ret != LDB_SUCCESS) {
2192 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2193 return NT_STATUS_TRANSACTION_ABORTED;
2196 user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2197 "(&(objectSid=%s)(objectClass=user))",
2198 ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2199 if (!user_dn) {
2200 ldb_transaction_cancel(ldb);
2201 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2202 dom_sid_string(mem_ctx, user_sid)));
2203 return NT_STATUS_NO_SUCH_USER;
2206 nt_status = samdb_set_password(ldb, mem_ctx,
2207 user_dn, NULL,
2208 new_password,
2209 lmNewHash, ntNewHash,
2210 user_change,
2211 reject_reason, _dominfo);
2212 if (!NT_STATUS_IS_OK(nt_status)) {
2213 ldb_transaction_cancel(ldb);
2214 talloc_free(user_dn);
2215 return nt_status;
2218 ret = ldb_transaction_commit(ldb);
2219 if (ret != LDB_SUCCESS) {
2220 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2221 ldb_dn_get_linearized(user_dn),
2222 ldb_errstring(ldb)));
2223 talloc_free(user_dn);
2224 return NT_STATUS_TRANSACTION_ABORTED;
2227 talloc_free(user_dn);
2228 return NT_STATUS_OK;
2232 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
2233 struct dom_sid *sid, struct ldb_dn **ret_dn)
2235 struct ldb_message *msg;
2236 struct ldb_dn *basedn;
2237 char *sidstr;
2238 int ret;
2240 sidstr = dom_sid_string(mem_ctx, sid);
2241 NT_STATUS_HAVE_NO_MEMORY(sidstr);
2243 /* We might have to create a ForeignSecurityPrincipal, even if this user
2244 * is in our own domain */
2246 msg = ldb_msg_new(sidstr);
2247 if (msg == NULL) {
2248 talloc_free(sidstr);
2249 return NT_STATUS_NO_MEMORY;
2252 ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2253 ldb_get_default_basedn(sam_ctx),
2254 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2255 &basedn);
2256 if (ret != LDB_SUCCESS) {
2257 DEBUG(0, ("Failed to find DN for "
2258 "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2259 talloc_free(sidstr);
2260 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2263 /* add core elements to the ldb_message for the alias */
2264 msg->dn = basedn;
2265 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2266 talloc_free(sidstr);
2267 return NT_STATUS_NO_MEMORY;
2270 samdb_msg_add_string(sam_ctx, msg, msg,
2271 "objectClass",
2272 "foreignSecurityPrincipal");
2274 /* create the alias */
2275 ret = ldb_add(sam_ctx, msg);
2276 if (ret != LDB_SUCCESS) {
2277 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2278 "record %s: %s\n",
2279 ldb_dn_get_linearized(msg->dn),
2280 ldb_errstring(sam_ctx)));
2281 talloc_free(sidstr);
2282 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2285 *ret_dn = talloc_steal(mem_ctx, msg->dn);
2286 talloc_free(sidstr);
2288 return NT_STATUS_OK;
2293 Find the DN of a domain, assuming it to be a dotted.dns name
2296 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
2298 unsigned int i;
2299 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2300 const char *binary_encoded;
2301 const char **split_realm;
2302 struct ldb_dn *dn;
2304 if (!tmp_ctx) {
2305 return NULL;
2308 split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2309 if (!split_realm) {
2310 talloc_free(tmp_ctx);
2311 return NULL;
2313 dn = ldb_dn_new(mem_ctx, ldb, NULL);
2314 for (i=0; split_realm[i]; i++) {
2315 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2316 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2317 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2318 binary_encoded, ldb_dn_get_linearized(dn)));
2319 talloc_free(tmp_ctx);
2320 return NULL;
2323 if (!ldb_dn_validate(dn)) {
2324 DEBUG(2, ("Failed to validated DN %s\n",
2325 ldb_dn_get_linearized(dn)));
2326 talloc_free(tmp_ctx);
2327 return NULL;
2329 talloc_free(tmp_ctx);
2330 return dn;
2334 Find the DN of a domain, be it the netbios or DNS name
2336 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2337 const char *domain_name)
2339 const char * const domain_ref_attrs[] = {
2340 "ncName", NULL
2342 const char * const domain_ref2_attrs[] = {
2343 NULL
2345 struct ldb_result *res_domain_ref;
2346 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2347 /* find the domain's DN */
2348 int ret_domain = ldb_search(ldb, mem_ctx,
2349 &res_domain_ref,
2350 samdb_partitions_dn(ldb, mem_ctx),
2351 LDB_SCOPE_ONELEVEL,
2352 domain_ref_attrs,
2353 "(&(nETBIOSName=%s)(objectclass=crossRef))",
2354 escaped_domain);
2355 if (ret_domain != LDB_SUCCESS) {
2356 return NULL;
2359 if (res_domain_ref->count == 0) {
2360 ret_domain = ldb_search(ldb, mem_ctx,
2361 &res_domain_ref,
2362 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2363 LDB_SCOPE_BASE,
2364 domain_ref2_attrs,
2365 "(objectclass=domain)");
2366 if (ret_domain != LDB_SUCCESS) {
2367 return NULL;
2370 if (res_domain_ref->count == 1) {
2371 return res_domain_ref->msgs[0]->dn;
2373 return NULL;
2376 if (res_domain_ref->count > 1) {
2377 DEBUG(0,("Found %d records matching domain [%s]\n",
2378 ret_domain, domain_name));
2379 return NULL;
2382 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2388 use a GUID to find a DN
2390 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
2391 TALLOC_CTX *mem_ctx,
2392 const struct GUID *guid, struct ldb_dn **dn)
2394 int ret;
2395 struct ldb_result *res;
2396 const char *attrs[] = { NULL };
2397 char *guid_str = GUID_string(mem_ctx, guid);
2399 if (!guid_str) {
2400 return ldb_operr(ldb);
2403 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2404 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2405 DSDB_SEARCH_SHOW_EXTENDED_DN |
2406 DSDB_SEARCH_ONE_ONLY,
2407 "objectGUID=%s", guid_str);
2408 talloc_free(guid_str);
2409 if (ret != LDB_SUCCESS) {
2410 return ret;
2413 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2414 talloc_free(res);
2416 return LDB_SUCCESS;
2420 use a DN to find a GUID with a given attribute name
2422 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2423 struct ldb_dn *dn, const char *attribute,
2424 struct GUID *guid)
2426 int ret;
2427 struct ldb_result *res;
2428 const char *attrs[2];
2429 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2431 attrs[0] = attribute;
2432 attrs[1] = NULL;
2434 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2435 if (ret != LDB_SUCCESS) {
2436 talloc_free(tmp_ctx);
2437 return ret;
2439 if (res->count < 1) {
2440 talloc_free(tmp_ctx);
2441 return LDB_ERR_NO_SUCH_OBJECT;
2443 *guid = samdb_result_guid(res->msgs[0], attribute);
2444 talloc_free(tmp_ctx);
2445 return LDB_SUCCESS;
2449 use a DN to find a GUID
2451 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2452 struct ldb_dn *dn, struct GUID *guid)
2454 return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2460 adds the given GUID to the given ldb_message. This value is added
2461 for the given attr_name (may be either "objectGUID" or "parentGUID").
2463 int dsdb_msg_add_guid(struct ldb_message *msg,
2464 struct GUID *guid,
2465 const char *attr_name)
2467 int ret;
2468 struct ldb_val v;
2469 NTSTATUS status;
2470 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
2472 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2473 if (!NT_STATUS_IS_OK(status)) {
2474 ret = LDB_ERR_OPERATIONS_ERROR;
2475 goto done;
2478 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2479 if (ret != LDB_SUCCESS) {
2480 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2481 attr_name));
2482 goto done;
2485 ret = LDB_SUCCESS;
2487 done:
2488 talloc_free(tmp_ctx);
2489 return ret;
2495 use a DN to find a SID
2497 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
2498 struct ldb_dn *dn, struct dom_sid *sid)
2500 int ret;
2501 struct ldb_result *res;
2502 const char *attrs[] = { "objectSID", NULL };
2503 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2504 struct dom_sid *s;
2506 ZERO_STRUCTP(sid);
2508 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2509 if (ret != LDB_SUCCESS) {
2510 talloc_free(tmp_ctx);
2511 return ret;
2513 if (res->count < 1) {
2514 talloc_free(tmp_ctx);
2515 return LDB_ERR_NO_SUCH_OBJECT;
2517 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2518 if (s == NULL) {
2519 talloc_free(tmp_ctx);
2520 return LDB_ERR_NO_SUCH_OBJECT;
2522 *sid = *s;
2523 talloc_free(tmp_ctx);
2524 return LDB_SUCCESS;
2528 use a SID to find a DN
2530 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
2531 TALLOC_CTX *mem_ctx,
2532 struct dom_sid *sid, struct ldb_dn **dn)
2534 int ret;
2535 struct ldb_result *res;
2536 const char *attrs[] = { NULL };
2537 char *sid_str = dom_sid_string(mem_ctx, sid);
2539 if (!sid_str) {
2540 return ldb_operr(ldb);
2543 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2544 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2545 DSDB_SEARCH_SHOW_EXTENDED_DN |
2546 DSDB_SEARCH_ONE_ONLY,
2547 "objectSID=%s", sid_str);
2548 talloc_free(sid_str);
2549 if (ret != LDB_SUCCESS) {
2550 return ret;
2553 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2554 talloc_free(res);
2556 return LDB_SUCCESS;
2560 load a repsFromTo blob list for a given partition GUID
2561 attr must be "repsFrom" or "repsTo"
2563 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2564 const char *attr, struct repsFromToBlob **r, uint32_t *count)
2566 const char *attrs[] = { attr, NULL };
2567 struct ldb_result *res = NULL;
2568 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2569 unsigned int i;
2570 struct ldb_message_element *el;
2572 *r = NULL;
2573 *count = 0;
2575 if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2576 res->count < 1) {
2577 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2578 talloc_free(tmp_ctx);
2579 return WERR_DS_DRA_INTERNAL_ERROR;
2582 el = ldb_msg_find_element(res->msgs[0], attr);
2583 if (el == NULL) {
2584 /* it's OK to be empty */
2585 talloc_free(tmp_ctx);
2586 return WERR_OK;
2589 *count = el->num_values;
2590 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2591 if (*r == NULL) {
2592 talloc_free(tmp_ctx);
2593 return WERR_DS_DRA_INTERNAL_ERROR;
2596 for (i=0; i<(*count); i++) {
2597 enum ndr_err_code ndr_err;
2598 ndr_err = ndr_pull_struct_blob(&el->values[i],
2599 mem_ctx,
2600 &(*r)[i],
2601 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2602 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2603 talloc_free(tmp_ctx);
2604 return WERR_DS_DRA_INTERNAL_ERROR;
2608 talloc_free(tmp_ctx);
2610 return WERR_OK;
2614 save the repsFromTo blob list for a given partition GUID
2615 attr must be "repsFrom" or "repsTo"
2617 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2618 const char *attr, struct repsFromToBlob *r, uint32_t count)
2620 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2621 struct ldb_message *msg;
2622 struct ldb_message_element *el;
2623 unsigned int i;
2625 msg = ldb_msg_new(tmp_ctx);
2626 msg->dn = dn;
2627 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2628 goto failed;
2631 el->values = talloc_array(msg, struct ldb_val, count);
2632 if (!el->values) {
2633 goto failed;
2636 for (i=0; i<count; i++) {
2637 struct ldb_val v;
2638 enum ndr_err_code ndr_err;
2640 ndr_err = ndr_push_struct_blob(&v, tmp_ctx,
2641 &r[i],
2642 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2643 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2644 goto failed;
2647 el->num_values++;
2648 el->values[i] = v;
2651 if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2652 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2653 goto failed;
2656 talloc_free(tmp_ctx);
2658 return WERR_OK;
2660 failed:
2661 talloc_free(tmp_ctx);
2662 return WERR_DS_DRA_INTERNAL_ERROR;
2667 load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2668 object for a partition
2670 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2671 uint64_t *uSN, uint64_t *urgent_uSN)
2673 struct ldb_request *req;
2674 int ret;
2675 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2676 struct dsdb_control_current_partition *p_ctrl;
2677 struct ldb_result *res;
2679 res = talloc_zero(tmp_ctx, struct ldb_result);
2680 if (!res) {
2681 talloc_free(tmp_ctx);
2682 return ldb_oom(ldb);
2685 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2686 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2687 LDB_SCOPE_BASE,
2688 NULL, NULL,
2689 NULL,
2690 res, ldb_search_default_callback,
2691 NULL);
2692 if (ret != LDB_SUCCESS) {
2693 talloc_free(tmp_ctx);
2694 return ret;
2697 p_ctrl = talloc(req, struct dsdb_control_current_partition);
2698 if (p_ctrl == NULL) {
2699 talloc_free(tmp_ctx);
2700 return ldb_oom(ldb);
2702 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2703 p_ctrl->dn = dn;
2705 ret = ldb_request_add_control(req,
2706 DSDB_CONTROL_CURRENT_PARTITION_OID,
2707 false, p_ctrl);
2708 if (ret != LDB_SUCCESS) {
2709 talloc_free(tmp_ctx);
2710 return ret;
2713 /* Run the new request */
2714 ret = ldb_request(ldb, req);
2716 if (ret == LDB_SUCCESS) {
2717 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2720 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2721 /* it hasn't been created yet, which means
2722 an implicit value of zero */
2723 *uSN = 0;
2724 talloc_free(tmp_ctx);
2725 return LDB_SUCCESS;
2728 if (ret != LDB_SUCCESS) {
2729 talloc_free(tmp_ctx);
2730 return ret;
2733 if (res->count < 1) {
2734 *uSN = 0;
2735 if (urgent_uSN) {
2736 *urgent_uSN = 0;
2738 } else {
2739 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2740 if (urgent_uSN) {
2741 *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2745 talloc_free(tmp_ctx);
2747 return LDB_SUCCESS;
2750 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2751 const struct drsuapi_DsReplicaCursor2 *c2)
2753 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2756 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2757 const struct drsuapi_DsReplicaCursor *c2)
2759 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2764 see if a computer identified by its invocationId is a RODC
2766 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
2768 /* 1) find the DN for this servers NTDSDSA object
2769 2) search for the msDS-isRODC attribute
2770 3) if not present then not a RODC
2771 4) if present and TRUE then is a RODC
2773 struct ldb_dn *config_dn;
2774 const char *attrs[] = { "msDS-isRODC", NULL };
2775 int ret;
2776 struct ldb_result *res;
2777 TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
2779 config_dn = ldb_get_config_basedn(sam_ctx);
2780 if (!config_dn) {
2781 talloc_free(tmp_ctx);
2782 return ldb_operr(sam_ctx);
2785 ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
2786 DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
2788 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2789 *is_rodc = false;
2790 talloc_free(tmp_ctx);
2791 return LDB_SUCCESS;
2794 if (ret != LDB_SUCCESS) {
2795 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
2796 GUID_string(tmp_ctx, objectGUID)));
2797 *is_rodc = false;
2798 talloc_free(tmp_ctx);
2799 return ret;
2802 ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
2803 *is_rodc = (ret == 1);
2805 talloc_free(tmp_ctx);
2806 return LDB_SUCCESS;
2811 see if we are a RODC
2813 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
2815 const struct GUID *objectGUID;
2816 int ret;
2817 bool *cached;
2819 /* see if we have a cached copy */
2820 cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
2821 if (cached) {
2822 *am_rodc = *cached;
2823 return LDB_SUCCESS;
2826 objectGUID = samdb_ntds_objectGUID(sam_ctx);
2827 if (!objectGUID) {
2828 return ldb_operr(sam_ctx);
2831 ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
2832 if (ret != LDB_SUCCESS) {
2833 return ret;
2836 cached = talloc(sam_ctx, bool);
2837 if (cached == NULL) {
2838 return ldb_oom(sam_ctx);
2840 *cached = *am_rodc;
2842 ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
2843 if (ret != LDB_SUCCESS) {
2844 talloc_free(cached);
2845 return ldb_operr(sam_ctx);
2848 return LDB_SUCCESS;
2851 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
2853 TALLOC_CTX *tmp_ctx;
2854 bool *cached;
2856 tmp_ctx = talloc_new(ldb);
2857 if (tmp_ctx == NULL) {
2858 goto failed;
2861 cached = talloc(tmp_ctx, bool);
2862 if (!cached) {
2863 goto failed;
2866 *cached = am_rodc;
2867 if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
2868 goto failed;
2871 talloc_steal(ldb, cached);
2872 talloc_free(tmp_ctx);
2873 return true;
2875 failed:
2876 DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
2877 talloc_free(tmp_ctx);
2878 return false;
2883 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
2885 flags are DS_NTDS_OPTION_*
2887 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2889 TALLOC_CTX *tmp_ctx;
2890 const char *attrs[] = { "options", NULL };
2891 int ret;
2892 struct ldb_result *res;
2894 tmp_ctx = talloc_new(ldb);
2895 if (tmp_ctx == NULL) {
2896 goto failed;
2899 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2900 if (ret != LDB_SUCCESS) {
2901 goto failed;
2904 if (res->count != 1) {
2905 goto failed;
2908 *options = samdb_result_uint(res->msgs[0], "options", 0);
2910 talloc_free(tmp_ctx);
2912 return LDB_SUCCESS;
2914 failed:
2915 DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
2916 talloc_free(tmp_ctx);
2917 return LDB_ERR_NO_SUCH_OBJECT;
2920 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
2922 const char *attrs[] = { "objectCategory", NULL };
2923 int ret;
2924 struct ldb_result *res;
2926 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2927 if (ret != LDB_SUCCESS) {
2928 goto failed;
2931 if (res->count != 1) {
2932 goto failed;
2935 return samdb_result_string(res->msgs[0], "objectCategory", NULL);
2937 failed:
2938 DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
2939 return NULL;
2943 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
2944 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
2946 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
2948 char **tokens, *ret;
2949 size_t i;
2951 tokens = str_list_make(mem_ctx, cn, " -_");
2952 if (tokens == NULL)
2953 return NULL;
2955 /* "tolower()" and "toupper()" should also work properly on 0x00 */
2956 tokens[0][0] = tolower(tokens[0][0]);
2957 for (i = 1; i < str_list_length((const char **)tokens); i++)
2958 tokens[i][0] = toupper(tokens[i][0]);
2960 ret = talloc_strdup(mem_ctx, tokens[0]);
2961 for (i = 1; i < str_list_length((const char **)tokens); i++)
2962 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
2964 talloc_free(tokens);
2966 return ret;
2970 * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
2972 int dsdb_functional_level(struct ldb_context *ldb)
2974 int *domainFunctionality =
2975 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
2976 if (!domainFunctionality) {
2977 DEBUG(0,(__location__ ": WARNING: domainFunctionality not setup\n"));
2978 return DS_DOMAIN_FUNCTION_2000;
2980 return *domainFunctionality;
2984 * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
2986 int dsdb_forest_functional_level(struct ldb_context *ldb)
2988 int *forestFunctionality =
2989 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
2990 if (!forestFunctionality) {
2991 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
2992 return DS_DOMAIN_FUNCTION_2000;
2994 return *forestFunctionality;
2998 set a GUID in an extended DN structure
3000 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3002 struct ldb_val v;
3003 NTSTATUS status;
3004 int ret;
3006 status = GUID_to_ndr_blob(guid, dn, &v);
3007 if (!NT_STATUS_IS_OK(status)) {
3008 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3011 ret = ldb_dn_set_extended_component(dn, component_name, &v);
3012 data_blob_free(&v);
3013 return ret;
3017 return a GUID from a extended DN structure
3019 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3021 const struct ldb_val *v;
3023 v = ldb_dn_get_extended_component(dn, component_name);
3024 if (v == NULL) {
3025 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3028 return GUID_from_ndr_blob(v, guid);
3032 return a uint64_t from a extended DN structure
3034 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3036 const struct ldb_val *v;
3037 char *s;
3039 v = ldb_dn_get_extended_component(dn, component_name);
3040 if (v == NULL) {
3041 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3043 s = talloc_strndup(dn, (const char *)v->data, v->length);
3044 NT_STATUS_HAVE_NO_MEMORY(s);
3046 *val = strtoull(s, NULL, 0);
3048 talloc_free(s);
3049 return NT_STATUS_OK;
3053 return a NTTIME from a extended DN structure
3055 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3057 return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3061 return a uint32_t from a extended DN structure
3063 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3065 const struct ldb_val *v;
3066 char *s;
3068 v = ldb_dn_get_extended_component(dn, component_name);
3069 if (v == NULL) {
3070 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3073 s = talloc_strndup(dn, (const char *)v->data, v->length);
3074 NT_STATUS_HAVE_NO_MEMORY(s);
3076 *val = strtoul(s, NULL, 0);
3078 talloc_free(s);
3079 return NT_STATUS_OK;
3083 return a dom_sid from a extended DN structure
3085 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3087 const struct ldb_val *sid_blob;
3088 struct TALLOC_CTX *tmp_ctx;
3089 enum ndr_err_code ndr_err;
3091 sid_blob = ldb_dn_get_extended_component(dn, "SID");
3092 if (!sid_blob) {
3093 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3096 tmp_ctx = talloc_new(NULL);
3098 ndr_err = ndr_pull_struct_blob_all(sid_blob, tmp_ctx, sid,
3099 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3100 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3101 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3102 talloc_free(tmp_ctx);
3103 return status;
3106 talloc_free(tmp_ctx);
3107 return NT_STATUS_OK;
3112 return RMD_FLAGS directly from a ldb_dn
3113 returns 0 if not found
3115 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3117 const struct ldb_val *v;
3118 char buf[32];
3119 v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
3120 if (!v || v->length > sizeof(buf)-1) return 0;
3121 strncpy(buf, (const char *)v->data, v->length);
3122 buf[v->length] = 0;
3123 return strtoul(buf, NULL, 10);
3127 return RMD_FLAGS directly from a ldb_val for a DN
3128 returns 0 if RMD_FLAGS is not found
3130 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3132 const char *p;
3133 uint32_t flags;
3134 char *end;
3136 if (val->length < 13) {
3137 return 0;
3139 p = memmem(val->data, val->length-2, "<RMD_FLAGS=", 11);
3140 if (!p) {
3141 return 0;
3143 flags = strtoul(p+11, &end, 10);
3144 if (!end || *end != '>') {
3145 /* it must end in a > */
3146 return 0;
3148 return flags;
3152 return true if a ldb_val containing a DN in storage form is deleted
3154 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3156 return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3160 return true if a ldb_val containing a DN in storage form is
3161 in the upgraded w2k3 linked attribute format
3163 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3165 return memmem(val->data, val->length, "<RMD_ADDTIME=", 13) != NULL;
3169 return a DN for a wellknown GUID
3171 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3172 struct ldb_dn *nc_root, const char *wk_guid,
3173 struct ldb_dn **wkguid_dn)
3175 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3176 const char *attrs[] = { NULL };
3177 int ret;
3178 struct ldb_dn *dn;
3179 struct ldb_result *res;
3181 /* construct the magic WKGUID DN */
3182 dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3183 wk_guid, ldb_dn_get_linearized(nc_root));
3184 if (!wkguid_dn) {
3185 talloc_free(tmp_ctx);
3186 return ldb_operr(samdb);
3189 ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
3190 if (ret != LDB_SUCCESS) {
3191 talloc_free(tmp_ctx);
3192 return ret;
3195 (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3196 talloc_free(tmp_ctx);
3197 return LDB_SUCCESS;
3201 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3203 return ldb_dn_compare(*dn1, *dn2);
3207 find a NC root given a DN within the NC
3209 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3210 struct ldb_dn **nc_root)
3212 const char *root_attrs[] = { "namingContexts", NULL };
3213 TALLOC_CTX *tmp_ctx;
3214 int ret;
3215 struct ldb_message_element *el;
3216 struct ldb_result *root_res;
3217 unsigned int i;
3218 struct ldb_dn **nc_dns;
3220 tmp_ctx = talloc_new(samdb);
3221 if (tmp_ctx == NULL) {
3222 return ldb_oom(samdb);
3225 ret = ldb_search(samdb, tmp_ctx, &root_res,
3226 ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3227 if (ret != LDB_SUCCESS) {
3228 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3229 talloc_free(tmp_ctx);
3230 return ret;
3233 el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3234 if (!el) {
3235 DEBUG(1,("Finding namingContexts element in root_res failed: %s\n",
3236 ldb_errstring(samdb)));
3237 talloc_free(tmp_ctx);
3238 return LDB_ERR_NO_SUCH_ATTRIBUTE;
3241 nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3242 if (!nc_dns) {
3243 talloc_free(tmp_ctx);
3244 return ldb_oom(samdb);
3247 for (i=0; i<el->num_values; i++) {
3248 nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3249 if (nc_dns[i] == NULL) {
3250 talloc_free(tmp_ctx);
3251 return ldb_operr(samdb);
3255 TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3257 for (i=0; i<el->num_values; i++) {
3258 if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3259 (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3260 talloc_free(tmp_ctx);
3261 return LDB_SUCCESS;
3265 talloc_free(tmp_ctx);
3266 return LDB_ERR_NO_SUCH_OBJECT;
3271 find the deleted objects DN for any object, by looking for the NC
3272 root, then looking up the wellknown GUID
3274 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3275 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3276 struct ldb_dn **do_dn)
3278 struct ldb_dn *nc_root;
3279 int ret;
3281 ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3282 if (ret != LDB_SUCCESS) {
3283 return ret;
3286 ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3287 talloc_free(nc_root);
3288 return ret;
3292 return the tombstoneLifetime, in days
3294 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3296 struct ldb_dn *dn;
3297 dn = ldb_get_config_basedn(ldb);
3298 if (!dn) {
3299 return LDB_ERR_NO_SUCH_OBJECT;
3301 dn = ldb_dn_copy(ldb, dn);
3302 if (!dn) {
3303 return ldb_operr(ldb);
3305 /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3306 be a wellknown GUID for this */
3307 if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3308 talloc_free(dn);
3309 return ldb_operr(ldb);
3312 *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3313 talloc_free(dn);
3314 return LDB_SUCCESS;
3318 compare a ldb_val to a string case insensitively
3320 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3322 size_t len = strlen(s);
3323 int ret;
3324 if (len > v->length) return 1;
3325 ret = strncasecmp(s, (const char *)v->data, v->length);
3326 if (ret != 0) return ret;
3327 if (v->length > len && v->data[len] != 0) {
3328 return -1;
3330 return 0;
3335 load the UDV for a partition in v2 format
3336 The list is returned sorted, and with our local cursor added
3338 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3339 struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3341 static const char *attrs[] = { "replUpToDateVector", NULL };
3342 struct ldb_result *r;
3343 const struct ldb_val *ouv_value;
3344 unsigned int i;
3345 int ret;
3346 uint64_t highest_usn;
3347 const struct GUID *our_invocation_id;
3348 struct timeval now = timeval_current();
3350 ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3351 if (ret != LDB_SUCCESS) {
3352 return ret;
3355 ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3356 if (ouv_value) {
3357 enum ndr_err_code ndr_err;
3358 struct replUpToDateVectorBlob ouv;
3360 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
3361 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3362 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3363 talloc_free(r);
3364 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3366 if (ouv.version != 2) {
3367 /* we always store as version 2, and
3368 * replUpToDateVector is not replicated
3370 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3373 *count = ouv.ctr.ctr2.count;
3374 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3375 } else {
3376 *count = 0;
3377 *cursors = NULL;
3380 talloc_free(r);
3382 our_invocation_id = samdb_ntds_invocation_id(samdb);
3383 if (!our_invocation_id) {
3384 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3385 talloc_free(*cursors);
3386 return ldb_operr(samdb);
3389 ret = dsdb_load_partition_usn(samdb, dn, &highest_usn, NULL);
3390 if (ret != LDB_SUCCESS) {
3391 /* nothing to add - this can happen after a vampire */
3392 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3393 return LDB_SUCCESS;
3396 for (i=0; i<*count; i++) {
3397 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3398 (*cursors)[i].highest_usn = highest_usn;
3399 (*cursors)[i].last_sync_success = timeval_to_nttime(&now);
3400 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3401 return LDB_SUCCESS;
3405 (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3406 if (! *cursors) {
3407 return ldb_oom(samdb);
3410 (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3411 (*cursors)[*count].highest_usn = highest_usn;
3412 (*cursors)[*count].last_sync_success = timeval_to_nttime(&now);
3413 (*count)++;
3415 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3417 return LDB_SUCCESS;
3421 load the UDV for a partition in version 1 format
3422 The list is returned sorted, and with our local cursor added
3424 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3425 struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3427 struct drsuapi_DsReplicaCursor2 *v2;
3428 uint32_t i;
3429 int ret;
3431 ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3432 if (ret != LDB_SUCCESS) {
3433 return ret;
3436 if (*count == 0) {
3437 talloc_free(v2);
3438 *cursors = NULL;
3439 return LDB_SUCCESS;
3442 *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3443 if (*cursors == NULL) {
3444 talloc_free(v2);
3445 return ldb_oom(samdb);
3448 for (i=0; i<*count; i++) {
3449 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3450 (*cursors)[i].highest_usn = v2[i].highest_usn;
3452 talloc_free(v2);
3453 return LDB_SUCCESS;
3457 add a set of controls to a ldb_request structure based on a set of
3458 flags. See util.h for a list of available flags
3460 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3462 int ret;
3463 if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3464 struct ldb_search_options_control *options;
3465 /* Using the phantom root control allows us to search all partitions */
3466 options = talloc(req, struct ldb_search_options_control);
3467 if (options == NULL) {
3468 return LDB_ERR_OPERATIONS_ERROR;
3470 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3472 ret = ldb_request_add_control(req,
3473 LDB_CONTROL_SEARCH_OPTIONS_OID,
3474 true, options);
3475 if (ret != LDB_SUCCESS) {
3476 return ret;
3480 if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3481 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3482 if (ret != LDB_SUCCESS) {
3483 return ret;
3487 if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3488 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, true, NULL);
3489 if (ret != LDB_SUCCESS) {
3490 return ret;
3494 if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3495 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3496 if (!extended_ctrl) {
3497 return LDB_ERR_OPERATIONS_ERROR;
3499 extended_ctrl->type = 1;
3501 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3502 if (ret != LDB_SUCCESS) {
3503 return ret;
3507 if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3508 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3509 if (ret != LDB_SUCCESS) {
3510 return ret;
3514 if (dsdb_flags & DSDB_MODIFY_RELAX) {
3515 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3516 if (ret != LDB_SUCCESS) {
3517 return ret;
3521 if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3522 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3523 if (ret != LDB_SUCCESS) {
3524 return ret;
3528 if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3529 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3530 if (ret != LDB_SUCCESS) {
3531 return ret;
3535 if (dsdb_flags & DSDB_TREE_DELETE) {
3536 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
3537 if (ret != LDB_SUCCESS) {
3538 return ret;
3542 return LDB_SUCCESS;
3546 an add with a set of controls
3548 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
3549 uint32_t dsdb_flags)
3551 struct ldb_request *req;
3552 int ret;
3554 ret = ldb_build_add_req(&req, ldb, ldb,
3555 message,
3556 NULL,
3557 NULL,
3558 ldb_op_default_callback,
3559 NULL);
3561 if (ret != LDB_SUCCESS) return ret;
3563 ret = dsdb_request_add_controls(req, dsdb_flags);
3564 if (ret != LDB_SUCCESS) {
3565 talloc_free(req);
3566 return ret;
3569 ret = dsdb_autotransaction_request(ldb, req);
3571 talloc_free(req);
3572 return ret;
3576 a modify with a set of controls
3578 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3579 uint32_t dsdb_flags)
3581 struct ldb_request *req;
3582 int ret;
3584 ret = ldb_build_mod_req(&req, ldb, ldb,
3585 message,
3586 NULL,
3587 NULL,
3588 ldb_op_default_callback,
3589 NULL);
3591 if (ret != LDB_SUCCESS) return ret;
3593 ret = dsdb_request_add_controls(req, dsdb_flags);
3594 if (ret != LDB_SUCCESS) {
3595 talloc_free(req);
3596 return ret;
3599 ret = dsdb_autotransaction_request(ldb, req);
3601 talloc_free(req);
3602 return ret;
3606 like dsdb_modify() but set all the element flags to
3607 LDB_FLAG_MOD_REPLACE
3609 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3611 unsigned int i;
3613 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3614 for (i=0;i<msg->num_elements;i++) {
3615 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3618 return dsdb_modify(ldb, msg, dsdb_flags);
3623 search for attrs on one DN, allowing for dsdb_flags controls
3625 int dsdb_search_dn(struct ldb_context *ldb,
3626 TALLOC_CTX *mem_ctx,
3627 struct ldb_result **_res,
3628 struct ldb_dn *basedn,
3629 const char * const *attrs,
3630 uint32_t dsdb_flags)
3632 int ret;
3633 struct ldb_request *req;
3634 struct ldb_result *res;
3636 res = talloc_zero(mem_ctx, struct ldb_result);
3637 if (!res) {
3638 return ldb_oom(ldb);
3641 ret = ldb_build_search_req(&req, ldb, res,
3642 basedn,
3643 LDB_SCOPE_BASE,
3644 NULL,
3645 attrs,
3646 NULL,
3647 res,
3648 ldb_search_default_callback,
3649 NULL);
3650 if (ret != LDB_SUCCESS) {
3651 talloc_free(res);
3652 return ret;
3655 ret = dsdb_request_add_controls(req, dsdb_flags);
3656 if (ret != LDB_SUCCESS) {
3657 talloc_free(res);
3658 return ret;
3661 ret = ldb_request(ldb, req);
3662 if (ret == LDB_SUCCESS) {
3663 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3666 talloc_free(req);
3667 if (ret != LDB_SUCCESS) {
3668 talloc_free(res);
3669 return ret;
3672 *_res = res;
3673 return LDB_SUCCESS;
3677 general search with dsdb_flags for controls
3679 int dsdb_search(struct ldb_context *ldb,
3680 TALLOC_CTX *mem_ctx,
3681 struct ldb_result **_res,
3682 struct ldb_dn *basedn,
3683 enum ldb_scope scope,
3684 const char * const *attrs,
3685 uint32_t dsdb_flags,
3686 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3688 int ret;
3689 struct ldb_request *req;
3690 struct ldb_result *res;
3691 va_list ap;
3692 char *expression = NULL;
3693 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3695 res = talloc_zero(tmp_ctx, struct ldb_result);
3696 if (!res) {
3697 talloc_free(tmp_ctx);
3698 return ldb_oom(ldb);
3701 if (exp_fmt) {
3702 va_start(ap, exp_fmt);
3703 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3704 va_end(ap);
3706 if (!expression) {
3707 talloc_free(tmp_ctx);
3708 return ldb_oom(ldb);
3712 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3713 basedn,
3714 scope,
3715 expression,
3716 attrs,
3717 NULL,
3718 res,
3719 ldb_search_default_callback,
3720 NULL);
3721 if (ret != LDB_SUCCESS) {
3722 talloc_free(tmp_ctx);
3723 return ret;
3726 ret = dsdb_request_add_controls(req, dsdb_flags);
3727 if (ret != LDB_SUCCESS) {
3728 talloc_free(tmp_ctx);
3729 return ret;
3732 ret = ldb_request(ldb, req);
3733 if (ret == LDB_SUCCESS) {
3734 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3737 if (ret != LDB_SUCCESS) {
3738 talloc_free(tmp_ctx);
3739 return ret;
3742 if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
3743 if (res->count == 0) {
3744 talloc_free(tmp_ctx);
3745 return LDB_ERR_NO_SUCH_OBJECT;
3747 if (res->count != 1) {
3748 talloc_free(tmp_ctx);
3749 return LDB_ERR_CONSTRAINT_VIOLATION;
3753 *_res = talloc_steal(mem_ctx, res);
3754 talloc_free(tmp_ctx);
3756 return LDB_SUCCESS;
3761 general search with dsdb_flags for controls
3762 returns exactly 1 record or an error
3764 int dsdb_search_one(struct ldb_context *ldb,
3765 TALLOC_CTX *mem_ctx,
3766 struct ldb_message **msg,
3767 struct ldb_dn *basedn,
3768 enum ldb_scope scope,
3769 const char * const *attrs,
3770 uint32_t dsdb_flags,
3771 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3773 int ret;
3774 struct ldb_result *res;
3775 va_list ap;
3776 char *expression = NULL;
3777 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3779 dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
3781 res = talloc_zero(tmp_ctx, struct ldb_result);
3782 if (!res) {
3783 talloc_free(tmp_ctx);
3784 return ldb_oom(ldb);
3787 if (exp_fmt) {
3788 va_start(ap, exp_fmt);
3789 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3790 va_end(ap);
3792 if (!expression) {
3793 talloc_free(tmp_ctx);
3794 return ldb_oom(ldb);
3796 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
3797 dsdb_flags, "%s", expression);
3798 } else {
3799 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
3800 dsdb_flags, NULL);
3803 if (ret != LDB_SUCCESS) {
3804 talloc_free(tmp_ctx);
3805 return ret;
3808 *msg = talloc_steal(mem_ctx, res->msgs[0]);
3809 talloc_free(tmp_ctx);
3811 return LDB_SUCCESS;
3814 /* returns back the forest DNS name */
3815 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
3817 const char *forest_name = ldb_dn_canonical_string(mem_ctx,
3818 ldb_get_root_basedn(ldb));
3819 char *p;
3821 if (forest_name == NULL) {
3822 return NULL;
3825 p = strchr(forest_name, '/');
3826 if (p) {
3827 *p = '\0';
3830 return forest_name;
3834 validate that an DSA GUID belongs to the specified user sid.
3835 The user SID must be a domain controller account (either RODC or
3836 RWDC)
3838 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
3839 const struct GUID *dsa_guid,
3840 const struct dom_sid *sid)
3842 /* strategy:
3843 - find DN of record with the DSA GUID in the
3844 configuration partition (objectGUID)
3845 - remove "NTDS Settings" component from DN
3846 - do a base search on that DN for serverReference with
3847 extended-dn enabled
3848 - extract objectSID from resulting serverReference
3849 attribute
3850 - check this sid matches the sid argument
3852 struct ldb_dn *config_dn;
3853 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3854 struct ldb_message *msg;
3855 const char *attrs1[] = { NULL };
3856 const char *attrs2[] = { "serverReference", NULL };
3857 int ret;
3858 struct ldb_dn *dn, *account_dn;
3859 struct dom_sid sid2;
3860 NTSTATUS status;
3862 config_dn = ldb_get_config_basedn(ldb);
3864 ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
3865 attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
3866 if (ret != LDB_SUCCESS) {
3867 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
3868 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3869 talloc_free(tmp_ctx);
3870 return ldb_operr(ldb);
3872 dn = msg->dn;
3874 if (!ldb_dn_remove_child_components(dn, 1)) {
3875 talloc_free(tmp_ctx);
3876 return ldb_operr(ldb);
3879 ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
3880 attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
3881 "(objectClass=server)");
3882 if (ret != LDB_SUCCESS) {
3883 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
3884 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3885 talloc_free(tmp_ctx);
3886 return ldb_operr(ldb);
3889 account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
3890 if (account_dn == NULL) {
3891 DEBUG(1,(__location__ ": Failed to find account_dn for DSA with objectGUID %s, sid %s\n",
3892 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3893 talloc_free(tmp_ctx);
3894 return ldb_operr(ldb);
3897 status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
3898 if (!NT_STATUS_IS_OK(status)) {
3899 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
3900 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3901 talloc_free(tmp_ctx);
3902 return ldb_operr(ldb);
3905 if (!dom_sid_equal(sid, &sid2)) {
3906 /* someone is trying to spoof another account */
3907 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
3908 GUID_string(tmp_ctx, dsa_guid),
3909 dom_sid_string(tmp_ctx, sid),
3910 dom_sid_string(tmp_ctx, &sid2)));
3911 talloc_free(tmp_ctx);
3912 return ldb_operr(ldb);
3915 talloc_free(tmp_ctx);
3916 return LDB_SUCCESS;
3919 const char *rodc_fas_list[] = {"ms-PKI-DPAPIMasterKeys",
3920 "ms-PKI-AccountCredentials",
3921 "ms-PKI-RoamingTimeStamp",
3922 "ms-FVE-KeyPackage",
3923 "ms-FVE-RecoveryGuid",
3924 "ms-FVE-RecoveryInformation",
3925 "ms-FVE-RecoveryPassword",
3926 "ms-FVE-VolumeGuid",
3927 "ms-TPM-OwnerInformation",
3928 NULL};
3930 check if the attribute belongs to the RODC filtered attribute set
3932 bool dsdb_attr_in_rodc_fas(uint32_t replica_flags, const struct dsdb_attribute *sa)
3934 int rodc_filtered_flags = SEARCH_FLAG_RODC_ATTRIBUTE | SEARCH_FLAG_CONFIDENTIAL;
3935 bool drs_write_replica = ((replica_flags & DRSUAPI_DRS_WRIT_REP) == 0);
3937 if (drs_write_replica && (sa->searchFlags & rodc_filtered_flags)) {
3938 return true;
3940 if (drs_write_replica && is_attr_in_list(rodc_fas_list, sa->cn)) {
3941 return true;
3943 return false;