dsdb: check type with talloc_get_type_abort in samdb_set_password
[Samba.git] / source4 / dsdb / common / util.c
blob9dbdbdd7b29cf4cc466a914be1001ad4ff9491fb
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 "librpc/gen_ndr/irpc.h"
46 #include "libds/common/flag_mapping.h"
49 search the sam for the specified attributes in a specific domain, filter on
50 objectSid being in domain_sid.
52 int samdb_search_domain(struct ldb_context *sam_ldb,
53 TALLOC_CTX *mem_ctx,
54 struct ldb_dn *basedn,
55 struct ldb_message ***res,
56 const char * const *attrs,
57 const struct dom_sid *domain_sid,
58 const char *format, ...) _PRINTF_ATTRIBUTE(7,8)
60 va_list ap;
61 int i, count;
63 va_start(ap, format);
64 count = gendb_search_v(sam_ldb, mem_ctx, basedn,
65 res, attrs, format, ap);
66 va_end(ap);
68 i=0;
70 while (i<count) {
71 struct dom_sid *entry_sid;
73 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
75 if ((entry_sid == NULL) ||
76 (!dom_sid_in_domain(domain_sid, entry_sid))) {
77 /* Delete that entry from the result set */
78 (*res)[i] = (*res)[count-1];
79 count -= 1;
80 talloc_free(entry_sid);
81 continue;
83 talloc_free(entry_sid);
84 i += 1;
87 return count;
91 search the sam for a single string attribute in exactly 1 record
93 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
94 TALLOC_CTX *mem_ctx,
95 struct ldb_dn *basedn,
96 const char *attr_name,
97 const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
99 int count;
100 const char *attrs[2] = { NULL, NULL };
101 struct ldb_message **res = NULL;
103 attrs[0] = attr_name;
105 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
106 if (count > 1) {
107 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
108 attr_name, format, count));
110 if (count != 1) {
111 talloc_free(res);
112 return NULL;
115 return ldb_msg_find_attr_as_string(res[0], attr_name, NULL);
119 search the sam for a single string attribute in exactly 1 record
121 const char *samdb_search_string(struct ldb_context *sam_ldb,
122 TALLOC_CTX *mem_ctx,
123 struct ldb_dn *basedn,
124 const char *attr_name,
125 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
127 va_list ap;
128 const char *str;
130 va_start(ap, format);
131 str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
132 va_end(ap);
134 return str;
137 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
138 TALLOC_CTX *mem_ctx,
139 struct ldb_dn *basedn,
140 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
142 va_list ap;
143 struct ldb_dn *ret;
144 struct ldb_message **res = NULL;
145 int count;
147 va_start(ap, format);
148 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
149 va_end(ap);
151 if (count != 1) return NULL;
153 ret = talloc_steal(mem_ctx, res[0]->dn);
154 talloc_free(res);
156 return ret;
160 search the sam for a dom_sid attribute in exactly 1 record
162 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
163 TALLOC_CTX *mem_ctx,
164 struct ldb_dn *basedn,
165 const char *attr_name,
166 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
168 va_list ap;
169 int count;
170 struct ldb_message **res;
171 const char *attrs[2] = { NULL, NULL };
172 struct dom_sid *sid;
174 attrs[0] = attr_name;
176 va_start(ap, format);
177 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
178 va_end(ap);
179 if (count > 1) {
180 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
181 attr_name, format, count));
183 if (count != 1) {
184 talloc_free(res);
185 return NULL;
187 sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
188 talloc_free(res);
189 return sid;
193 return the count of the number of records in the sam matching the query
195 int samdb_search_count(struct ldb_context *sam_ldb,
196 TALLOC_CTX *mem_ctx,
197 struct ldb_dn *basedn,
198 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
200 va_list ap;
201 const char *attrs[] = { NULL };
202 int ret;
204 va_start(ap, format);
205 ret = gendb_search_v(sam_ldb, mem_ctx, basedn, NULL, attrs, format, ap);
206 va_end(ap);
208 return ret;
213 search the sam for a single integer attribute in exactly 1 record
215 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
216 TALLOC_CTX *mem_ctx,
217 unsigned int default_value,
218 struct ldb_dn *basedn,
219 const char *attr_name,
220 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
222 va_list ap;
223 int count;
224 struct ldb_message **res;
225 const char *attrs[2] = { NULL, NULL };
227 attrs[0] = attr_name;
229 va_start(ap, format);
230 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
231 va_end(ap);
233 if (count != 1) {
234 return default_value;
237 return ldb_msg_find_attr_as_uint(res[0], attr_name, default_value);
241 search the sam for a single signed 64 bit integer attribute in exactly 1 record
243 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
244 TALLOC_CTX *mem_ctx,
245 int64_t default_value,
246 struct ldb_dn *basedn,
247 const char *attr_name,
248 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
250 va_list ap;
251 int count;
252 struct ldb_message **res;
253 const char *attrs[2] = { NULL, NULL };
255 attrs[0] = attr_name;
257 va_start(ap, format);
258 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
259 va_end(ap);
261 if (count != 1) {
262 return default_value;
265 return ldb_msg_find_attr_as_int64(res[0], attr_name, default_value);
269 search the sam for multipe records each giving a single string attribute
270 return the number of matches, or -1 on error
272 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
273 TALLOC_CTX *mem_ctx,
274 struct ldb_dn *basedn,
275 const char ***strs,
276 const char *attr_name,
277 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
279 va_list ap;
280 int count, i;
281 const char *attrs[2] = { NULL, NULL };
282 struct ldb_message **res = NULL;
284 attrs[0] = attr_name;
286 va_start(ap, format);
287 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
288 va_end(ap);
290 if (count <= 0) {
291 return count;
294 /* make sure its single valued */
295 for (i=0;i<count;i++) {
296 if (res[i]->num_elements != 1) {
297 DEBUG(1,("samdb: search for %s %s not single valued\n",
298 attr_name, format));
299 talloc_free(res);
300 return -1;
304 *strs = talloc_array(mem_ctx, const char *, count+1);
305 if (! *strs) {
306 talloc_free(res);
307 return -1;
310 for (i=0;i<count;i++) {
311 (*strs)[i] = ldb_msg_find_attr_as_string(res[i], attr_name, NULL);
313 (*strs)[count] = NULL;
315 return count;
318 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
319 const char *attr, struct ldb_dn *default_value)
321 struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
322 if (!ret_dn) {
323 return default_value;
325 return ret_dn;
329 pull a rid from a objectSid in a result set.
331 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
332 const char *attr, uint32_t default_value)
334 struct dom_sid *sid;
335 uint32_t rid;
337 sid = samdb_result_dom_sid(mem_ctx, msg, attr);
338 if (sid == NULL) {
339 return default_value;
341 rid = sid->sub_auths[sid->num_auths-1];
342 talloc_free(sid);
343 return rid;
347 pull a dom_sid structure from a objectSid in a result set.
349 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
350 const char *attr)
352 bool ok;
353 const struct ldb_val *v;
354 struct dom_sid *sid;
355 v = ldb_msg_find_ldb_val(msg, attr);
356 if (v == NULL) {
357 return NULL;
359 sid = talloc(mem_ctx, struct dom_sid);
360 if (sid == NULL) {
361 return NULL;
363 ok = sid_blob_parse(*v, sid);
364 if (!ok) {
365 talloc_free(sid);
366 return NULL;
368 return sid;
372 pull a guid structure from a objectGUID in a result set.
374 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
376 const struct ldb_val *v;
377 struct GUID guid;
378 NTSTATUS status;
380 v = ldb_msg_find_ldb_val(msg, attr);
381 if (!v) return GUID_zero();
383 status = GUID_from_ndr_blob(v, &guid);
384 if (!NT_STATUS_IS_OK(status)) {
385 return GUID_zero();
388 return guid;
392 pull a sid prefix from a objectSid in a result set.
393 this is used to find the domain sid for a user
395 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
396 const char *attr)
398 struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
399 if (!sid || sid->num_auths < 1) return NULL;
400 sid->num_auths--;
401 return sid;
405 pull a NTTIME in a result set.
407 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
408 NTTIME default_value)
410 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
414 * Windows stores 0 for lastLogoff.
415 * But when a MS DC return the lastLogoff (as Logoff Time)
416 * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
417 * cause windows 2008 and newer version to fail for SMB requests
419 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
421 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
423 if (ret == 0)
424 ret = 0x7FFFFFFFFFFFFFFFULL;
426 return ret;
430 * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
431 * indicate an account doesn't expire.
433 * When Windows initially creates an account, it sets
434 * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF). However,
435 * when changing from an account having a specific expiration date to
436 * that account never expiring, it sets accountExpires = 0.
438 * Consolidate that logic here to allow clearer logic for account expiry in
439 * the rest of the code.
441 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
443 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
446 if (ret == 0)
447 ret = 0x7FFFFFFFFFFFFFFFULL;
449 return ret;
453 construct the allow_password_change field from the PwdLastSet attribute and the
454 domain password settings
456 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb,
457 TALLOC_CTX *mem_ctx,
458 struct ldb_dn *domain_dn,
459 struct ldb_message *msg,
460 const char *attr)
462 uint64_t attr_time = ldb_msg_find_attr_as_uint64(msg, attr, 0);
463 int64_t minPwdAge;
465 if (attr_time == 0) {
466 return 0;
469 minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
471 /* yes, this is a -= not a += as minPwdAge is stored as the negative
472 of the number of 100-nano-seconds */
473 attr_time -= minPwdAge;
475 return attr_time;
479 construct the force_password_change field from the PwdLastSet
480 attribute, the userAccountControl and the domain password settings
482 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb,
483 TALLOC_CTX *mem_ctx,
484 struct ldb_dn *domain_dn,
485 struct ldb_message *msg)
487 int64_t attr_time = ldb_msg_find_attr_as_int64(msg, "pwdLastSet", 0);
488 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg,
489 "userAccountControl",
491 int64_t maxPwdAge;
493 /* Machine accounts don't expire, and there is a flag for 'no expiry' */
494 if (!(userAccountControl & UF_NORMAL_ACCOUNT)
495 || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
496 return 0x7FFFFFFFFFFFFFFFULL;
499 if (attr_time == 0) {
500 return 0;
502 if (attr_time == -1) {
503 return 0x7FFFFFFFFFFFFFFFULL;
506 maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
507 "maxPwdAge", NULL);
508 if (maxPwdAge == 0 || maxPwdAge == -0x8000000000000000ULL) {
509 return 0x7FFFFFFFFFFFFFFFULL;
510 } else {
511 attr_time -= maxPwdAge;
514 return attr_time;
518 pull a samr_Password structutre from a result set.
520 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
522 struct samr_Password *hash = NULL;
523 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
524 if (val && (val->length >= sizeof(hash->hash))) {
525 hash = talloc(mem_ctx, struct samr_Password);
526 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
528 return hash;
532 pull an array of samr_Password structures from a result set.
534 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
535 const char *attr, struct samr_Password **hashes)
537 unsigned int count, i;
538 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
540 *hashes = NULL;
541 if (!val) {
542 return 0;
544 count = val->length / 16;
545 if (count == 0) {
546 return 0;
549 *hashes = talloc_array(mem_ctx, struct samr_Password, count);
550 if (! *hashes) {
551 return 0;
554 for (i=0;i<count;i++) {
555 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
558 return count;
561 NTSTATUS samdb_result_passwords_from_history(TALLOC_CTX *mem_ctx,
562 struct loadparm_context *lp_ctx,
563 struct ldb_message *msg,
564 unsigned int idx,
565 struct samr_Password **lm_pwd,
566 struct samr_Password **nt_pwd)
568 struct samr_Password *lmPwdHash, *ntPwdHash;
570 if (nt_pwd) {
571 unsigned int num_nt;
572 num_nt = samdb_result_hashes(mem_ctx, msg, "ntPwdHistory", &ntPwdHash);
573 if (num_nt < idx) {
574 *nt_pwd = NULL;
575 } else {
576 *nt_pwd = &ntPwdHash[idx];
579 if (lm_pwd) {
580 /* Ensure that if we have turned off LM
581 * authentication, that we never use the LM hash, even
582 * if we store it */
583 if (lpcfg_lanman_auth(lp_ctx)) {
584 unsigned int num_lm;
585 num_lm = samdb_result_hashes(mem_ctx, msg, "lmPwdHistory", &lmPwdHash);
586 if (num_lm < idx) {
587 *lm_pwd = NULL;
588 } else {
589 *lm_pwd = &lmPwdHash[idx];
591 } else {
592 *lm_pwd = NULL;
595 return NT_STATUS_OK;
598 NTSTATUS samdb_result_passwords_no_lockout(TALLOC_CTX *mem_ctx,
599 struct loadparm_context *lp_ctx,
600 struct ldb_message *msg,
601 struct samr_Password **lm_pwd,
602 struct samr_Password **nt_pwd)
604 struct samr_Password *lmPwdHash, *ntPwdHash;
606 if (nt_pwd) {
607 unsigned int num_nt;
608 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
609 if (num_nt == 0) {
610 *nt_pwd = NULL;
611 } else if (num_nt > 1) {
612 return NT_STATUS_INTERNAL_DB_CORRUPTION;
613 } else {
614 *nt_pwd = &ntPwdHash[0];
617 if (lm_pwd) {
618 /* Ensure that if we have turned off LM
619 * authentication, that we never use the LM hash, even
620 * if we store it */
621 if (lpcfg_lanman_auth(lp_ctx)) {
622 unsigned int num_lm;
623 num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
624 if (num_lm == 0) {
625 *lm_pwd = NULL;
626 } else if (num_lm > 1) {
627 return NT_STATUS_INTERNAL_DB_CORRUPTION;
628 } else {
629 *lm_pwd = &lmPwdHash[0];
631 } else {
632 *lm_pwd = NULL;
635 return NT_STATUS_OK;
638 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx,
639 struct loadparm_context *lp_ctx,
640 struct ldb_message *msg,
641 struct samr_Password **lm_pwd,
642 struct samr_Password **nt_pwd)
644 uint16_t acct_flags;
646 acct_flags = samdb_result_acct_flags(msg,
647 "msDS-User-Account-Control-Computed");
648 /* Quit if the account was locked out. */
649 if (acct_flags & ACB_AUTOLOCK) {
650 DEBUG(3,("samdb_result_passwords: Account for user %s was locked out.\n",
651 ldb_dn_get_linearized(msg->dn)));
652 return NT_STATUS_ACCOUNT_LOCKED_OUT;
655 return samdb_result_passwords_no_lockout(mem_ctx, lp_ctx, msg,
656 lm_pwd, nt_pwd);
660 pull a samr_LogonHours structutre from a result set.
662 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
664 struct samr_LogonHours hours;
665 size_t units_per_week = 168;
666 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
668 ZERO_STRUCT(hours);
670 if (val) {
671 units_per_week = val->length * 8;
674 hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
675 if (!hours.bits) {
676 return hours;
678 hours.units_per_week = units_per_week;
679 memset(hours.bits, 0xFF, units_per_week/8);
680 if (val) {
681 memcpy(hours.bits, val->data, val->length);
684 return hours;
688 pull a set of account_flags from a result set.
690 Naturally, this requires that userAccountControl and
691 (if not null) the attributes 'attr' be already
692 included in msg
694 uint32_t samdb_result_acct_flags(struct ldb_message *msg, const char *attr)
696 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
697 uint32_t attr_flags = 0;
698 uint32_t acct_flags = ds_uf2acb(userAccountControl);
699 if (attr) {
700 attr_flags = ldb_msg_find_attr_as_uint(msg, attr, UF_ACCOUNTDISABLE);
701 if (attr_flags == UF_ACCOUNTDISABLE) {
702 DEBUG(0, ("Attribute %s not found, disabling account %s!\n", attr,
703 ldb_dn_get_linearized(msg->dn)));
705 acct_flags |= ds_uf2acb(attr_flags);
708 return acct_flags;
711 struct lsa_BinaryString samdb_result_parameters(TALLOC_CTX *mem_ctx,
712 struct ldb_message *msg,
713 const char *attr)
715 struct lsa_BinaryString s;
716 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
718 ZERO_STRUCT(s);
720 if (!val) {
721 return s;
724 s.array = talloc_array(mem_ctx, uint16_t, val->length/2);
725 if (!s.array) {
726 return s;
728 s.length = s.size = val->length;
729 memcpy(s.array, val->data, val->length);
731 return s;
734 /* Find an attribute, with a particular value */
736 /* The current callers of this function expect a very specific
737 * behaviour: In particular, objectClass subclass equivilance is not
738 * wanted. This means that we should not lookup the schema for the
739 * comparison function */
740 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
741 const struct ldb_message *msg,
742 const char *name, const char *value)
744 unsigned int i;
745 struct ldb_message_element *el = ldb_msg_find_element(msg, name);
747 if (!el) {
748 return NULL;
751 for (i=0;i<el->num_values;i++) {
752 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
753 return el;
757 return NULL;
760 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
762 struct ldb_message_element *el;
764 el = ldb_msg_find_element(msg, name);
765 if (el) {
766 return LDB_SUCCESS;
769 return ldb_msg_add_string(msg, name, set_value);
773 add a dom_sid element to a message
775 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
776 const char *attr_name, const struct dom_sid *sid)
778 struct ldb_val v;
779 enum ndr_err_code ndr_err;
781 ndr_err = ndr_push_struct_blob(&v, mem_ctx,
782 sid,
783 (ndr_push_flags_fn_t)ndr_push_dom_sid);
784 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
785 return ldb_operr(sam_ldb);
787 return ldb_msg_add_value(msg, attr_name, &v, NULL);
792 add a delete element operation to a message
794 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
795 const char *attr_name)
797 /* we use an empty replace rather than a delete, as it allows for
798 dsdb_replace() to be used everywhere */
799 return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
803 add an add attribute value to a message or enhance an existing attribute
804 which has the same name and the add flag set.
806 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
807 struct ldb_message *msg, const char *attr_name,
808 const char *value)
810 struct ldb_message_element *el;
811 struct ldb_val val, *vals;
812 char *v;
813 unsigned int i;
814 bool found = false;
815 int ret;
817 v = talloc_strdup(mem_ctx, value);
818 if (v == NULL) {
819 return ldb_oom(sam_ldb);
822 val.data = (uint8_t *) v;
823 val.length = strlen(v);
825 if (val.length == 0) {
826 /* allow empty strings as non-existent attributes */
827 return LDB_SUCCESS;
830 for (i = 0; i < msg->num_elements; i++) {
831 el = &msg->elements[i];
832 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
833 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
834 found = true;
835 break;
838 if (!found) {
839 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
840 &el);
841 if (ret != LDB_SUCCESS) {
842 return ret;
846 vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
847 el->num_values + 1);
848 if (vals == NULL) {
849 return ldb_oom(sam_ldb);
851 el->values = vals;
852 el->values[el->num_values] = val;
853 ++(el->num_values);
855 return LDB_SUCCESS;
859 add a delete attribute value to a message or enhance an existing attribute
860 which has the same name and the delete flag set.
862 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
863 struct ldb_message *msg, const char *attr_name,
864 const char *value)
866 struct ldb_message_element *el;
867 struct ldb_val val, *vals;
868 char *v;
869 unsigned int i;
870 bool found = false;
871 int ret;
873 v = talloc_strdup(mem_ctx, value);
874 if (v == NULL) {
875 return ldb_oom(sam_ldb);
878 val.data = (uint8_t *) v;
879 val.length = strlen(v);
881 if (val.length == 0) {
882 /* allow empty strings as non-existent attributes */
883 return LDB_SUCCESS;
886 for (i = 0; i < msg->num_elements; i++) {
887 el = &msg->elements[i];
888 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
889 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
890 found = true;
891 break;
894 if (!found) {
895 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
896 &el);
897 if (ret != LDB_SUCCESS) {
898 return ret;
902 vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
903 el->num_values + 1);
904 if (vals == NULL) {
905 return ldb_oom(sam_ldb);
907 el->values = vals;
908 el->values[el->num_values] = val;
909 ++(el->num_values);
911 return LDB_SUCCESS;
915 add a int element to a message
917 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
918 const char *attr_name, int v)
920 const char *s = talloc_asprintf(mem_ctx, "%d", v);
921 if (s == NULL) {
922 return ldb_oom(sam_ldb);
924 return ldb_msg_add_string(msg, attr_name, s);
928 * Add an unsigned int element to a message
930 * The issue here is that we have not yet first cast to int32_t explicitly,
931 * before we cast to an signed int to printf() into the %d or cast to a
932 * int64_t before we then cast to a long long to printf into a %lld.
934 * There are *no* unsigned integers in Active Directory LDAP, even the RID
935 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
936 * (See the schema, and the syntax definitions in schema_syntax.c).
939 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
940 const char *attr_name, unsigned int v)
942 return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
946 add a (signed) int64_t element to a message
948 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
949 const char *attr_name, int64_t v)
951 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
952 if (s == NULL) {
953 return ldb_oom(sam_ldb);
955 return ldb_msg_add_string(msg, attr_name, s);
959 * Add an unsigned int64_t (uint64_t) element to a message
961 * The issue here is that we have not yet first cast to int32_t explicitly,
962 * before we cast to an signed int to printf() into the %d or cast to a
963 * int64_t before we then cast to a long long to printf into a %lld.
965 * There are *no* unsigned integers in Active Directory LDAP, even the RID
966 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
967 * (See the schema, and the syntax definitions in schema_syntax.c).
970 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
971 const char *attr_name, uint64_t v)
973 return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
977 add a samr_Password element to a message
979 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
980 const char *attr_name, const struct samr_Password *hash)
982 struct ldb_val val;
983 val.data = talloc_memdup(mem_ctx, hash->hash, 16);
984 if (!val.data) {
985 return ldb_oom(sam_ldb);
987 val.length = 16;
988 return ldb_msg_add_value(msg, attr_name, &val, NULL);
992 add a samr_Password array to a message
994 int samdb_msg_add_hashes(struct ldb_context *ldb,
995 TALLOC_CTX *mem_ctx, struct ldb_message *msg,
996 const char *attr_name, struct samr_Password *hashes,
997 unsigned int count)
999 struct ldb_val val;
1000 unsigned int i;
1001 val.data = talloc_array_size(mem_ctx, 16, count);
1002 val.length = count*16;
1003 if (!val.data) {
1004 return ldb_oom(ldb);
1006 for (i=0;i<count;i++) {
1007 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
1009 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1013 add a acct_flags element to a message
1015 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1016 const char *attr_name, uint32_t v)
1018 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1022 add a logon_hours element to a message
1024 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1025 const char *attr_name, struct samr_LogonHours *hours)
1027 struct ldb_val val;
1028 val.length = hours->units_per_week / 8;
1029 val.data = hours->bits;
1030 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1034 add a parameters element to a message
1036 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1037 const char *attr_name, struct lsa_BinaryString *parameters)
1039 struct ldb_val val;
1040 val.length = parameters->length;
1041 val.data = (uint8_t *)parameters->array;
1042 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1046 * Sets an unsigned int element in a message
1048 * The issue here is that we have not yet first cast to int32_t explicitly,
1049 * before we cast to an signed int to printf() into the %d or cast to a
1050 * int64_t before we then cast to a long long to printf into a %lld.
1052 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1053 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1054 * (See the schema, and the syntax definitions in schema_syntax.c).
1057 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1058 struct ldb_message *msg, const char *attr_name,
1059 unsigned int v)
1061 struct ldb_message_element *el;
1063 el = ldb_msg_find_element(msg, attr_name);
1064 if (el) {
1065 el->num_values = 0;
1067 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1071 * Handle ldb_request in transaction
1073 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1074 struct ldb_request *req)
1076 int ret;
1078 ret = ldb_transaction_start(sam_ldb);
1079 if (ret != LDB_SUCCESS) {
1080 return ret;
1083 ret = ldb_request(sam_ldb, req);
1084 if (ret == LDB_SUCCESS) {
1085 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1088 if (ret == LDB_SUCCESS) {
1089 return ldb_transaction_commit(sam_ldb);
1091 ldb_transaction_cancel(sam_ldb);
1093 return ret;
1097 return a default security descriptor
1099 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1101 struct security_descriptor *sd;
1103 sd = security_descriptor_initialise(mem_ctx);
1105 return sd;
1108 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1110 struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1111 struct ldb_dn *aggregate_dn;
1112 if (!schema_dn) {
1113 return NULL;
1116 aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1117 if (!aggregate_dn) {
1118 return NULL;
1120 if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1121 return NULL;
1123 return aggregate_dn;
1126 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1128 struct ldb_dn *new_dn;
1130 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1131 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1132 talloc_free(new_dn);
1133 return NULL;
1135 return new_dn;
1138 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1140 struct ldb_dn *new_dn;
1142 new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1143 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1144 talloc_free(new_dn);
1145 return NULL;
1147 return new_dn;
1150 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1152 struct ldb_dn *new_dn;
1154 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1155 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1156 talloc_free(new_dn);
1157 return NULL;
1159 return new_dn;
1163 work out the domain sid for the current open ldb
1165 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1167 TALLOC_CTX *tmp_ctx;
1168 const struct dom_sid *domain_sid;
1169 const char *attrs[] = {
1170 "objectSid",
1171 NULL
1173 struct ldb_result *res;
1174 int ret;
1176 /* see if we have a cached copy */
1177 domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1178 if (domain_sid) {
1179 return domain_sid;
1182 tmp_ctx = talloc_new(ldb);
1183 if (tmp_ctx == NULL) {
1184 goto failed;
1187 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1189 if (ret != LDB_SUCCESS) {
1190 goto failed;
1193 if (res->count != 1) {
1194 goto failed;
1197 domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1198 if (domain_sid == NULL) {
1199 goto failed;
1202 /* cache the domain_sid in the ldb */
1203 if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1204 goto failed;
1207 talloc_steal(ldb, domain_sid);
1208 talloc_free(tmp_ctx);
1210 return domain_sid;
1212 failed:
1213 talloc_free(tmp_ctx);
1214 return NULL;
1218 get domain sid from cache
1220 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1222 return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1225 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1227 TALLOC_CTX *tmp_ctx;
1228 struct dom_sid *dom_sid_new;
1229 struct dom_sid *dom_sid_old;
1231 /* see if we have a cached copy */
1232 dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1233 "cache.domain_sid"), struct dom_sid);
1235 tmp_ctx = talloc_new(ldb);
1236 if (tmp_ctx == NULL) {
1237 goto failed;
1240 dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1241 if (!dom_sid_new) {
1242 goto failed;
1245 /* cache the domain_sid in the ldb */
1246 if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1247 goto failed;
1250 talloc_steal(ldb, dom_sid_new);
1251 talloc_free(tmp_ctx);
1252 talloc_free(dom_sid_old);
1254 return true;
1256 failed:
1257 DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1258 talloc_free(tmp_ctx);
1259 return false;
1262 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1264 TALLOC_CTX *tmp_ctx;
1265 struct ldb_dn *ntds_settings_dn_new;
1266 struct ldb_dn *ntds_settings_dn_old;
1268 /* see if we have a forced copy from provision */
1269 ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb,
1270 "forced.ntds_settings_dn"), struct ldb_dn);
1272 tmp_ctx = talloc_new(ldb);
1273 if (tmp_ctx == NULL) {
1274 goto failed;
1277 ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1278 if (!ntds_settings_dn_new) {
1279 goto failed;
1282 /* set the DN in the ldb to avoid lookups during provision */
1283 if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1284 goto failed;
1287 talloc_steal(ldb, ntds_settings_dn_new);
1288 talloc_free(tmp_ctx);
1289 talloc_free(ntds_settings_dn_old);
1291 return true;
1293 failed:
1294 DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1295 talloc_free(tmp_ctx);
1296 return false;
1300 work out the ntds settings dn for the current open ldb
1302 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1304 TALLOC_CTX *tmp_ctx;
1305 const char *root_attrs[] = { "dsServiceName", NULL };
1306 int ret;
1307 struct ldb_result *root_res;
1308 struct ldb_dn *settings_dn;
1310 /* see if we have a cached copy */
1311 settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1312 if (settings_dn) {
1313 return ldb_dn_copy(mem_ctx, settings_dn);
1316 tmp_ctx = talloc_new(mem_ctx);
1317 if (tmp_ctx == NULL) {
1318 goto failed;
1321 ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1322 if (ret != LDB_SUCCESS) {
1323 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1324 ldb_errstring(ldb)));
1325 goto failed;
1328 if (root_res->count != 1) {
1329 goto failed;
1332 settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1334 /* note that we do not cache the DN here, as that would mean
1335 * we could not handle server renames at runtime. Only
1336 * provision sets up forced.ntds_settings_dn */
1338 talloc_steal(mem_ctx, settings_dn);
1339 talloc_free(tmp_ctx);
1341 return settings_dn;
1343 failed:
1344 DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1345 talloc_free(tmp_ctx);
1346 return NULL;
1350 work out the ntds settings invocationId for the current open ldb
1352 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1354 TALLOC_CTX *tmp_ctx;
1355 const char *attrs[] = { "invocationId", NULL };
1356 int ret;
1357 struct ldb_result *res;
1358 struct GUID *invocation_id;
1360 /* see if we have a cached copy */
1361 invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1362 if (invocation_id) {
1363 SMB_ASSERT(!GUID_all_zero(invocation_id));
1364 return invocation_id;
1367 tmp_ctx = talloc_new(ldb);
1368 if (tmp_ctx == NULL) {
1369 goto failed;
1372 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1373 if (ret) {
1374 goto failed;
1377 if (res->count != 1) {
1378 goto failed;
1381 invocation_id = talloc(tmp_ctx, struct GUID);
1382 if (!invocation_id) {
1383 goto failed;
1386 *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1387 if (GUID_all_zero(invocation_id)) {
1388 if (ldb_msg_find_ldb_val(res->msgs[0], "invocationId")) {
1389 DEBUG(0, ("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1390 } else {
1391 DEBUG(0, ("Failed to find parse own NTDS Settings invocationId from the ldb!\n"));
1393 goto failed;
1396 /* cache the domain_sid in the ldb */
1397 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1398 goto failed;
1401 talloc_steal(ldb, invocation_id);
1402 talloc_free(tmp_ctx);
1404 return invocation_id;
1406 failed:
1407 DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1408 talloc_free(tmp_ctx);
1409 return NULL;
1412 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1414 TALLOC_CTX *tmp_ctx;
1415 struct GUID *invocation_id_new;
1416 struct GUID *invocation_id_old;
1418 /* see if we have a cached copy */
1419 invocation_id_old = (struct GUID *)ldb_get_opaque(ldb,
1420 "cache.invocation_id");
1422 tmp_ctx = talloc_new(ldb);
1423 if (tmp_ctx == NULL) {
1424 goto failed;
1427 invocation_id_new = talloc(tmp_ctx, struct GUID);
1428 if (!invocation_id_new) {
1429 goto failed;
1432 SMB_ASSERT(!GUID_all_zero(invocation_id_in));
1433 *invocation_id_new = *invocation_id_in;
1435 /* cache the domain_sid in the ldb */
1436 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1437 goto failed;
1440 talloc_steal(ldb, invocation_id_new);
1441 talloc_free(tmp_ctx);
1442 talloc_free(invocation_id_old);
1444 return true;
1446 failed:
1447 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1448 talloc_free(tmp_ctx);
1449 return false;
1453 work out the ntds settings objectGUID for the current open ldb
1455 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1457 TALLOC_CTX *tmp_ctx;
1458 const char *attrs[] = { "objectGUID", NULL };
1459 int ret;
1460 struct ldb_result *res;
1461 struct GUID *ntds_guid;
1463 /* see if we have a cached copy */
1464 ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1465 if (ntds_guid) {
1466 return ntds_guid;
1469 tmp_ctx = talloc_new(ldb);
1470 if (tmp_ctx == NULL) {
1471 goto failed;
1474 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1475 if (ret) {
1476 goto failed;
1479 if (res->count != 1) {
1480 goto failed;
1483 ntds_guid = talloc(tmp_ctx, struct GUID);
1484 if (!ntds_guid) {
1485 goto failed;
1488 *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1490 /* cache the domain_sid in the ldb */
1491 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1492 goto failed;
1495 talloc_steal(ldb, ntds_guid);
1496 talloc_free(tmp_ctx);
1498 return ntds_guid;
1500 failed:
1501 DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1502 talloc_free(tmp_ctx);
1503 return NULL;
1506 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1508 TALLOC_CTX *tmp_ctx;
1509 struct GUID *ntds_guid_new;
1510 struct GUID *ntds_guid_old;
1512 /* see if we have a cached copy */
1513 ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1515 tmp_ctx = talloc_new(ldb);
1516 if (tmp_ctx == NULL) {
1517 goto failed;
1520 ntds_guid_new = talloc(tmp_ctx, struct GUID);
1521 if (!ntds_guid_new) {
1522 goto failed;
1525 *ntds_guid_new = *ntds_guid_in;
1527 /* cache the domain_sid in the ldb */
1528 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1529 goto failed;
1532 talloc_steal(ldb, ntds_guid_new);
1533 talloc_free(tmp_ctx);
1534 talloc_free(ntds_guid_old);
1536 return true;
1538 failed:
1539 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1540 talloc_free(tmp_ctx);
1541 return false;
1545 work out the server dn for the current open ldb
1547 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1549 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1550 struct ldb_dn *dn;
1551 if (!tmp_ctx) {
1552 return NULL;
1554 dn = ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb, tmp_ctx));
1555 talloc_free(tmp_ctx);
1556 return dn;
1561 work out the server dn for the current open ldb
1563 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1565 struct ldb_dn *server_dn;
1566 struct ldb_dn *servers_dn;
1567 struct ldb_dn *server_site_dn;
1569 /* TODO: there must be a saner way to do this!! */
1570 server_dn = samdb_server_dn(ldb, mem_ctx);
1571 if (!server_dn) return NULL;
1573 servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1574 talloc_free(server_dn);
1575 if (!servers_dn) return NULL;
1577 server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1578 talloc_free(servers_dn);
1580 return server_site_dn;
1584 find the site name from a computers DN record
1586 int samdb_find_site_for_computer(struct ldb_context *ldb,
1587 TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1588 const char **site_name)
1590 int ret;
1591 struct ldb_dn *dn;
1592 const struct ldb_val *rdn_val;
1594 *site_name = NULL;
1596 ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1597 if (ret != LDB_SUCCESS) {
1598 return ret;
1601 if (!ldb_dn_remove_child_components(dn, 2)) {
1602 talloc_free(dn);
1603 return LDB_ERR_INVALID_DN_SYNTAX;
1606 rdn_val = ldb_dn_get_rdn_val(dn);
1607 if (rdn_val == NULL) {
1608 return LDB_ERR_OPERATIONS_ERROR;
1611 (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1612 talloc_free(dn);
1613 if (!*site_name) {
1614 return LDB_ERR_OPERATIONS_ERROR;
1616 return LDB_SUCCESS;
1620 find the NTDS GUID from a computers DN record
1622 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1623 struct GUID *ntds_guid)
1625 int ret;
1626 struct ldb_dn *dn;
1628 *ntds_guid = GUID_zero();
1630 ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1631 if (ret != LDB_SUCCESS) {
1632 return ret;
1635 if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1636 talloc_free(dn);
1637 return LDB_ERR_OPERATIONS_ERROR;
1640 ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1641 talloc_free(dn);
1642 return ret;
1646 find a 'reference' DN that points at another object
1647 (eg. serverReference, rIDManagerReference etc)
1649 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1650 const char *attribute, struct ldb_dn **dn)
1652 const char *attrs[2];
1653 struct ldb_result *res;
1654 int ret;
1656 attrs[0] = attribute;
1657 attrs[1] = NULL;
1659 ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY|DSDB_SEARCH_SHOW_EXTENDED_DN, NULL);
1660 if (ret != LDB_SUCCESS) {
1661 ldb_asprintf_errstring(ldb, "Cannot find DN %s to get attribute %s for reference dn: %s",
1662 ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb));
1663 return ret;
1666 *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1667 if (!*dn) {
1668 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1669 ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1670 ldb_dn_get_linearized(base));
1671 } else {
1672 ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1673 ldb_dn_get_linearized(base));
1675 talloc_free(res);
1676 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1679 talloc_free(res);
1680 return LDB_SUCCESS;
1684 find if a DN (must have GUID component!) is our ntdsDsa
1686 int samdb_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *dn, bool *is_ntdsa)
1688 NTSTATUS status;
1689 struct GUID dn_guid;
1690 const struct GUID *our_ntds_guid;
1691 status = dsdb_get_extended_dn_guid(dn, &dn_guid, "GUID");
1692 if (!NT_STATUS_IS_OK(status)) {
1693 return LDB_ERR_OPERATIONS_ERROR;
1696 our_ntds_guid = samdb_ntds_objectGUID(ldb);
1697 if (!our_ntds_guid) {
1698 DEBUG(0, ("Failed to find our NTDS Settings GUID for comparison with %s - %s\n", ldb_dn_get_linearized(dn), ldb_errstring(ldb)));
1699 return LDB_ERR_OPERATIONS_ERROR;
1702 *is_ntdsa = GUID_equal(&dn_guid, our_ntds_guid);
1703 return LDB_SUCCESS;
1707 find a 'reference' DN that points at another object and indicate if it is our ntdsDsa
1709 int samdb_reference_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *base,
1710 const char *attribute, bool *is_ntdsa)
1712 int ret;
1713 struct ldb_dn *referenced_dn;
1714 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1715 if (tmp_ctx == NULL) {
1716 return LDB_ERR_OPERATIONS_ERROR;
1718 ret = samdb_reference_dn(ldb, tmp_ctx, base, attribute, &referenced_dn);
1719 if (ret != LDB_SUCCESS) {
1720 DEBUG(0, ("Failed to find object %s for attribute %s - %s\n", ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb)));
1721 return ret;
1724 ret = samdb_dn_is_our_ntdsa(ldb, referenced_dn, is_ntdsa);
1726 talloc_free(tmp_ctx);
1727 return ret;
1731 find our machine account via the serverReference attribute in the
1732 server DN
1734 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1736 struct ldb_dn *server_dn;
1737 int ret;
1739 server_dn = samdb_server_dn(ldb, mem_ctx);
1740 if (server_dn == NULL) {
1741 return LDB_ERR_NO_SUCH_OBJECT;
1744 ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1745 talloc_free(server_dn);
1747 return ret;
1751 find the RID Manager$ DN via the rIDManagerReference attribute in the
1752 base DN
1754 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1756 return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1757 "rIDManagerReference", dn);
1761 find the RID Set DN via the rIDSetReferences attribute in our
1762 machine account DN
1764 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1766 struct ldb_dn *server_ref_dn;
1767 int ret;
1769 ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1770 if (ret != LDB_SUCCESS) {
1771 return ret;
1773 ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1774 talloc_free(server_ref_dn);
1775 return ret;
1778 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1780 const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1781 mem_ctx));
1783 if (val == NULL) {
1784 return NULL;
1787 return (const char *) val->data;
1791 * Finds the client site by using the client's IP address.
1792 * The "subnet_name" returns the name of the subnet if parameter != NULL
1794 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1795 const char *ip_address, char **subnet_name)
1797 const char *attrs[] = { "cn", "siteObject", NULL };
1798 struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1799 struct ldb_result *res;
1800 const struct ldb_val *val;
1801 const char *site_name = NULL, *l_subnet_name = NULL;
1802 const char *allow_list[2] = { NULL, NULL };
1803 unsigned int i, count;
1804 int cnt, ret;
1807 * if we don't have a client ip e.g. ncalrpc
1808 * the server site is the client site
1810 if (ip_address == NULL) {
1811 return samdb_server_site_name(ldb, mem_ctx);
1814 sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1815 if (sites_container_dn == NULL) {
1816 return NULL;
1819 subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1820 if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1821 talloc_free(sites_container_dn);
1822 talloc_free(subnets_dn);
1823 return NULL;
1826 ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1827 attrs, NULL);
1828 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1829 count = 0;
1830 } else if (ret != LDB_SUCCESS) {
1831 talloc_free(sites_container_dn);
1832 talloc_free(subnets_dn);
1833 return NULL;
1834 } else {
1835 count = res->count;
1838 for (i = 0; i < count; i++) {
1839 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1840 NULL);
1842 allow_list[0] = l_subnet_name;
1844 if (socket_allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1845 sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1846 res->msgs[i],
1847 "siteObject");
1848 if (sites_dn == NULL) {
1849 /* No reference, maybe another subnet matches */
1850 continue;
1853 /* "val" cannot be NULL here since "sites_dn" != NULL */
1854 val = ldb_dn_get_rdn_val(sites_dn);
1855 site_name = talloc_strdup(mem_ctx,
1856 (const char *) val->data);
1858 talloc_free(sites_dn);
1860 break;
1864 if (site_name == NULL) {
1865 /* This is the Windows Server fallback rule: when no subnet
1866 * exists and we have only one site available then use it (it
1867 * is for sure the same as our server site). If more sites do
1868 * exist then we don't know which one to use and set the site
1869 * name to "". */
1870 cnt = samdb_search_count(ldb, mem_ctx, sites_container_dn,
1871 "(objectClass=site)");
1872 if (cnt == 1) {
1873 site_name = samdb_server_site_name(ldb, mem_ctx);
1874 } else {
1875 site_name = talloc_strdup(mem_ctx, "");
1877 l_subnet_name = NULL;
1880 if (subnet_name != NULL) {
1881 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1884 talloc_free(sites_container_dn);
1885 talloc_free(subnets_dn);
1886 talloc_free(res);
1888 return site_name;
1892 work out if we are the PDC for the domain of the current open ldb
1894 bool samdb_is_pdc(struct ldb_context *ldb)
1896 int ret;
1897 bool is_pdc;
1899 ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner",
1900 &is_pdc);
1901 if (ret != LDB_SUCCESS) {
1902 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n",
1903 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
1904 ldb_errstring(ldb)));
1905 return false;
1908 return is_pdc;
1912 work out if we are a Global Catalog server for the domain of the current open ldb
1914 bool samdb_is_gc(struct ldb_context *ldb)
1916 uint32_t options;
1917 if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
1918 return false;
1920 return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
1923 /* Find a domain object in the parents of a particular DN. */
1924 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1925 struct ldb_dn **parent_dn, const char **errstring)
1927 TALLOC_CTX *local_ctx;
1928 struct ldb_dn *sdn = dn;
1929 struct ldb_result *res = NULL;
1930 int ret = LDB_SUCCESS;
1931 const char *attrs[] = { NULL };
1933 local_ctx = talloc_new(mem_ctx);
1934 if (local_ctx == NULL) return ldb_oom(ldb);
1936 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1937 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1938 "(|(objectClass=domain)(objectClass=builtinDomain))");
1939 if (ret == LDB_SUCCESS) {
1940 if (res->count == 1) {
1941 break;
1943 } else {
1944 break;
1948 if (ret != LDB_SUCCESS) {
1949 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1950 ldb_dn_get_linearized(dn),
1951 ldb_dn_get_linearized(sdn),
1952 ldb_errstring(ldb));
1953 talloc_free(local_ctx);
1954 return ret;
1956 if (res->count != 1) {
1957 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1958 ldb_dn_get_linearized(dn));
1959 DEBUG(0,(__location__ ": %s\n", *errstring));
1960 talloc_free(local_ctx);
1961 return LDB_ERR_CONSTRAINT_VIOLATION;
1964 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1965 talloc_free(local_ctx);
1966 return ret;
1971 * Performs checks on a user password (plaintext UNIX format - attribute
1972 * "password"). The remaining parameters have to be extracted from the domain
1973 * object in the AD.
1975 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1977 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *utf8_blob,
1978 const uint32_t pwdProperties,
1979 const uint32_t minPwdLength)
1981 const char *utf8_pw = (const char *)utf8_blob->data;
1982 size_t utf8_len = strlen_m(utf8_pw);
1984 /* checks if the "minPwdLength" property is satisfied */
1985 if (minPwdLength > utf8_len) {
1986 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1989 /* checks the password complexity */
1990 if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
1991 return SAMR_VALIDATION_STATUS_SUCCESS;
1994 if (utf8_len == 0) {
1995 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1998 if (!check_password_quality(utf8_pw)) {
1999 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2002 return SAMR_VALIDATION_STATUS_SUCCESS;
2006 * Callback for "samdb_set_password" password change
2008 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2010 int ret;
2012 if (!ares) {
2013 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2016 if (ares->error != LDB_SUCCESS) {
2017 ret = ares->error;
2018 req->context = talloc_steal(req,
2019 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2020 talloc_free(ares);
2021 return ldb_request_done(req, ret);
2024 if (ares->type != LDB_REPLY_DONE) {
2025 talloc_free(ares);
2026 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2029 req->context = talloc_steal(req,
2030 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2031 talloc_free(ares);
2032 return ldb_request_done(req, LDB_SUCCESS);
2036 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2037 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2038 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2039 * user change or not. The "rejectReason" gives some more information if the
2040 * change failed.
2042 * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2043 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2045 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2046 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2047 const DATA_BLOB *new_password,
2048 const struct samr_Password *lmNewHash,
2049 const struct samr_Password *ntNewHash,
2050 const struct samr_Password *lmOldHash,
2051 const struct samr_Password *ntOldHash,
2052 enum samPwdChangeReason *reject_reason,
2053 struct samr_DomInfo1 **_dominfo)
2055 struct ldb_message *msg;
2056 struct ldb_message_element *el;
2057 struct ldb_request *req;
2058 struct dsdb_control_password_change_status *pwd_stat = NULL;
2059 int ret;
2060 bool hash_values = false;
2061 NTSTATUS status = NT_STATUS_OK;
2063 #define CHECK_RET(x) \
2064 if (x != LDB_SUCCESS) { \
2065 talloc_free(msg); \
2066 return NT_STATUS_NO_MEMORY; \
2069 msg = ldb_msg_new(mem_ctx);
2070 if (msg == NULL) {
2071 return NT_STATUS_NO_MEMORY;
2073 msg->dn = user_dn;
2074 if ((new_password != NULL)
2075 && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2076 /* we have the password as plaintext UTF16 */
2077 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2078 new_password, NULL));
2079 el = ldb_msg_find_element(msg, "clearTextPassword");
2080 el->flags = LDB_FLAG_MOD_REPLACE;
2081 } else if ((new_password == NULL)
2082 && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2083 /* we have a password as LM and/or NT hash */
2084 if (lmNewHash != NULL) {
2085 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2086 "dBCSPwd", lmNewHash));
2087 el = ldb_msg_find_element(msg, "dBCSPwd");
2088 el->flags = LDB_FLAG_MOD_REPLACE;
2090 if (ntNewHash != NULL) {
2091 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2092 "unicodePwd", ntNewHash));
2093 el = ldb_msg_find_element(msg, "unicodePwd");
2094 el->flags = LDB_FLAG_MOD_REPLACE;
2096 hash_values = true;
2097 } else {
2098 /* the password wasn't specified correctly */
2099 talloc_free(msg);
2100 return NT_STATUS_INVALID_PARAMETER;
2103 /* build modify request */
2104 ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2105 samdb_set_password_callback, NULL);
2106 if (ret != LDB_SUCCESS) {
2107 talloc_free(msg);
2108 return NT_STATUS_NO_MEMORY;
2111 /* A password change operation */
2112 if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2113 struct dsdb_control_password_change *change;
2115 change = talloc(req, struct dsdb_control_password_change);
2116 if (change == NULL) {
2117 talloc_free(req);
2118 talloc_free(msg);
2119 return NT_STATUS_NO_MEMORY;
2122 change->old_nt_pwd_hash = ntOldHash;
2123 change->old_lm_pwd_hash = lmOldHash;
2125 ret = ldb_request_add_control(req,
2126 DSDB_CONTROL_PASSWORD_CHANGE_OID,
2127 true, change);
2128 if (ret != LDB_SUCCESS) {
2129 talloc_free(req);
2130 talloc_free(msg);
2131 return NT_STATUS_NO_MEMORY;
2134 if (hash_values) {
2135 ret = ldb_request_add_control(req,
2136 DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2137 true, NULL);
2138 if (ret != LDB_SUCCESS) {
2139 talloc_free(req);
2140 talloc_free(msg);
2141 return NT_STATUS_NO_MEMORY;
2144 ret = ldb_request_add_control(req,
2145 DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2146 true, NULL);
2147 if (ret != LDB_SUCCESS) {
2148 talloc_free(req);
2149 talloc_free(msg);
2150 return NT_STATUS_NO_MEMORY;
2153 ret = dsdb_autotransaction_request(ldb, req);
2155 if (req->context != NULL) {
2156 struct ldb_control *control = talloc_get_type_abort(req->context,
2157 struct ldb_control);
2158 pwd_stat = talloc_get_type_abort(control->data,
2159 struct dsdb_control_password_change_status);
2160 talloc_steal(mem_ctx, pwd_stat);
2163 talloc_free(req);
2164 talloc_free(msg);
2166 /* Sets the domain info (if requested) */
2167 if (_dominfo != NULL) {
2168 struct samr_DomInfo1 *dominfo;
2170 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2171 if (dominfo == NULL) {
2172 return NT_STATUS_NO_MEMORY;
2175 if (pwd_stat != NULL) {
2176 dominfo->min_password_length = pwd_stat->domain_data.minPwdLength;
2177 dominfo->password_properties = pwd_stat->domain_data.pwdProperties;
2178 dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2179 dominfo->max_password_age = pwd_stat->domain_data.maxPwdAge;
2180 dominfo->min_password_age = pwd_stat->domain_data.minPwdAge;
2183 *_dominfo = dominfo;
2186 if (reject_reason != NULL) {
2187 if (pwd_stat != NULL) {
2188 *reject_reason = pwd_stat->reject_reason;
2189 } else {
2190 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2194 if (pwd_stat != NULL) {
2195 talloc_free(pwd_stat);
2198 if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2199 const char *errmsg = ldb_errstring(ldb);
2200 char *endptr = NULL;
2201 WERROR werr = WERR_GENERAL_FAILURE;
2202 status = NT_STATUS_UNSUCCESSFUL;
2203 if (errmsg != NULL) {
2204 werr = W_ERROR(strtol(errmsg, &endptr, 16));
2206 if (endptr != errmsg) {
2207 if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2208 status = NT_STATUS_WRONG_PASSWORD;
2210 if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2211 status = NT_STATUS_PASSWORD_RESTRICTION;
2214 } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2215 /* don't let the caller know if an account doesn't exist */
2216 status = NT_STATUS_WRONG_PASSWORD;
2217 } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2218 status = NT_STATUS_ACCESS_DENIED;
2219 } else if (ret != LDB_SUCCESS) {
2220 DEBUG(1, ("Failed to set password on %s: %s\n",
2221 ldb_dn_get_linearized(msg->dn),
2222 ldb_errstring(ldb)));
2223 status = NT_STATUS_UNSUCCESSFUL;
2226 return status;
2230 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2231 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2232 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2233 * user change or not. The "rejectReason" gives some more information if the
2234 * change failed.
2236 * This wrapper function for "samdb_set_password" takes a SID as input rather
2237 * than a user DN.
2239 * This call encapsulates a new LDB transaction for changing the password;
2240 * therefore the user hasn't to start a new one.
2242 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2243 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2244 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2245 * NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2247 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2248 const struct dom_sid *user_sid,
2249 const DATA_BLOB *new_password,
2250 const struct samr_Password *lmNewHash,
2251 const struct samr_Password *ntNewHash,
2252 const struct samr_Password *lmOldHash,
2253 const struct samr_Password *ntOldHash,
2254 enum samPwdChangeReason *reject_reason,
2255 struct samr_DomInfo1 **_dominfo)
2257 NTSTATUS nt_status;
2258 struct ldb_dn *user_dn;
2259 int ret;
2261 ret = ldb_transaction_start(ldb);
2262 if (ret != LDB_SUCCESS) {
2263 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2264 return NT_STATUS_TRANSACTION_ABORTED;
2267 user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2268 "(&(objectSid=%s)(objectClass=user))",
2269 ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2270 if (!user_dn) {
2271 ldb_transaction_cancel(ldb);
2272 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2273 dom_sid_string(mem_ctx, user_sid)));
2274 return NT_STATUS_NO_SUCH_USER;
2277 nt_status = samdb_set_password(ldb, mem_ctx,
2278 user_dn, NULL,
2279 new_password,
2280 lmNewHash, ntNewHash,
2281 lmOldHash, ntOldHash,
2282 reject_reason, _dominfo);
2283 if (!NT_STATUS_IS_OK(nt_status)) {
2284 ldb_transaction_cancel(ldb);
2285 talloc_free(user_dn);
2286 return nt_status;
2289 ret = ldb_transaction_commit(ldb);
2290 if (ret != LDB_SUCCESS) {
2291 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2292 ldb_dn_get_linearized(user_dn),
2293 ldb_errstring(ldb)));
2294 talloc_free(user_dn);
2295 return NT_STATUS_TRANSACTION_ABORTED;
2298 talloc_free(user_dn);
2299 return NT_STATUS_OK;
2303 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
2304 struct dom_sid *sid, struct ldb_dn **ret_dn)
2306 struct ldb_message *msg;
2307 struct ldb_dn *basedn;
2308 char *sidstr;
2309 int ret;
2311 sidstr = dom_sid_string(mem_ctx, sid);
2312 NT_STATUS_HAVE_NO_MEMORY(sidstr);
2314 /* We might have to create a ForeignSecurityPrincipal, even if this user
2315 * is in our own domain */
2317 msg = ldb_msg_new(sidstr);
2318 if (msg == NULL) {
2319 talloc_free(sidstr);
2320 return NT_STATUS_NO_MEMORY;
2323 ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2324 ldb_get_default_basedn(sam_ctx),
2325 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2326 &basedn);
2327 if (ret != LDB_SUCCESS) {
2328 DEBUG(0, ("Failed to find DN for "
2329 "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2330 talloc_free(sidstr);
2331 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2334 /* add core elements to the ldb_message for the alias */
2335 msg->dn = basedn;
2336 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2337 talloc_free(sidstr);
2338 return NT_STATUS_NO_MEMORY;
2341 ret = ldb_msg_add_string(msg, "objectClass",
2342 "foreignSecurityPrincipal");
2343 if (ret != LDB_SUCCESS) {
2344 talloc_free(sidstr);
2345 return NT_STATUS_NO_MEMORY;
2348 /* create the alias */
2349 ret = ldb_add(sam_ctx, msg);
2350 if (ret != LDB_SUCCESS) {
2351 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2352 "record %s: %s\n",
2353 ldb_dn_get_linearized(msg->dn),
2354 ldb_errstring(sam_ctx)));
2355 talloc_free(sidstr);
2356 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2359 *ret_dn = talloc_steal(mem_ctx, msg->dn);
2360 talloc_free(sidstr);
2362 return NT_STATUS_OK;
2367 Find the DN of a domain, assuming it to be a dotted.dns name
2370 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
2372 unsigned int i;
2373 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2374 const char *binary_encoded;
2375 const char * const *split_realm;
2376 struct ldb_dn *dn;
2378 if (!tmp_ctx) {
2379 return NULL;
2382 split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
2383 if (!split_realm) {
2384 talloc_free(tmp_ctx);
2385 return NULL;
2387 dn = ldb_dn_new(mem_ctx, ldb, NULL);
2388 for (i=0; split_realm[i]; i++) {
2389 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2390 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2391 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2392 binary_encoded, ldb_dn_get_linearized(dn)));
2393 talloc_free(tmp_ctx);
2394 return NULL;
2397 if (!ldb_dn_validate(dn)) {
2398 DEBUG(2, ("Failed to validated DN %s\n",
2399 ldb_dn_get_linearized(dn)));
2400 talloc_free(tmp_ctx);
2401 return NULL;
2403 talloc_free(tmp_ctx);
2404 return dn;
2409 Find the DNS equivalent of a DN, in dotted DNS form
2411 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
2413 int i, num_components = ldb_dn_get_comp_num(dn);
2414 char *dns_name = talloc_strdup(mem_ctx, "");
2415 if (dns_name == NULL) {
2416 return NULL;
2419 for (i=0; i<num_components; i++) {
2420 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
2421 char *s;
2422 if (v == NULL) {
2423 talloc_free(dns_name);
2424 return NULL;
2426 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
2427 (int)v->length, (int)v->length, (char *)v->data);
2428 if (s == NULL) {
2429 talloc_free(dns_name);
2430 return NULL;
2432 dns_name = s;
2435 /* remove the last '.' */
2436 if (dns_name[0] != 0) {
2437 dns_name[strlen(dns_name)-1] = 0;
2440 return dns_name;
2444 Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
2445 name is based on the forest DNS name
2447 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
2448 TALLOC_CTX *mem_ctx,
2449 const struct GUID *ntds_guid)
2451 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2452 const char *guid_str;
2453 struct ldb_dn *forest_dn;
2454 const char *dnsforest;
2455 char *ret;
2457 guid_str = GUID_string(tmp_ctx, ntds_guid);
2458 if (guid_str == NULL) {
2459 talloc_free(tmp_ctx);
2460 return NULL;
2462 forest_dn = ldb_get_root_basedn(samdb);
2463 if (forest_dn == NULL) {
2464 talloc_free(tmp_ctx);
2465 return NULL;
2467 dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
2468 if (dnsforest == NULL) {
2469 talloc_free(tmp_ctx);
2470 return NULL;
2472 ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
2473 talloc_free(tmp_ctx);
2474 return ret;
2479 Find the DN of a domain, be it the netbios or DNS name
2481 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2482 const char *domain_name)
2484 const char * const domain_ref_attrs[] = {
2485 "ncName", NULL
2487 const char * const domain_ref2_attrs[] = {
2488 NULL
2490 struct ldb_result *res_domain_ref;
2491 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2492 /* find the domain's DN */
2493 int ret_domain = ldb_search(ldb, mem_ctx,
2494 &res_domain_ref,
2495 samdb_partitions_dn(ldb, mem_ctx),
2496 LDB_SCOPE_ONELEVEL,
2497 domain_ref_attrs,
2498 "(&(nETBIOSName=%s)(objectclass=crossRef))",
2499 escaped_domain);
2500 if (ret_domain != LDB_SUCCESS) {
2501 return NULL;
2504 if (res_domain_ref->count == 0) {
2505 ret_domain = ldb_search(ldb, mem_ctx,
2506 &res_domain_ref,
2507 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2508 LDB_SCOPE_BASE,
2509 domain_ref2_attrs,
2510 "(objectclass=domain)");
2511 if (ret_domain != LDB_SUCCESS) {
2512 return NULL;
2515 if (res_domain_ref->count == 1) {
2516 return res_domain_ref->msgs[0]->dn;
2518 return NULL;
2521 if (res_domain_ref->count > 1) {
2522 DEBUG(0,("Found %d records matching domain [%s]\n",
2523 ret_domain, domain_name));
2524 return NULL;
2527 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2533 use a GUID to find a DN
2535 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
2536 TALLOC_CTX *mem_ctx,
2537 const struct GUID *guid,
2538 uint32_t dsdb_flags,
2539 struct ldb_dn **dn)
2541 int ret;
2542 struct ldb_result *res;
2543 const char *attrs[] = { NULL };
2544 char *guid_str = GUID_string(mem_ctx, guid);
2546 if (!guid_str) {
2547 return ldb_operr(ldb);
2550 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2551 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2552 DSDB_SEARCH_SHOW_EXTENDED_DN |
2553 DSDB_SEARCH_ONE_ONLY | dsdb_flags,
2554 "objectGUID=%s", guid_str);
2555 talloc_free(guid_str);
2556 if (ret != LDB_SUCCESS) {
2557 return ret;
2560 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2561 talloc_free(res);
2563 return LDB_SUCCESS;
2567 use a DN to find a GUID with a given attribute name
2569 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2570 struct ldb_dn *dn, const char *attribute,
2571 struct GUID *guid)
2573 int ret;
2574 struct ldb_result *res;
2575 const char *attrs[2];
2576 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2578 attrs[0] = attribute;
2579 attrs[1] = NULL;
2581 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2582 DSDB_SEARCH_SHOW_DELETED |
2583 DSDB_SEARCH_SHOW_RECYCLED);
2584 if (ret != LDB_SUCCESS) {
2585 talloc_free(tmp_ctx);
2586 return ret;
2588 if (res->count < 1) {
2589 talloc_free(tmp_ctx);
2590 return LDB_ERR_NO_SUCH_OBJECT;
2592 *guid = samdb_result_guid(res->msgs[0], attribute);
2593 talloc_free(tmp_ctx);
2594 return LDB_SUCCESS;
2598 use a DN to find a GUID
2600 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2601 struct ldb_dn *dn, struct GUID *guid)
2603 return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2609 adds the given GUID to the given ldb_message. This value is added
2610 for the given attr_name (may be either "objectGUID" or "parentGUID").
2612 int dsdb_msg_add_guid(struct ldb_message *msg,
2613 struct GUID *guid,
2614 const char *attr_name)
2616 int ret;
2617 struct ldb_val v;
2618 NTSTATUS status;
2619 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
2621 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2622 if (!NT_STATUS_IS_OK(status)) {
2623 ret = LDB_ERR_OPERATIONS_ERROR;
2624 goto done;
2627 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2628 if (ret != LDB_SUCCESS) {
2629 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2630 attr_name));
2631 goto done;
2634 ret = LDB_SUCCESS;
2636 done:
2637 talloc_free(tmp_ctx);
2638 return ret;
2644 use a DN to find a SID
2646 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
2647 struct ldb_dn *dn, struct dom_sid *sid)
2649 int ret;
2650 struct ldb_result *res;
2651 const char *attrs[] = { "objectSid", NULL };
2652 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2653 struct dom_sid *s;
2655 ZERO_STRUCTP(sid);
2657 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2658 DSDB_SEARCH_SHOW_DELETED |
2659 DSDB_SEARCH_SHOW_RECYCLED);
2660 if (ret != LDB_SUCCESS) {
2661 talloc_free(tmp_ctx);
2662 return ret;
2664 if (res->count < 1) {
2665 talloc_free(tmp_ctx);
2666 return LDB_ERR_NO_SUCH_OBJECT;
2668 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
2669 if (s == NULL) {
2670 talloc_free(tmp_ctx);
2671 return LDB_ERR_NO_SUCH_OBJECT;
2673 *sid = *s;
2674 talloc_free(tmp_ctx);
2675 return LDB_SUCCESS;
2679 use a SID to find a DN
2681 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
2682 TALLOC_CTX *mem_ctx,
2683 struct dom_sid *sid, struct ldb_dn **dn)
2685 int ret;
2686 struct ldb_result *res;
2687 const char *attrs[] = { NULL };
2688 char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
2690 if (!sid_str) {
2691 return ldb_operr(ldb);
2694 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2695 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2696 DSDB_SEARCH_SHOW_EXTENDED_DN |
2697 DSDB_SEARCH_ONE_ONLY,
2698 "objectSid=%s", sid_str);
2699 talloc_free(sid_str);
2700 if (ret != LDB_SUCCESS) {
2701 return ret;
2704 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2705 talloc_free(res);
2707 return LDB_SUCCESS;
2711 load a repsFromTo blob list for a given partition GUID
2712 attr must be "repsFrom" or "repsTo"
2714 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2715 const char *attr, struct repsFromToBlob **r, uint32_t *count)
2717 const char *attrs[] = { attr, NULL };
2718 struct ldb_result *res = NULL;
2719 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2720 unsigned int i;
2721 struct ldb_message_element *el;
2722 int ret;
2724 *r = NULL;
2725 *count = 0;
2727 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
2728 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2729 /* partition hasn't been replicated yet */
2730 return WERR_OK;
2732 if (ret != LDB_SUCCESS) {
2733 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
2734 talloc_free(tmp_ctx);
2735 return WERR_DS_DRA_INTERNAL_ERROR;
2738 el = ldb_msg_find_element(res->msgs[0], attr);
2739 if (el == NULL) {
2740 /* it's OK to be empty */
2741 talloc_free(tmp_ctx);
2742 return WERR_OK;
2745 *count = el->num_values;
2746 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2747 if (*r == NULL) {
2748 talloc_free(tmp_ctx);
2749 return WERR_DS_DRA_INTERNAL_ERROR;
2752 for (i=0; i<(*count); i++) {
2753 enum ndr_err_code ndr_err;
2754 ndr_err = ndr_pull_struct_blob(&el->values[i],
2755 mem_ctx,
2756 &(*r)[i],
2757 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2758 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2759 talloc_free(tmp_ctx);
2760 return WERR_DS_DRA_INTERNAL_ERROR;
2764 talloc_free(tmp_ctx);
2766 return WERR_OK;
2770 save the repsFromTo blob list for a given partition GUID
2771 attr must be "repsFrom" or "repsTo"
2773 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2774 const char *attr, struct repsFromToBlob *r, uint32_t count)
2776 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2777 struct ldb_message *msg;
2778 struct ldb_message_element *el;
2779 unsigned int i;
2781 msg = ldb_msg_new(tmp_ctx);
2782 msg->dn = dn;
2783 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2784 goto failed;
2787 el->values = talloc_array(msg, struct ldb_val, count);
2788 if (!el->values) {
2789 goto failed;
2792 for (i=0; i<count; i++) {
2793 struct ldb_val v;
2794 enum ndr_err_code ndr_err;
2796 ndr_err = ndr_push_struct_blob(&v, tmp_ctx,
2797 &r[i],
2798 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2799 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2800 goto failed;
2803 el->num_values++;
2804 el->values[i] = v;
2807 if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
2808 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2809 goto failed;
2812 talloc_free(tmp_ctx);
2814 return WERR_OK;
2816 failed:
2817 talloc_free(tmp_ctx);
2818 return WERR_DS_DRA_INTERNAL_ERROR;
2823 load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2824 object for a partition
2826 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2827 uint64_t *uSN, uint64_t *urgent_uSN)
2829 struct ldb_request *req;
2830 int ret;
2831 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2832 struct dsdb_control_current_partition *p_ctrl;
2833 struct ldb_result *res;
2835 res = talloc_zero(tmp_ctx, struct ldb_result);
2836 if (!res) {
2837 talloc_free(tmp_ctx);
2838 return ldb_oom(ldb);
2841 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2842 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2843 LDB_SCOPE_BASE,
2844 NULL, NULL,
2845 NULL,
2846 res, ldb_search_default_callback,
2847 NULL);
2848 if (ret != LDB_SUCCESS) {
2849 talloc_free(tmp_ctx);
2850 return ret;
2853 p_ctrl = talloc(req, struct dsdb_control_current_partition);
2854 if (p_ctrl == NULL) {
2855 talloc_free(tmp_ctx);
2856 return ldb_oom(ldb);
2858 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2859 p_ctrl->dn = dn;
2861 ret = ldb_request_add_control(req,
2862 DSDB_CONTROL_CURRENT_PARTITION_OID,
2863 false, p_ctrl);
2864 if (ret != LDB_SUCCESS) {
2865 talloc_free(tmp_ctx);
2866 return ret;
2869 /* Run the new request */
2870 ret = ldb_request(ldb, req);
2872 if (ret == LDB_SUCCESS) {
2873 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2876 if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
2877 /* it hasn't been created yet, which means
2878 an implicit value of zero */
2879 *uSN = 0;
2880 talloc_free(tmp_ctx);
2881 return LDB_SUCCESS;
2884 if (ret != LDB_SUCCESS) {
2885 talloc_free(tmp_ctx);
2886 return ret;
2889 if (res->count < 1) {
2890 *uSN = 0;
2891 if (urgent_uSN) {
2892 *urgent_uSN = 0;
2894 } else {
2895 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2896 if (urgent_uSN) {
2897 *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2901 talloc_free(tmp_ctx);
2903 return LDB_SUCCESS;
2906 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2907 const struct drsuapi_DsReplicaCursor2 *c2)
2909 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2912 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2913 const struct drsuapi_DsReplicaCursor *c2)
2915 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2920 see if a computer identified by its invocationId is a RODC
2922 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
2924 /* 1) find the DN for this servers NTDSDSA object
2925 2) search for the msDS-isRODC attribute
2926 3) if not present then not a RODC
2927 4) if present and TRUE then is a RODC
2929 struct ldb_dn *config_dn;
2930 const char *attrs[] = { "msDS-isRODC", NULL };
2931 int ret;
2932 struct ldb_result *res;
2933 TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
2935 config_dn = ldb_get_config_basedn(sam_ctx);
2936 if (!config_dn) {
2937 talloc_free(tmp_ctx);
2938 return ldb_operr(sam_ctx);
2941 ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
2942 DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
2944 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2945 *is_rodc = false;
2946 talloc_free(tmp_ctx);
2947 return LDB_SUCCESS;
2950 if (ret != LDB_SUCCESS) {
2951 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
2952 GUID_string(tmp_ctx, objectGUID)));
2953 *is_rodc = false;
2954 talloc_free(tmp_ctx);
2955 return ret;
2958 ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
2959 *is_rodc = (ret == 1);
2961 talloc_free(tmp_ctx);
2962 return LDB_SUCCESS;
2967 see if we are a RODC
2969 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
2971 const struct GUID *objectGUID;
2972 int ret;
2973 bool *cached;
2975 /* see if we have a cached copy */
2976 cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
2977 if (cached) {
2978 *am_rodc = *cached;
2979 return LDB_SUCCESS;
2982 objectGUID = samdb_ntds_objectGUID(sam_ctx);
2983 if (!objectGUID) {
2984 return ldb_operr(sam_ctx);
2987 ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
2988 if (ret != LDB_SUCCESS) {
2989 return ret;
2992 cached = talloc(sam_ctx, bool);
2993 if (cached == NULL) {
2994 return ldb_oom(sam_ctx);
2996 *cached = *am_rodc;
2998 ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
2999 if (ret != LDB_SUCCESS) {
3000 talloc_free(cached);
3001 return ldb_operr(sam_ctx);
3004 return LDB_SUCCESS;
3007 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3009 TALLOC_CTX *tmp_ctx;
3010 bool *cached;
3012 tmp_ctx = talloc_new(ldb);
3013 if (tmp_ctx == NULL) {
3014 goto failed;
3017 cached = talloc(tmp_ctx, bool);
3018 if (!cached) {
3019 goto failed;
3022 *cached = am_rodc;
3023 if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3024 goto failed;
3027 talloc_steal(ldb, cached);
3028 talloc_free(tmp_ctx);
3029 return true;
3031 failed:
3032 DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3033 talloc_free(tmp_ctx);
3034 return false;
3039 * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3040 * flags are DS_NTDSSETTINGS_OPT_*
3042 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3043 uint32_t *options)
3045 int rc;
3046 TALLOC_CTX *tmp_ctx;
3047 struct ldb_result *res;
3048 struct ldb_dn *site_dn;
3049 const char *attrs[] = { "options", NULL };
3051 tmp_ctx = talloc_new(ldb_ctx);
3052 if (tmp_ctx == NULL)
3053 goto failed;
3055 /* Retrieve the site dn for the ldb that we
3056 * have open. This is our local site.
3058 site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3059 if (site_dn == NULL)
3060 goto failed;
3062 /* Perform a one level (child) search from the local
3063 * site distinguided name. We're looking for the
3064 * "options" attribute within the nTDSSiteSettings
3065 * object
3067 rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3068 LDB_SCOPE_ONELEVEL, attrs,
3069 "objectClass=nTDSSiteSettings");
3071 if (rc != LDB_SUCCESS || res->count != 1)
3072 goto failed;
3074 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3076 talloc_free(tmp_ctx);
3078 return LDB_SUCCESS;
3080 failed:
3081 DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3082 talloc_free(tmp_ctx);
3083 return LDB_ERR_NO_SUCH_OBJECT;
3087 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
3089 flags are DS_NTDS_OPTION_*
3091 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3093 TALLOC_CTX *tmp_ctx;
3094 const char *attrs[] = { "options", NULL };
3095 int ret;
3096 struct ldb_result *res;
3098 tmp_ctx = talloc_new(ldb);
3099 if (tmp_ctx == NULL) {
3100 goto failed;
3103 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3104 if (ret != LDB_SUCCESS) {
3105 goto failed;
3108 if (res->count != 1) {
3109 goto failed;
3112 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3114 talloc_free(tmp_ctx);
3116 return LDB_SUCCESS;
3118 failed:
3119 DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3120 talloc_free(tmp_ctx);
3121 return LDB_ERR_NO_SUCH_OBJECT;
3124 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3126 const char *attrs[] = { "objectCategory", NULL };
3127 int ret;
3128 struct ldb_result *res;
3130 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3131 if (ret != LDB_SUCCESS) {
3132 goto failed;
3135 if (res->count != 1) {
3136 goto failed;
3139 return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3141 failed:
3142 DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3143 return NULL;
3147 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3148 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3150 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3152 char **tokens, *ret;
3153 size_t i;
3155 tokens = str_list_make(mem_ctx, cn, " -_");
3156 if (tokens == NULL)
3157 return NULL;
3159 /* "tolower()" and "toupper()" should also work properly on 0x00 */
3160 tokens[0][0] = tolower(tokens[0][0]);
3161 for (i = 1; i < str_list_length((const char * const *)tokens); i++)
3162 tokens[i][0] = toupper(tokens[i][0]);
3164 ret = talloc_strdup(mem_ctx, tokens[0]);
3165 for (i = 1; i < str_list_length((const char * const *)tokens); i++)
3166 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3168 talloc_free(tokens);
3170 return ret;
3174 * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3176 int dsdb_functional_level(struct ldb_context *ldb)
3178 int *domainFunctionality =
3179 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3180 if (!domainFunctionality) {
3181 /* this is expected during initial provision */
3182 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3183 return DS_DOMAIN_FUNCTION_2000;
3185 return *domainFunctionality;
3189 * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3191 int dsdb_forest_functional_level(struct ldb_context *ldb)
3193 int *forestFunctionality =
3194 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3195 if (!forestFunctionality) {
3196 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3197 return DS_DOMAIN_FUNCTION_2000;
3199 return *forestFunctionality;
3203 set a GUID in an extended DN structure
3205 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3207 struct ldb_val v;
3208 NTSTATUS status;
3209 int ret;
3211 status = GUID_to_ndr_blob(guid, dn, &v);
3212 if (!NT_STATUS_IS_OK(status)) {
3213 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3216 ret = ldb_dn_set_extended_component(dn, component_name, &v);
3217 data_blob_free(&v);
3218 return ret;
3222 return a GUID from a extended DN structure
3224 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3226 const struct ldb_val *v;
3228 v = ldb_dn_get_extended_component(dn, component_name);
3229 if (v == NULL) {
3230 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3233 return GUID_from_ndr_blob(v, guid);
3237 return a uint64_t from a extended DN structure
3239 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3241 const struct ldb_val *v;
3242 char *s;
3244 v = ldb_dn_get_extended_component(dn, component_name);
3245 if (v == NULL) {
3246 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3248 s = talloc_strndup(dn, (const char *)v->data, v->length);
3249 NT_STATUS_HAVE_NO_MEMORY(s);
3251 *val = strtoull(s, NULL, 0);
3253 talloc_free(s);
3254 return NT_STATUS_OK;
3258 return a NTTIME from a extended DN structure
3260 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3262 return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3266 return a uint32_t from a extended DN structure
3268 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3270 const struct ldb_val *v;
3271 char *s;
3273 v = ldb_dn_get_extended_component(dn, component_name);
3274 if (v == NULL) {
3275 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3278 s = talloc_strndup(dn, (const char *)v->data, v->length);
3279 NT_STATUS_HAVE_NO_MEMORY(s);
3281 *val = strtoul(s, NULL, 0);
3283 talloc_free(s);
3284 return NT_STATUS_OK;
3288 return a dom_sid from a extended DN structure
3290 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3292 const struct ldb_val *sid_blob;
3293 struct TALLOC_CTX *tmp_ctx;
3294 enum ndr_err_code ndr_err;
3296 sid_blob = ldb_dn_get_extended_component(dn, component_name);
3297 if (!sid_blob) {
3298 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3301 tmp_ctx = talloc_new(NULL);
3303 ndr_err = ndr_pull_struct_blob_all(sid_blob, tmp_ctx, sid,
3304 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3305 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3306 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3307 talloc_free(tmp_ctx);
3308 return status;
3311 talloc_free(tmp_ctx);
3312 return NT_STATUS_OK;
3317 return RMD_FLAGS directly from a ldb_dn
3318 returns 0 if not found
3320 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3322 const struct ldb_val *v;
3323 char buf[32];
3324 v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
3325 if (!v || v->length > sizeof(buf)-1) return 0;
3326 strncpy(buf, (const char *)v->data, v->length);
3327 buf[v->length] = 0;
3328 return strtoul(buf, NULL, 10);
3332 return RMD_FLAGS directly from a ldb_val for a DN
3333 returns 0 if RMD_FLAGS is not found
3335 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3337 const char *p;
3338 uint32_t flags;
3339 char *end;
3341 if (val->length < 13) {
3342 return 0;
3344 p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3345 if (!p) {
3346 return 0;
3348 flags = strtoul(p+11, &end, 10);
3349 if (!end || *end != '>') {
3350 /* it must end in a > */
3351 return 0;
3353 return flags;
3357 return true if a ldb_val containing a DN in storage form is deleted
3359 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3361 return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3365 return true if a ldb_val containing a DN in storage form is
3366 in the upgraded w2k3 linked attribute format
3368 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3370 return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
3374 return a DN for a wellknown GUID
3376 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3377 struct ldb_dn *nc_root, const char *wk_guid,
3378 struct ldb_dn **wkguid_dn)
3380 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3381 const char *attrs[] = { NULL };
3382 int ret;
3383 struct ldb_dn *dn;
3384 struct ldb_result *res;
3386 /* construct the magic WKGUID DN */
3387 dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3388 wk_guid, ldb_dn_get_linearized(nc_root));
3389 if (!wkguid_dn) {
3390 talloc_free(tmp_ctx);
3391 return ldb_operr(samdb);
3394 ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
3395 DSDB_SEARCH_SHOW_DELETED |
3396 DSDB_SEARCH_SHOW_RECYCLED);
3397 if (ret != LDB_SUCCESS) {
3398 talloc_free(tmp_ctx);
3399 return ret;
3402 (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3403 talloc_free(tmp_ctx);
3404 return LDB_SUCCESS;
3408 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3410 return ldb_dn_compare(*dn1, *dn2);
3414 find a NC root given a DN within the NC
3416 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3417 struct ldb_dn **nc_root)
3419 const char *root_attrs[] = { "namingContexts", NULL };
3420 TALLOC_CTX *tmp_ctx;
3421 int ret;
3422 struct ldb_message_element *el;
3423 struct ldb_result *root_res;
3424 unsigned int i;
3425 struct ldb_dn **nc_dns;
3427 tmp_ctx = talloc_new(samdb);
3428 if (tmp_ctx == NULL) {
3429 return ldb_oom(samdb);
3432 ret = ldb_search(samdb, tmp_ctx, &root_res,
3433 ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3434 if (ret != LDB_SUCCESS) {
3435 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3436 talloc_free(tmp_ctx);
3437 return ret;
3440 el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3441 if ((el == NULL) || (el->num_values < 3)) {
3442 struct ldb_message *tmp_msg;
3444 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list."));
3446 /* This generates a temporary list of NCs in order to let the
3447 * provisioning work. */
3448 tmp_msg = ldb_msg_new(tmp_ctx);
3449 if (tmp_msg == NULL) {
3450 talloc_free(tmp_ctx);
3451 return ldb_oom(samdb);
3453 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3454 ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
3455 if (ret != LDB_SUCCESS) {
3456 talloc_free(tmp_ctx);
3457 return ret;
3459 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3460 ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
3461 if (ret != LDB_SUCCESS) {
3462 talloc_free(tmp_ctx);
3463 return ret;
3465 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3466 ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
3467 if (ret != LDB_SUCCESS) {
3468 talloc_free(tmp_ctx);
3469 return ret;
3471 el = &tmp_msg->elements[0];
3474 nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3475 if (!nc_dns) {
3476 talloc_free(tmp_ctx);
3477 return ldb_oom(samdb);
3480 for (i=0; i<el->num_values; i++) {
3481 nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3482 if (nc_dns[i] == NULL) {
3483 talloc_free(tmp_ctx);
3484 return ldb_operr(samdb);
3488 TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3490 for (i=0; i<el->num_values; i++) {
3491 if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3492 (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3493 talloc_free(tmp_ctx);
3494 return LDB_SUCCESS;
3498 talloc_free(tmp_ctx);
3499 return LDB_ERR_NO_SUCH_OBJECT;
3504 find the deleted objects DN for any object, by looking for the NC
3505 root, then looking up the wellknown GUID
3507 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3508 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3509 struct ldb_dn **do_dn)
3511 struct ldb_dn *nc_root;
3512 int ret;
3514 ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3515 if (ret != LDB_SUCCESS) {
3516 return ret;
3519 ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3520 talloc_free(nc_root);
3521 return ret;
3525 return the tombstoneLifetime, in days
3527 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3529 struct ldb_dn *dn;
3530 dn = ldb_get_config_basedn(ldb);
3531 if (!dn) {
3532 return LDB_ERR_NO_SUCH_OBJECT;
3534 dn = ldb_dn_copy(ldb, dn);
3535 if (!dn) {
3536 return ldb_operr(ldb);
3538 /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3539 be a wellknown GUID for this */
3540 if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3541 talloc_free(dn);
3542 return ldb_operr(ldb);
3545 *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3546 talloc_free(dn);
3547 return LDB_SUCCESS;
3551 compare a ldb_val to a string case insensitively
3553 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3555 size_t len = strlen(s);
3556 int ret;
3557 if (len > v->length) return 1;
3558 ret = strncasecmp(s, (const char *)v->data, v->length);
3559 if (ret != 0) return ret;
3560 if (v->length > len && v->data[len] != 0) {
3561 return -1;
3563 return 0;
3568 load the UDV for a partition in v2 format
3569 The list is returned sorted, and with our local cursor added
3571 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3572 struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3574 static const char *attrs[] = { "replUpToDateVector", NULL };
3575 struct ldb_result *r;
3576 const struct ldb_val *ouv_value;
3577 unsigned int i;
3578 int ret;
3579 uint64_t highest_usn = 0;
3580 const struct GUID *our_invocation_id;
3581 static const struct timeval tv1970;
3582 NTTIME nt1970 = timeval_to_nttime(&tv1970);
3584 ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3585 if (ret != LDB_SUCCESS) {
3586 return ret;
3589 ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3590 if (ouv_value) {
3591 enum ndr_err_code ndr_err;
3592 struct replUpToDateVectorBlob ouv;
3594 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
3595 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3596 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3597 talloc_free(r);
3598 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3600 if (ouv.version != 2) {
3601 /* we always store as version 2, and
3602 * replUpToDateVector is not replicated
3604 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3607 *count = ouv.ctr.ctr2.count;
3608 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3609 } else {
3610 *count = 0;
3611 *cursors = NULL;
3614 talloc_free(r);
3616 our_invocation_id = samdb_ntds_invocation_id(samdb);
3617 if (!our_invocation_id) {
3618 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3619 talloc_free(*cursors);
3620 return ldb_operr(samdb);
3623 ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
3624 if (ret != LDB_SUCCESS) {
3625 /* nothing to add - this can happen after a vampire */
3626 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3627 return LDB_SUCCESS;
3630 for (i=0; i<*count; i++) {
3631 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3632 (*cursors)[i].highest_usn = highest_usn;
3633 (*cursors)[i].last_sync_success = nt1970;
3634 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3635 return LDB_SUCCESS;
3639 (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3640 if (! *cursors) {
3641 return ldb_oom(samdb);
3644 (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3645 (*cursors)[*count].highest_usn = highest_usn;
3646 (*cursors)[*count].last_sync_success = nt1970;
3647 (*count)++;
3649 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3651 return LDB_SUCCESS;
3655 load the UDV for a partition in version 1 format
3656 The list is returned sorted, and with our local cursor added
3658 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3659 struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3661 struct drsuapi_DsReplicaCursor2 *v2;
3662 uint32_t i;
3663 int ret;
3665 ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3666 if (ret != LDB_SUCCESS) {
3667 return ret;
3670 if (*count == 0) {
3671 talloc_free(v2);
3672 *cursors = NULL;
3673 return LDB_SUCCESS;
3676 *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3677 if (*cursors == NULL) {
3678 talloc_free(v2);
3679 return ldb_oom(samdb);
3682 for (i=0; i<*count; i++) {
3683 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3684 (*cursors)[i].highest_usn = v2[i].highest_usn;
3686 talloc_free(v2);
3687 return LDB_SUCCESS;
3691 add a set of controls to a ldb_request structure based on a set of
3692 flags. See util.h for a list of available flags
3694 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3696 int ret;
3697 if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3698 struct ldb_search_options_control *options;
3699 /* Using the phantom root control allows us to search all partitions */
3700 options = talloc(req, struct ldb_search_options_control);
3701 if (options == NULL) {
3702 return LDB_ERR_OPERATIONS_ERROR;
3704 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3706 ret = ldb_request_add_control(req,
3707 LDB_CONTROL_SEARCH_OPTIONS_OID,
3708 true, options);
3709 if (ret != LDB_SUCCESS) {
3710 return ret;
3714 if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
3715 ret = ldb_request_add_control(req,
3716 DSDB_CONTROL_NO_GLOBAL_CATALOG,
3717 false, NULL);
3718 if (ret != LDB_SUCCESS) {
3719 return ret;
3723 if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3724 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3725 if (ret != LDB_SUCCESS) {
3726 return ret;
3730 if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
3731 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
3732 if (ret != LDB_SUCCESS) {
3733 return ret;
3737 if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3738 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
3739 if (ret != LDB_SUCCESS) {
3740 return ret;
3744 if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3745 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3746 if (!extended_ctrl) {
3747 return LDB_ERR_OPERATIONS_ERROR;
3749 extended_ctrl->type = 1;
3751 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3752 if (ret != LDB_SUCCESS) {
3753 return ret;
3757 if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3758 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3759 if (ret != LDB_SUCCESS) {
3760 return ret;
3764 if (dsdb_flags & DSDB_MODIFY_RELAX) {
3765 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3766 if (ret != LDB_SUCCESS) {
3767 return ret;
3771 if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3772 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3773 if (ret != LDB_SUCCESS) {
3774 return ret;
3778 if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3779 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3780 if (ret != LDB_SUCCESS) {
3781 return ret;
3785 if (dsdb_flags & DSDB_TREE_DELETE) {
3786 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
3787 if (ret != LDB_SUCCESS) {
3788 return ret;
3792 if (dsdb_flags & DSDB_PROVISION) {
3793 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
3794 if (ret != LDB_SUCCESS) {
3795 return ret;
3799 /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
3800 if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
3801 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
3802 if (ret != LDB_SUCCESS) {
3803 return ret;
3807 if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
3809 * This must not be critical, as it will only be
3810 * handled (and need to be handled) if the other
3811 * attributes in the request bring password_hash into
3812 * action
3814 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
3815 if (ret != LDB_SUCCESS) {
3816 return ret;
3820 if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
3821 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
3822 if (ret != LDB_SUCCESS) {
3823 return ret;
3827 return LDB_SUCCESS;
3831 an add with a set of controls
3833 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
3834 uint32_t dsdb_flags)
3836 struct ldb_request *req;
3837 int ret;
3839 ret = ldb_build_add_req(&req, ldb, ldb,
3840 message,
3841 NULL,
3842 NULL,
3843 ldb_op_default_callback,
3844 NULL);
3846 if (ret != LDB_SUCCESS) return ret;
3848 ret = dsdb_request_add_controls(req, dsdb_flags);
3849 if (ret != LDB_SUCCESS) {
3850 talloc_free(req);
3851 return ret;
3854 ret = dsdb_autotransaction_request(ldb, req);
3856 talloc_free(req);
3857 return ret;
3861 a modify with a set of controls
3863 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3864 uint32_t dsdb_flags)
3866 struct ldb_request *req;
3867 int ret;
3869 ret = ldb_build_mod_req(&req, ldb, ldb,
3870 message,
3871 NULL,
3872 NULL,
3873 ldb_op_default_callback,
3874 NULL);
3876 if (ret != LDB_SUCCESS) return ret;
3878 ret = dsdb_request_add_controls(req, dsdb_flags);
3879 if (ret != LDB_SUCCESS) {
3880 talloc_free(req);
3881 return ret;
3884 ret = dsdb_autotransaction_request(ldb, req);
3886 talloc_free(req);
3887 return ret;
3891 a delete with a set of flags
3893 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
3894 uint32_t dsdb_flags)
3896 struct ldb_request *req;
3897 int ret;
3899 ret = ldb_build_del_req(&req, ldb, ldb,
3901 NULL,
3902 NULL,
3903 ldb_op_default_callback,
3904 NULL);
3906 if (ret != LDB_SUCCESS) return ret;
3908 ret = dsdb_request_add_controls(req, dsdb_flags);
3909 if (ret != LDB_SUCCESS) {
3910 talloc_free(req);
3911 return ret;
3914 ret = dsdb_autotransaction_request(ldb, req);
3916 talloc_free(req);
3917 return ret;
3921 like dsdb_modify() but set all the element flags to
3922 LDB_FLAG_MOD_REPLACE
3924 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3926 unsigned int i;
3928 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3929 for (i=0;i<msg->num_elements;i++) {
3930 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3933 return dsdb_modify(ldb, msg, dsdb_flags);
3938 search for attrs on one DN, allowing for dsdb_flags controls
3940 int dsdb_search_dn(struct ldb_context *ldb,
3941 TALLOC_CTX *mem_ctx,
3942 struct ldb_result **_result,
3943 struct ldb_dn *basedn,
3944 const char * const *attrs,
3945 uint32_t dsdb_flags)
3947 int ret;
3948 struct ldb_request *req;
3949 struct ldb_result *res;
3951 res = talloc_zero(mem_ctx, struct ldb_result);
3952 if (!res) {
3953 return ldb_oom(ldb);
3956 ret = ldb_build_search_req(&req, ldb, res,
3957 basedn,
3958 LDB_SCOPE_BASE,
3959 NULL,
3960 attrs,
3961 NULL,
3962 res,
3963 ldb_search_default_callback,
3964 NULL);
3965 if (ret != LDB_SUCCESS) {
3966 talloc_free(res);
3967 return ret;
3970 ret = dsdb_request_add_controls(req, dsdb_flags);
3971 if (ret != LDB_SUCCESS) {
3972 talloc_free(res);
3973 return ret;
3976 ret = ldb_request(ldb, req);
3977 if (ret == LDB_SUCCESS) {
3978 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3981 talloc_free(req);
3982 if (ret != LDB_SUCCESS) {
3983 talloc_free(res);
3984 return ret;
3987 *_result = res;
3988 return LDB_SUCCESS;
3992 search for attrs on one DN, by the GUID of the DN, allowing for
3993 dsdb_flags controls
3995 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
3996 TALLOC_CTX *mem_ctx,
3997 struct ldb_result **_result,
3998 const struct GUID *guid,
3999 const char * const *attrs,
4000 uint32_t dsdb_flags)
4002 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4003 struct ldb_dn *dn;
4004 int ret;
4006 dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
4007 if (dn == NULL) {
4008 talloc_free(tmp_ctx);
4009 return ldb_oom(ldb);
4012 ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
4013 talloc_free(tmp_ctx);
4014 return ret;
4018 general search with dsdb_flags for controls
4020 int dsdb_search(struct ldb_context *ldb,
4021 TALLOC_CTX *mem_ctx,
4022 struct ldb_result **_result,
4023 struct ldb_dn *basedn,
4024 enum ldb_scope scope,
4025 const char * const *attrs,
4026 uint32_t dsdb_flags,
4027 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4029 int ret;
4030 struct ldb_request *req;
4031 struct ldb_result *res;
4032 va_list ap;
4033 char *expression = NULL;
4034 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4036 /* cross-partitions searches with a basedn break multi-domain support */
4037 SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
4039 res = talloc_zero(tmp_ctx, struct ldb_result);
4040 if (!res) {
4041 talloc_free(tmp_ctx);
4042 return ldb_oom(ldb);
4045 if (exp_fmt) {
4046 va_start(ap, exp_fmt);
4047 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4048 va_end(ap);
4050 if (!expression) {
4051 talloc_free(tmp_ctx);
4052 return ldb_oom(ldb);
4056 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
4057 basedn,
4058 scope,
4059 expression,
4060 attrs,
4061 NULL,
4062 res,
4063 ldb_search_default_callback,
4064 NULL);
4065 if (ret != LDB_SUCCESS) {
4066 talloc_free(tmp_ctx);
4067 return ret;
4070 ret = dsdb_request_add_controls(req, dsdb_flags);
4071 if (ret != LDB_SUCCESS) {
4072 talloc_free(tmp_ctx);
4073 ldb_reset_err_string(ldb);
4074 return ret;
4077 ret = ldb_request(ldb, req);
4078 if (ret == LDB_SUCCESS) {
4079 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4082 if (ret != LDB_SUCCESS) {
4083 talloc_free(tmp_ctx);
4084 return ret;
4087 if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
4088 if (res->count == 0) {
4089 talloc_free(tmp_ctx);
4090 ldb_reset_err_string(ldb);
4091 return LDB_ERR_NO_SUCH_OBJECT;
4093 if (res->count != 1) {
4094 talloc_free(tmp_ctx);
4095 ldb_reset_err_string(ldb);
4096 return LDB_ERR_CONSTRAINT_VIOLATION;
4100 *_result = talloc_steal(mem_ctx, res);
4101 talloc_free(tmp_ctx);
4103 return LDB_SUCCESS;
4108 general search with dsdb_flags for controls
4109 returns exactly 1 record or an error
4111 int dsdb_search_one(struct ldb_context *ldb,
4112 TALLOC_CTX *mem_ctx,
4113 struct ldb_message **msg,
4114 struct ldb_dn *basedn,
4115 enum ldb_scope scope,
4116 const char * const *attrs,
4117 uint32_t dsdb_flags,
4118 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4120 int ret;
4121 struct ldb_result *res;
4122 va_list ap;
4123 char *expression = NULL;
4124 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4126 dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4128 res = talloc_zero(tmp_ctx, struct ldb_result);
4129 if (!res) {
4130 talloc_free(tmp_ctx);
4131 return ldb_oom(ldb);
4134 if (exp_fmt) {
4135 va_start(ap, exp_fmt);
4136 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4137 va_end(ap);
4139 if (!expression) {
4140 talloc_free(tmp_ctx);
4141 return ldb_oom(ldb);
4143 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4144 dsdb_flags, "%s", expression);
4145 } else {
4146 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4147 dsdb_flags, NULL);
4150 if (ret != LDB_SUCCESS) {
4151 talloc_free(tmp_ctx);
4152 return ret;
4155 *msg = talloc_steal(mem_ctx, res->msgs[0]);
4156 talloc_free(tmp_ctx);
4158 return LDB_SUCCESS;
4161 /* returns back the forest DNS name */
4162 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4164 const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4165 ldb_get_root_basedn(ldb));
4166 char *p;
4168 if (forest_name == NULL) {
4169 return NULL;
4172 p = strchr(forest_name, '/');
4173 if (p) {
4174 *p = '\0';
4177 return forest_name;
4180 /* returns back the default domain DNS name */
4181 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4183 const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4184 ldb_get_default_basedn(ldb));
4185 char *p;
4187 if (domain_name == NULL) {
4188 return NULL;
4191 p = strchr(domain_name, '/');
4192 if (p) {
4193 *p = '\0';
4196 return domain_name;
4200 validate that an DSA GUID belongs to the specified user sid.
4201 The user SID must be a domain controller account (either RODC or
4202 RWDC)
4204 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4205 const struct GUID *dsa_guid,
4206 const struct dom_sid *sid)
4208 /* strategy:
4209 - find DN of record with the DSA GUID in the
4210 configuration partition (objectGUID)
4211 - remove "NTDS Settings" component from DN
4212 - do a base search on that DN for serverReference with
4213 extended-dn enabled
4214 - extract objectSid from resulting serverReference
4215 attribute
4216 - check this sid matches the sid argument
4218 struct ldb_dn *config_dn;
4219 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4220 struct ldb_message *msg;
4221 const char *attrs1[] = { NULL };
4222 const char *attrs2[] = { "serverReference", NULL };
4223 int ret;
4224 struct ldb_dn *dn, *account_dn;
4225 struct dom_sid sid2;
4226 NTSTATUS status;
4228 config_dn = ldb_get_config_basedn(ldb);
4230 ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4231 attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4232 if (ret != LDB_SUCCESS) {
4233 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4234 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4235 talloc_free(tmp_ctx);
4236 return ldb_operr(ldb);
4238 dn = msg->dn;
4240 if (!ldb_dn_remove_child_components(dn, 1)) {
4241 talloc_free(tmp_ctx);
4242 return ldb_operr(ldb);
4245 ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4246 attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4247 "(objectClass=server)");
4248 if (ret != LDB_SUCCESS) {
4249 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4250 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4251 talloc_free(tmp_ctx);
4252 return ldb_operr(ldb);
4255 account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4256 if (account_dn == NULL) {
4257 DEBUG(1,(__location__ ": Failed to find account_dn for DSA with objectGUID %s, sid %s\n",
4258 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4259 talloc_free(tmp_ctx);
4260 return ldb_operr(ldb);
4263 status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4264 if (!NT_STATUS_IS_OK(status)) {
4265 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4266 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4267 talloc_free(tmp_ctx);
4268 return ldb_operr(ldb);
4271 if (!dom_sid_equal(sid, &sid2)) {
4272 /* someone is trying to spoof another account */
4273 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4274 GUID_string(tmp_ctx, dsa_guid),
4275 dom_sid_string(tmp_ctx, sid),
4276 dom_sid_string(tmp_ctx, &sid2)));
4277 talloc_free(tmp_ctx);
4278 return ldb_operr(ldb);
4281 talloc_free(tmp_ctx);
4282 return LDB_SUCCESS;
4285 static const char * const secret_attributes[] = {
4286 DSDB_SECRET_ATTRIBUTES,
4287 NULL
4291 check if the attribute belongs to the RODC filtered attribute set
4292 Note that attributes that are in the filtered attribute set are the
4293 ones that _are_ always sent to a RODC
4295 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4297 /* they never get secret attributes */
4298 if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4299 return false;
4302 /* they do get non-secret critical attributes */
4303 if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4304 return true;
4307 /* they do get non-secret attributes marked as being in the FAS */
4308 if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4309 return true;
4312 /* other attributes are denied */
4313 return false;
4316 /* return fsmo role dn and role owner dn for a particular role*/
4317 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4318 struct ldb_context *ldb,
4319 uint32_t role,
4320 struct ldb_dn **fsmo_role_dn,
4321 struct ldb_dn **role_owner_dn)
4323 int ret;
4324 switch (role) {
4325 case DREPL_NAMING_MASTER:
4326 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4327 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4328 if (ret != LDB_SUCCESS) {
4329 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4330 ldb_errstring(ldb)));
4331 talloc_free(tmp_ctx);
4332 return WERR_DS_DRA_INTERNAL_ERROR;
4334 break;
4335 case DREPL_INFRASTRUCTURE_MASTER:
4336 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4337 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4338 if (ret != LDB_SUCCESS) {
4339 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4340 ldb_errstring(ldb)));
4341 talloc_free(tmp_ctx);
4342 return WERR_DS_DRA_INTERNAL_ERROR;
4344 break;
4345 case DREPL_RID_MASTER:
4346 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
4347 if (ret != LDB_SUCCESS) {
4348 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
4349 talloc_free(tmp_ctx);
4350 return WERR_DS_DRA_INTERNAL_ERROR;
4353 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4354 if (ret != LDB_SUCCESS) {
4355 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
4356 ldb_errstring(ldb)));
4357 talloc_free(tmp_ctx);
4358 return WERR_DS_DRA_INTERNAL_ERROR;
4360 break;
4361 case DREPL_SCHEMA_MASTER:
4362 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
4363 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4364 if (ret != LDB_SUCCESS) {
4365 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4366 ldb_errstring(ldb)));
4367 talloc_free(tmp_ctx);
4368 return WERR_DS_DRA_INTERNAL_ERROR;
4370 break;
4371 case DREPL_PDC_MASTER:
4372 *fsmo_role_dn = ldb_get_default_basedn(ldb);
4373 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4374 if (ret != LDB_SUCCESS) {
4375 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
4376 ldb_errstring(ldb)));
4377 talloc_free(tmp_ctx);
4378 return WERR_DS_DRA_INTERNAL_ERROR;
4380 break;
4381 default:
4382 return WERR_DS_DRA_INTERNAL_ERROR;
4384 return WERR_OK;
4387 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
4388 TALLOC_CTX *mem_ctx,
4389 struct ldb_dn *server_dn)
4391 int ldb_ret;
4392 struct ldb_result *res = NULL;
4393 const char * const attrs[] = { "dNSHostName", NULL};
4395 ldb_ret = ldb_search(ldb, mem_ctx, &res,
4396 server_dn,
4397 LDB_SCOPE_BASE,
4398 attrs, NULL);
4399 if (ldb_ret != LDB_SUCCESS) {
4400 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
4401 ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
4402 return NULL;
4405 return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
4409 returns true if an attribute is in the filter,
4410 false otherwise, provided that attribute value is provided with the expression
4412 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
4413 const char *attr)
4415 unsigned int i;
4416 switch (tree->operation) {
4417 case LDB_OP_AND:
4418 case LDB_OP_OR:
4419 for (i=0;i<tree->u.list.num_elements;i++) {
4420 if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
4421 attr))
4422 return true;
4424 return false;
4425 case LDB_OP_NOT:
4426 return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
4427 case LDB_OP_EQUALITY:
4428 case LDB_OP_GREATER:
4429 case LDB_OP_LESS:
4430 case LDB_OP_APPROX:
4431 if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
4432 return true;
4434 return false;
4435 case LDB_OP_SUBSTRING:
4436 if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
4437 return true;
4439 return false;
4440 case LDB_OP_PRESENT:
4441 /* (attrname=*) is not filtered out */
4442 return false;
4443 case LDB_OP_EXTENDED:
4444 if (tree->u.extended.attr &&
4445 ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
4446 return true;
4448 return false;
4450 return false;
4453 bool is_attr_in_list(const char * const * attrs, const char *attr)
4455 unsigned int i;
4457 for (i = 0; attrs[i]; i++) {
4458 if (ldb_attr_cmp(attrs[i], attr) == 0)
4459 return true;
4462 return false;
4467 map an ldb error code to an approximate NTSTATUS code
4469 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
4471 switch (err) {
4472 case LDB_SUCCESS:
4473 return NT_STATUS_OK;
4475 case LDB_ERR_PROTOCOL_ERROR:
4476 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
4478 case LDB_ERR_TIME_LIMIT_EXCEEDED:
4479 return NT_STATUS_IO_TIMEOUT;
4481 case LDB_ERR_SIZE_LIMIT_EXCEEDED:
4482 return NT_STATUS_BUFFER_TOO_SMALL;
4484 case LDB_ERR_COMPARE_FALSE:
4485 case LDB_ERR_COMPARE_TRUE:
4486 return NT_STATUS_REVISION_MISMATCH;
4488 case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
4489 return NT_STATUS_NOT_SUPPORTED;
4491 case LDB_ERR_STRONG_AUTH_REQUIRED:
4492 case LDB_ERR_CONFIDENTIALITY_REQUIRED:
4493 case LDB_ERR_SASL_BIND_IN_PROGRESS:
4494 case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
4495 case LDB_ERR_INVALID_CREDENTIALS:
4496 case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
4497 case LDB_ERR_UNWILLING_TO_PERFORM:
4498 return NT_STATUS_ACCESS_DENIED;
4500 case LDB_ERR_NO_SUCH_OBJECT:
4501 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4503 case LDB_ERR_REFERRAL:
4504 case LDB_ERR_NO_SUCH_ATTRIBUTE:
4505 return NT_STATUS_NOT_FOUND;
4507 case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
4508 return NT_STATUS_NOT_SUPPORTED;
4510 case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
4511 return NT_STATUS_BUFFER_TOO_SMALL;
4513 case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
4514 case LDB_ERR_INAPPROPRIATE_MATCHING:
4515 case LDB_ERR_CONSTRAINT_VIOLATION:
4516 case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
4517 case LDB_ERR_INVALID_DN_SYNTAX:
4518 case LDB_ERR_NAMING_VIOLATION:
4519 case LDB_ERR_OBJECT_CLASS_VIOLATION:
4520 case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
4521 case LDB_ERR_NOT_ALLOWED_ON_RDN:
4522 return NT_STATUS_INVALID_PARAMETER;
4524 case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
4525 case LDB_ERR_ENTRY_ALREADY_EXISTS:
4526 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
4528 case LDB_ERR_BUSY:
4529 return NT_STATUS_NETWORK_BUSY;
4531 case LDB_ERR_ALIAS_PROBLEM:
4532 case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
4533 case LDB_ERR_UNAVAILABLE:
4534 case LDB_ERR_LOOP_DETECT:
4535 case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
4536 case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
4537 case LDB_ERR_OTHER:
4538 case LDB_ERR_OPERATIONS_ERROR:
4539 break;
4541 return NT_STATUS_UNSUCCESSFUL;
4546 create a new naming context that will hold a partial replica
4548 int dsdb_create_partial_replica_NC(struct ldb_context *ldb, struct ldb_dn *dn)
4550 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4551 struct ldb_message *msg;
4552 int ret;
4554 msg = ldb_msg_new(tmp_ctx);
4555 if (msg == NULL) {
4556 talloc_free(tmp_ctx);
4557 return ldb_oom(ldb);
4560 msg->dn = dn;
4561 ret = ldb_msg_add_string(msg, "objectClass", "top");
4562 if (ret != LDB_SUCCESS) {
4563 talloc_free(tmp_ctx);
4564 return ldb_oom(ldb);
4567 /* [MS-DRSR] implies that we should only add the 'top'
4568 * objectclass, but that would cause lots of problems with our
4569 * objectclass code as top is not structural, so we add
4570 * 'domainDNS' as well to keep things sane. We're expecting
4571 * this new NC to be of objectclass domainDNS after
4572 * replication anyway
4574 ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
4575 if (ret != LDB_SUCCESS) {
4576 talloc_free(tmp_ctx);
4577 return ldb_oom(ldb);
4580 ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
4581 INSTANCE_TYPE_IS_NC_HEAD|
4582 INSTANCE_TYPE_NC_ABOVE|
4583 INSTANCE_TYPE_UNINSTANT);
4584 if (ret != LDB_SUCCESS) {
4585 talloc_free(tmp_ctx);
4586 return ldb_oom(ldb);
4589 ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
4590 if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
4591 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
4592 ldb_dn_get_linearized(dn),
4593 ldb_errstring(ldb), ldb_strerror(ret)));
4594 talloc_free(tmp_ctx);
4595 return ret;
4598 DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
4600 talloc_free(tmp_ctx);
4601 return LDB_SUCCESS;
4605 build a GUID from a string
4607 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
4609 NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
4610 uint32_t time_low;
4611 uint32_t time_mid, time_hi_and_version;
4612 uint32_t clock_seq[2];
4613 uint32_t node[6];
4614 int i;
4616 if (s == NULL) {
4617 return NT_STATUS_INVALID_PARAMETER;
4620 if (11 == sscanf(s, "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
4621 &time_low, &time_mid, &time_hi_and_version,
4622 &clock_seq[0], &clock_seq[1],
4623 &node[0], &node[1], &node[2], &node[3], &node[4], &node[5])) {
4624 status = NT_STATUS_OK;
4627 if (!NT_STATUS_IS_OK(status)) {
4628 return status;
4631 guid->time_low = time_low;
4632 guid->time_mid = time_mid;
4633 guid->time_hi_and_version = time_hi_and_version;
4634 guid->clock_seq[0] = clock_seq[0];
4635 guid->clock_seq[1] = clock_seq[1];
4636 for (i=0;i<6;i++) {
4637 guid->node[i] = node[i];
4640 return NT_STATUS_OK;
4643 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
4645 return talloc_asprintf(mem_ctx,
4646 "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
4647 guid->time_low, guid->time_mid,
4648 guid->time_hi_and_version,
4649 guid->clock_seq[0],
4650 guid->clock_seq[1],
4651 guid->node[0], guid->node[1],
4652 guid->node[2], guid->node[3],
4653 guid->node[4], guid->node[5]);
4657 * Prepare an update to the badPwdCount and associated attributes.
4659 * This requires that the user_msg have (if present):
4660 * - objectSid
4661 * - badPasswordTime
4662 * - badPwdCount
4664 * This also requires that the domain_msg have (if present):
4665 * - pwdProperties
4666 * - lockoutThreshold
4667 * - lockOutObservationWindow
4669 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
4670 struct ldb_context *sam_ctx,
4671 struct ldb_message *user_msg,
4672 struct ldb_message *domain_msg,
4673 struct ldb_message **_mod_msg)
4675 int i, ret, badPwdCount;
4676 int64_t lockoutThreshold, lockOutObservationWindow, badPasswordTime;
4677 struct dom_sid *sid;
4678 struct timeval tv_now = timeval_current();
4679 NTTIME now = timeval_to_nttime(&tv_now);
4680 NTSTATUS status;
4681 uint32_t pwdProperties, rid = 0;
4682 struct ldb_message *mod_msg;
4684 sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
4686 pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
4687 "pwdProperties", -1);
4688 if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
4689 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
4690 if (!NT_STATUS_IS_OK(status)) {
4692 * This can't happen anyway, but always try
4693 * and update the badPwdCount on failure
4695 rid = 0;
4698 TALLOC_FREE(sid);
4701 * Work out if we are doing password lockout on the domain.
4702 * Also, the built in administrator account is exempt:
4703 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
4705 lockoutThreshold = ldb_msg_find_attr_as_int(domain_msg,
4706 "lockoutThreshold", 0);
4707 if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
4708 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
4709 ldb_dn_get_linearized(user_msg->dn)));
4710 return NT_STATUS_OK;
4713 lockOutObservationWindow = ldb_msg_find_attr_as_int64(domain_msg,
4714 "lockOutObservationWindow", 0);
4716 badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
4718 mod_msg = ldb_msg_new(mem_ctx);
4719 if (mod_msg == NULL) {
4720 return NT_STATUS_NO_MEMORY;
4722 mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
4723 if (mod_msg->dn == NULL) {
4724 TALLOC_FREE(mod_msg);
4725 return NT_STATUS_NO_MEMORY;
4728 if (badPasswordTime - lockOutObservationWindow >= now) {
4729 badPwdCount = ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
4730 } else {
4731 badPwdCount = 0;
4734 badPwdCount++;
4736 ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
4737 if (ret != LDB_SUCCESS) {
4738 TALLOC_FREE(mod_msg);
4739 return NT_STATUS_NO_MEMORY;
4741 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
4742 if (ret != LDB_SUCCESS) {
4743 TALLOC_FREE(mod_msg);
4744 return NT_STATUS_NO_MEMORY;
4747 if (badPwdCount >= lockoutThreshold) {
4748 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
4749 if (ret != LDB_SUCCESS) {
4750 TALLOC_FREE(mod_msg);
4751 return NT_STATUS_NO_MEMORY;
4753 DEBUG(5, ("Locked out user %s after %d wrong passwords\n",
4754 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
4755 } else {
4756 DEBUG(5, ("Updated badPwdCount on %s after %d wrong passwords\n",
4757 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
4760 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
4761 for (i=0; i< mod_msg->num_elements; i++) {
4762 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
4765 *_mod_msg = mod_msg;
4766 return NT_STATUS_OK;