s4:dsdb/samldb: add DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID when defaulting pwdLas...
[Samba.git] / source4 / dsdb / common / util.c
blobb27c73bb9be137d9459d156e41c993d4cc5c9fae
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_parse(v->data, v->length, 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 NTSTATUS samdb_result_parameters(TALLOC_CTX *mem_ctx,
712 struct ldb_message *msg,
713 const char *attr,
714 struct lsa_BinaryString *s)
716 int i;
717 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
719 ZERO_STRUCTP(s);
721 if (!val) {
722 return NT_STATUS_OK;
725 if ((val->length % 2) != 0) {
727 * If the on-disk data is not even in length, we know
728 * it is corrupt, and can not be safely pushed. We
729 * would either truncate, send either a un-initilaised
730 * byte or send a forced zero byte
732 return NT_STATUS_INTERNAL_DB_CORRUPTION;
735 s->array = talloc_array(mem_ctx, uint16_t, val->length/2);
736 if (!s->array) {
737 return NT_STATUS_NO_MEMORY;
739 s->length = s->size = val->length;
741 /* The on-disk format is the 'network' format, being UTF16LE (sort of) */
742 for (i = 0; i < s->length / 2; i++) {
743 s->array[i] = SVAL(val->data, i * 2);
746 return NT_STATUS_OK;
749 /* Find an attribute, with a particular value */
751 /* The current callers of this function expect a very specific
752 * behaviour: In particular, objectClass subclass equivilance is not
753 * wanted. This means that we should not lookup the schema for the
754 * comparison function */
755 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
756 const struct ldb_message *msg,
757 const char *name, const char *value)
759 unsigned int i;
760 struct ldb_message_element *el = ldb_msg_find_element(msg, name);
762 if (!el) {
763 return NULL;
766 for (i=0;i<el->num_values;i++) {
767 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
768 return el;
772 return NULL;
775 static int samdb_find_or_add_attribute_ex(struct ldb_context *ldb,
776 struct ldb_message *msg,
777 const char *name,
778 const char *set_value,
779 bool *added)
781 int ret;
782 struct ldb_message_element *el;
784 el = ldb_msg_find_element(msg, name);
785 if (el) {
786 if (added != NULL) {
787 *added = false;
790 return LDB_SUCCESS;
793 ret = ldb_msg_add_string(msg, name, set_value);
794 if (ret != LDB_SUCCESS) {
795 return ret;
797 msg->elements[msg->num_elements - 1].flags = LDB_FLAG_MOD_ADD;
798 if (added != NULL) {
799 *added = true;
801 return LDB_SUCCESS;
804 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
806 return samdb_find_or_add_attribute_ex(ldb, msg, name, set_value, NULL);
810 add a dom_sid element to a message
812 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
813 const char *attr_name, const struct dom_sid *sid)
815 struct ldb_val v;
816 enum ndr_err_code ndr_err;
818 ndr_err = ndr_push_struct_blob(&v, mem_ctx,
819 sid,
820 (ndr_push_flags_fn_t)ndr_push_dom_sid);
821 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
822 return ldb_operr(sam_ldb);
824 return ldb_msg_add_value(msg, attr_name, &v, NULL);
829 add a delete element operation to a message
831 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
832 const char *attr_name)
834 /* we use an empty replace rather than a delete, as it allows for
835 dsdb_replace() to be used everywhere */
836 return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
840 add an add attribute value to a message or enhance an existing attribute
841 which has the same name and the add flag set.
843 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
844 struct ldb_message *msg, const char *attr_name,
845 const char *value)
847 struct ldb_message_element *el;
848 struct ldb_val val, *vals;
849 char *v;
850 unsigned int i;
851 bool found = false;
852 int ret;
854 v = talloc_strdup(mem_ctx, value);
855 if (v == NULL) {
856 return ldb_oom(sam_ldb);
859 val.data = (uint8_t *) v;
860 val.length = strlen(v);
862 if (val.length == 0) {
863 /* allow empty strings as non-existent attributes */
864 return LDB_SUCCESS;
867 for (i = 0; i < msg->num_elements; i++) {
868 el = &msg->elements[i];
869 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
870 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
871 found = true;
872 break;
875 if (!found) {
876 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
877 &el);
878 if (ret != LDB_SUCCESS) {
879 return ret;
883 vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
884 el->num_values + 1);
885 if (vals == NULL) {
886 return ldb_oom(sam_ldb);
888 el->values = vals;
889 el->values[el->num_values] = val;
890 ++(el->num_values);
892 return LDB_SUCCESS;
896 add a delete attribute value to a message or enhance an existing attribute
897 which has the same name and the delete flag set.
899 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
900 struct ldb_message *msg, const char *attr_name,
901 const char *value)
903 struct ldb_message_element *el;
904 struct ldb_val val, *vals;
905 char *v;
906 unsigned int i;
907 bool found = false;
908 int ret;
910 v = talloc_strdup(mem_ctx, value);
911 if (v == NULL) {
912 return ldb_oom(sam_ldb);
915 val.data = (uint8_t *) v;
916 val.length = strlen(v);
918 if (val.length == 0) {
919 /* allow empty strings as non-existent attributes */
920 return LDB_SUCCESS;
923 for (i = 0; i < msg->num_elements; i++) {
924 el = &msg->elements[i];
925 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
926 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
927 found = true;
928 break;
931 if (!found) {
932 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
933 &el);
934 if (ret != LDB_SUCCESS) {
935 return ret;
939 vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
940 el->num_values + 1);
941 if (vals == NULL) {
942 return ldb_oom(sam_ldb);
944 el->values = vals;
945 el->values[el->num_values] = val;
946 ++(el->num_values);
948 return LDB_SUCCESS;
952 add a int element to a message
954 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
955 const char *attr_name, int v)
957 const char *s = talloc_asprintf(mem_ctx, "%d", v);
958 if (s == NULL) {
959 return ldb_oom(sam_ldb);
961 return ldb_msg_add_string(msg, attr_name, s);
965 * Add an unsigned int element to a message
967 * The issue here is that we have not yet first cast to int32_t explicitly,
968 * before we cast to an signed int to printf() into the %d or cast to a
969 * int64_t before we then cast to a long long to printf into a %lld.
971 * There are *no* unsigned integers in Active Directory LDAP, even the RID
972 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
973 * (See the schema, and the syntax definitions in schema_syntax.c).
976 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
977 const char *attr_name, unsigned int v)
979 return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
983 add a (signed) int64_t element to a message
985 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
986 const char *attr_name, int64_t v)
988 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
989 if (s == NULL) {
990 return ldb_oom(sam_ldb);
992 return ldb_msg_add_string(msg, attr_name, s);
996 * Add an unsigned int64_t (uint64_t) element to a message
998 * The issue here is that we have not yet first cast to int32_t explicitly,
999 * before we cast to an signed int to printf() into the %d or cast to a
1000 * int64_t before we then cast to a long long to printf into a %lld.
1002 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1003 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1004 * (See the schema, and the syntax definitions in schema_syntax.c).
1007 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1008 const char *attr_name, uint64_t v)
1010 return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
1014 add a samr_Password element to a message
1016 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1017 const char *attr_name, const struct samr_Password *hash)
1019 struct ldb_val val;
1020 val.data = talloc_memdup(mem_ctx, hash->hash, 16);
1021 if (!val.data) {
1022 return ldb_oom(sam_ldb);
1024 val.length = 16;
1025 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1029 add a samr_Password array to a message
1031 int samdb_msg_add_hashes(struct ldb_context *ldb,
1032 TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1033 const char *attr_name, struct samr_Password *hashes,
1034 unsigned int count)
1036 struct ldb_val val;
1037 unsigned int i;
1038 val.data = talloc_array_size(mem_ctx, 16, count);
1039 val.length = count*16;
1040 if (!val.data) {
1041 return ldb_oom(ldb);
1043 for (i=0;i<count;i++) {
1044 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
1046 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1050 add a acct_flags element to a message
1052 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1053 const char *attr_name, uint32_t v)
1055 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1059 add a logon_hours element to a message
1061 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1062 const char *attr_name, struct samr_LogonHours *hours)
1064 struct ldb_val val;
1065 val.length = hours->units_per_week / 8;
1066 val.data = hours->bits;
1067 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1071 add a parameters element to a message
1073 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1074 const char *attr_name, struct lsa_BinaryString *parameters)
1076 int i;
1077 struct ldb_val val;
1078 if ((parameters->length % 2) != 0) {
1079 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
1082 val.data = talloc_array(mem_ctx, uint8_t, parameters->length);
1083 if (val.data == NULL) {
1084 return LDB_ERR_OPERATIONS_ERROR;
1086 val.length = parameters->length;
1087 for (i = 0; i < parameters->length / 2; i++) {
1089 * The on-disk format needs to be in the 'network'
1090 * format, parmeters->array is a uint16_t array of
1091 * length parameters->length / 2
1093 SSVAL(val.data, i * 2, parameters->array[i]);
1095 return ldb_msg_add_steal_value(msg, attr_name, &val);
1099 * Sets an unsigned int element in a message
1101 * The issue here is that we have not yet first cast to int32_t explicitly,
1102 * before we cast to an signed int to printf() into the %d or cast to a
1103 * int64_t before we then cast to a long long to printf into a %lld.
1105 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1106 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1107 * (See the schema, and the syntax definitions in schema_syntax.c).
1110 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1111 struct ldb_message *msg, const char *attr_name,
1112 unsigned int v)
1114 struct ldb_message_element *el;
1116 el = ldb_msg_find_element(msg, attr_name);
1117 if (el) {
1118 el->num_values = 0;
1120 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1124 * Handle ldb_request in transaction
1126 int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1127 struct ldb_request *req)
1129 int ret;
1131 ret = ldb_transaction_start(sam_ldb);
1132 if (ret != LDB_SUCCESS) {
1133 return ret;
1136 ret = ldb_request(sam_ldb, req);
1137 if (ret == LDB_SUCCESS) {
1138 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1141 if (ret == LDB_SUCCESS) {
1142 return ldb_transaction_commit(sam_ldb);
1144 ldb_transaction_cancel(sam_ldb);
1146 return ret;
1150 return a default security descriptor
1152 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1154 struct security_descriptor *sd;
1156 sd = security_descriptor_initialise(mem_ctx);
1158 return sd;
1161 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1163 struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1164 struct ldb_dn *aggregate_dn;
1165 if (!schema_dn) {
1166 return NULL;
1169 aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1170 if (!aggregate_dn) {
1171 return NULL;
1173 if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1174 return NULL;
1176 return aggregate_dn;
1179 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1181 struct ldb_dn *new_dn;
1183 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1184 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1185 talloc_free(new_dn);
1186 return NULL;
1188 return new_dn;
1191 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1193 struct ldb_dn *new_dn;
1195 new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1196 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1197 talloc_free(new_dn);
1198 return NULL;
1200 return new_dn;
1203 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1205 struct ldb_dn *new_dn;
1207 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1208 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1209 talloc_free(new_dn);
1210 return NULL;
1212 return new_dn;
1216 work out the domain sid for the current open ldb
1218 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1220 TALLOC_CTX *tmp_ctx;
1221 const struct dom_sid *domain_sid;
1222 const char *attrs[] = {
1223 "objectSid",
1224 NULL
1226 struct ldb_result *res;
1227 int ret;
1229 /* see if we have a cached copy */
1230 domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1231 if (domain_sid) {
1232 return domain_sid;
1235 tmp_ctx = talloc_new(ldb);
1236 if (tmp_ctx == NULL) {
1237 goto failed;
1240 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1242 if (ret != LDB_SUCCESS) {
1243 goto failed;
1246 if (res->count != 1) {
1247 goto failed;
1250 domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1251 if (domain_sid == NULL) {
1252 goto failed;
1255 /* cache the domain_sid in the ldb */
1256 if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1257 goto failed;
1260 talloc_steal(ldb, domain_sid);
1261 talloc_free(tmp_ctx);
1263 return domain_sid;
1265 failed:
1266 talloc_free(tmp_ctx);
1267 return NULL;
1271 get domain sid from cache
1273 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1275 return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1278 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1280 TALLOC_CTX *tmp_ctx;
1281 struct dom_sid *dom_sid_new;
1282 struct dom_sid *dom_sid_old;
1284 /* see if we have a cached copy */
1285 dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1286 "cache.domain_sid"), struct dom_sid);
1288 tmp_ctx = talloc_new(ldb);
1289 if (tmp_ctx == NULL) {
1290 goto failed;
1293 dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1294 if (!dom_sid_new) {
1295 goto failed;
1298 /* cache the domain_sid in the ldb */
1299 if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1300 goto failed;
1303 talloc_steal(ldb, dom_sid_new);
1304 talloc_free(tmp_ctx);
1305 talloc_free(dom_sid_old);
1307 return true;
1309 failed:
1310 DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1311 talloc_free(tmp_ctx);
1312 return false;
1315 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1317 TALLOC_CTX *tmp_ctx;
1318 struct ldb_dn *ntds_settings_dn_new;
1319 struct ldb_dn *ntds_settings_dn_old;
1321 /* see if we have a forced copy from provision */
1322 ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb,
1323 "forced.ntds_settings_dn"), struct ldb_dn);
1325 tmp_ctx = talloc_new(ldb);
1326 if (tmp_ctx == NULL) {
1327 goto failed;
1330 ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1331 if (!ntds_settings_dn_new) {
1332 goto failed;
1335 /* set the DN in the ldb to avoid lookups during provision */
1336 if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1337 goto failed;
1340 talloc_steal(ldb, ntds_settings_dn_new);
1341 talloc_free(tmp_ctx);
1342 talloc_free(ntds_settings_dn_old);
1344 return true;
1346 failed:
1347 DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1348 talloc_free(tmp_ctx);
1349 return false;
1353 work out the ntds settings dn for the current open ldb
1355 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1357 TALLOC_CTX *tmp_ctx;
1358 const char *root_attrs[] = { "dsServiceName", NULL };
1359 int ret;
1360 struct ldb_result *root_res;
1361 struct ldb_dn *settings_dn;
1363 /* see if we have a cached copy */
1364 settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1365 if (settings_dn) {
1366 return ldb_dn_copy(mem_ctx, settings_dn);
1369 tmp_ctx = talloc_new(mem_ctx);
1370 if (tmp_ctx == NULL) {
1371 goto failed;
1374 ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1375 if (ret != LDB_SUCCESS) {
1376 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1377 ldb_errstring(ldb)));
1378 goto failed;
1381 if (root_res->count != 1) {
1382 goto failed;
1385 settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1387 /* note that we do not cache the DN here, as that would mean
1388 * we could not handle server renames at runtime. Only
1389 * provision sets up forced.ntds_settings_dn */
1391 talloc_steal(mem_ctx, settings_dn);
1392 talloc_free(tmp_ctx);
1394 return settings_dn;
1396 failed:
1397 DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1398 talloc_free(tmp_ctx);
1399 return NULL;
1403 work out the ntds settings invocationId for the current open ldb
1405 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1407 TALLOC_CTX *tmp_ctx;
1408 const char *attrs[] = { "invocationId", NULL };
1409 int ret;
1410 struct ldb_result *res;
1411 struct GUID *invocation_id;
1413 /* see if we have a cached copy */
1414 invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1415 if (invocation_id) {
1416 SMB_ASSERT(!GUID_all_zero(invocation_id));
1417 return invocation_id;
1420 tmp_ctx = talloc_new(ldb);
1421 if (tmp_ctx == NULL) {
1422 goto failed;
1425 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1426 if (ret) {
1427 goto failed;
1430 if (res->count != 1) {
1431 goto failed;
1434 invocation_id = talloc(tmp_ctx, struct GUID);
1435 if (!invocation_id) {
1436 goto failed;
1439 *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1440 if (GUID_all_zero(invocation_id)) {
1441 if (ldb_msg_find_ldb_val(res->msgs[0], "invocationId")) {
1442 DEBUG(0, ("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1443 } else {
1444 DEBUG(0, ("Failed to find parse own NTDS Settings invocationId from the ldb!\n"));
1446 goto failed;
1449 /* cache the domain_sid in the ldb */
1450 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1451 goto failed;
1454 talloc_steal(ldb, invocation_id);
1455 talloc_free(tmp_ctx);
1457 return invocation_id;
1459 failed:
1460 DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1461 talloc_free(tmp_ctx);
1462 return NULL;
1465 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1467 TALLOC_CTX *tmp_ctx;
1468 struct GUID *invocation_id_new;
1469 struct GUID *invocation_id_old;
1471 /* see if we have a cached copy */
1472 invocation_id_old = (struct GUID *)ldb_get_opaque(ldb,
1473 "cache.invocation_id");
1475 tmp_ctx = talloc_new(ldb);
1476 if (tmp_ctx == NULL) {
1477 goto failed;
1480 invocation_id_new = talloc(tmp_ctx, struct GUID);
1481 if (!invocation_id_new) {
1482 goto failed;
1485 SMB_ASSERT(!GUID_all_zero(invocation_id_in));
1486 *invocation_id_new = *invocation_id_in;
1488 /* cache the domain_sid in the ldb */
1489 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1490 goto failed;
1493 talloc_steal(ldb, invocation_id_new);
1494 talloc_free(tmp_ctx);
1495 talloc_free(invocation_id_old);
1497 return true;
1499 failed:
1500 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1501 talloc_free(tmp_ctx);
1502 return false;
1506 work out the ntds settings objectGUID for the current open ldb
1508 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1510 TALLOC_CTX *tmp_ctx;
1511 const char *attrs[] = { "objectGUID", NULL };
1512 int ret;
1513 struct ldb_result *res;
1514 struct GUID *ntds_guid;
1516 /* see if we have a cached copy */
1517 ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1518 if (ntds_guid) {
1519 return ntds_guid;
1522 tmp_ctx = talloc_new(ldb);
1523 if (tmp_ctx == NULL) {
1524 goto failed;
1527 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1528 if (ret) {
1529 goto failed;
1532 if (res->count != 1) {
1533 goto failed;
1536 ntds_guid = talloc(tmp_ctx, struct GUID);
1537 if (!ntds_guid) {
1538 goto failed;
1541 *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1543 /* cache the domain_sid in the ldb */
1544 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1545 goto failed;
1548 talloc_steal(ldb, ntds_guid);
1549 talloc_free(tmp_ctx);
1551 return ntds_guid;
1553 failed:
1554 DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1555 talloc_free(tmp_ctx);
1556 return NULL;
1559 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1561 TALLOC_CTX *tmp_ctx;
1562 struct GUID *ntds_guid_new;
1563 struct GUID *ntds_guid_old;
1565 /* see if we have a cached copy */
1566 ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1568 tmp_ctx = talloc_new(ldb);
1569 if (tmp_ctx == NULL) {
1570 goto failed;
1573 ntds_guid_new = talloc(tmp_ctx, struct GUID);
1574 if (!ntds_guid_new) {
1575 goto failed;
1578 *ntds_guid_new = *ntds_guid_in;
1580 /* cache the domain_sid in the ldb */
1581 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1582 goto failed;
1585 talloc_steal(ldb, ntds_guid_new);
1586 talloc_free(tmp_ctx);
1587 talloc_free(ntds_guid_old);
1589 return true;
1591 failed:
1592 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1593 talloc_free(tmp_ctx);
1594 return false;
1598 work out the server dn for the current open ldb
1600 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1602 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1603 struct ldb_dn *dn;
1604 if (!tmp_ctx) {
1605 return NULL;
1607 dn = ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb, tmp_ctx));
1608 talloc_free(tmp_ctx);
1609 return dn;
1614 work out the server dn for the current open ldb
1616 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1618 struct ldb_dn *server_dn;
1619 struct ldb_dn *servers_dn;
1620 struct ldb_dn *server_site_dn;
1622 /* TODO: there must be a saner way to do this!! */
1623 server_dn = samdb_server_dn(ldb, mem_ctx);
1624 if (!server_dn) return NULL;
1626 servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1627 talloc_free(server_dn);
1628 if (!servers_dn) return NULL;
1630 server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1631 talloc_free(servers_dn);
1633 return server_site_dn;
1637 find the site name from a computers DN record
1639 int samdb_find_site_for_computer(struct ldb_context *ldb,
1640 TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1641 const char **site_name)
1643 int ret;
1644 struct ldb_dn *dn;
1645 const struct ldb_val *rdn_val;
1647 *site_name = NULL;
1649 ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1650 if (ret != LDB_SUCCESS) {
1651 return ret;
1654 if (!ldb_dn_remove_child_components(dn, 2)) {
1655 talloc_free(dn);
1656 return LDB_ERR_INVALID_DN_SYNTAX;
1659 rdn_val = ldb_dn_get_rdn_val(dn);
1660 if (rdn_val == NULL) {
1661 return LDB_ERR_OPERATIONS_ERROR;
1664 (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1665 talloc_free(dn);
1666 if (!*site_name) {
1667 return LDB_ERR_OPERATIONS_ERROR;
1669 return LDB_SUCCESS;
1673 find the NTDS GUID from a computers DN record
1675 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1676 struct GUID *ntds_guid)
1678 int ret;
1679 struct ldb_dn *dn;
1681 *ntds_guid = GUID_zero();
1683 ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1684 if (ret != LDB_SUCCESS) {
1685 return ret;
1688 if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1689 talloc_free(dn);
1690 return LDB_ERR_OPERATIONS_ERROR;
1693 ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1694 talloc_free(dn);
1695 return ret;
1699 find a 'reference' DN that points at another object
1700 (eg. serverReference, rIDManagerReference etc)
1702 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1703 const char *attribute, struct ldb_dn **dn)
1705 const char *attrs[2];
1706 struct ldb_result *res;
1707 int ret;
1709 attrs[0] = attribute;
1710 attrs[1] = NULL;
1712 ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY|DSDB_SEARCH_SHOW_EXTENDED_DN, NULL);
1713 if (ret != LDB_SUCCESS) {
1714 ldb_asprintf_errstring(ldb, "Cannot find DN %s to get attribute %s for reference dn: %s",
1715 ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb));
1716 return ret;
1719 *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1720 if (!*dn) {
1721 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1722 ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1723 ldb_dn_get_linearized(base));
1724 } else {
1725 ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1726 ldb_dn_get_linearized(base));
1728 talloc_free(res);
1729 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1732 talloc_free(res);
1733 return LDB_SUCCESS;
1737 find if a DN (must have GUID component!) is our ntdsDsa
1739 int samdb_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *dn, bool *is_ntdsa)
1741 NTSTATUS status;
1742 struct GUID dn_guid;
1743 const struct GUID *our_ntds_guid;
1744 status = dsdb_get_extended_dn_guid(dn, &dn_guid, "GUID");
1745 if (!NT_STATUS_IS_OK(status)) {
1746 return LDB_ERR_OPERATIONS_ERROR;
1749 our_ntds_guid = samdb_ntds_objectGUID(ldb);
1750 if (!our_ntds_guid) {
1751 DEBUG(0, ("Failed to find our NTDS Settings GUID for comparison with %s - %s\n", ldb_dn_get_linearized(dn), ldb_errstring(ldb)));
1752 return LDB_ERR_OPERATIONS_ERROR;
1755 *is_ntdsa = GUID_equal(&dn_guid, our_ntds_guid);
1756 return LDB_SUCCESS;
1760 find a 'reference' DN that points at another object and indicate if it is our ntdsDsa
1762 int samdb_reference_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *base,
1763 const char *attribute, bool *is_ntdsa)
1765 int ret;
1766 struct ldb_dn *referenced_dn;
1767 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1768 if (tmp_ctx == NULL) {
1769 return LDB_ERR_OPERATIONS_ERROR;
1771 ret = samdb_reference_dn(ldb, tmp_ctx, base, attribute, &referenced_dn);
1772 if (ret != LDB_SUCCESS) {
1773 DEBUG(0, ("Failed to find object %s for attribute %s - %s\n", ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb)));
1774 return ret;
1777 ret = samdb_dn_is_our_ntdsa(ldb, referenced_dn, is_ntdsa);
1779 talloc_free(tmp_ctx);
1780 return ret;
1784 find our machine account via the serverReference attribute in the
1785 server DN
1787 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1789 struct ldb_dn *server_dn;
1790 int ret;
1792 server_dn = samdb_server_dn(ldb, mem_ctx);
1793 if (server_dn == NULL) {
1794 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
1797 ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1798 talloc_free(server_dn);
1800 return ret;
1804 find the RID Manager$ DN via the rIDManagerReference attribute in the
1805 base DN
1807 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1809 return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1810 "rIDManagerReference", dn);
1814 find the RID Set DN via the rIDSetReferences attribute in our
1815 machine account DN
1817 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1819 struct ldb_dn *server_ref_dn;
1820 int ret;
1822 ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1823 if (ret != LDB_SUCCESS) {
1824 return ret;
1826 ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1827 talloc_free(server_ref_dn);
1828 return ret;
1831 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1833 const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1834 mem_ctx));
1836 if (val == NULL) {
1837 return NULL;
1840 return (const char *) val->data;
1844 * Finds the client site by using the client's IP address.
1845 * The "subnet_name" returns the name of the subnet if parameter != NULL
1847 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1848 const char *ip_address, char **subnet_name)
1850 const char *attrs[] = { "cn", "siteObject", NULL };
1851 struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1852 struct ldb_result *res;
1853 const struct ldb_val *val;
1854 const char *site_name = NULL, *l_subnet_name = NULL;
1855 const char *allow_list[2] = { NULL, NULL };
1856 unsigned int i, count;
1857 int cnt, ret;
1860 * if we don't have a client ip e.g. ncalrpc
1861 * the server site is the client site
1863 if (ip_address == NULL) {
1864 return samdb_server_site_name(ldb, mem_ctx);
1867 sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1868 if (sites_container_dn == NULL) {
1869 return NULL;
1872 subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1873 if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1874 talloc_free(sites_container_dn);
1875 talloc_free(subnets_dn);
1876 return NULL;
1879 ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1880 attrs, NULL);
1881 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1882 count = 0;
1883 } else if (ret != LDB_SUCCESS) {
1884 talloc_free(sites_container_dn);
1885 talloc_free(subnets_dn);
1886 return NULL;
1887 } else {
1888 count = res->count;
1891 for (i = 0; i < count; i++) {
1892 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1893 NULL);
1895 allow_list[0] = l_subnet_name;
1897 if (socket_allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1898 sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1899 res->msgs[i],
1900 "siteObject");
1901 if (sites_dn == NULL) {
1902 /* No reference, maybe another subnet matches */
1903 continue;
1906 /* "val" cannot be NULL here since "sites_dn" != NULL */
1907 val = ldb_dn_get_rdn_val(sites_dn);
1908 site_name = talloc_strdup(mem_ctx,
1909 (const char *) val->data);
1911 talloc_free(sites_dn);
1913 break;
1917 if (site_name == NULL) {
1918 /* This is the Windows Server fallback rule: when no subnet
1919 * exists and we have only one site available then use it (it
1920 * is for sure the same as our server site). If more sites do
1921 * exist then we don't know which one to use and set the site
1922 * name to "". */
1923 cnt = samdb_search_count(ldb, mem_ctx, sites_container_dn,
1924 "(objectClass=site)");
1925 if (cnt == 1) {
1926 site_name = samdb_server_site_name(ldb, mem_ctx);
1927 } else {
1928 site_name = talloc_strdup(mem_ctx, "");
1930 l_subnet_name = NULL;
1933 if (subnet_name != NULL) {
1934 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1937 talloc_free(sites_container_dn);
1938 talloc_free(subnets_dn);
1939 talloc_free(res);
1941 return site_name;
1945 work out if we are the PDC for the domain of the current open ldb
1947 bool samdb_is_pdc(struct ldb_context *ldb)
1949 int ret;
1950 bool is_pdc;
1952 ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner",
1953 &is_pdc);
1954 if (ret != LDB_SUCCESS) {
1955 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n",
1956 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
1957 ldb_errstring(ldb)));
1958 return false;
1961 return is_pdc;
1965 work out if we are a Global Catalog server for the domain of the current open ldb
1967 bool samdb_is_gc(struct ldb_context *ldb)
1969 uint32_t options;
1970 if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
1971 return false;
1973 return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
1976 /* Find a domain object in the parents of a particular DN. */
1977 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1978 struct ldb_dn **parent_dn, const char **errstring)
1980 TALLOC_CTX *local_ctx;
1981 struct ldb_dn *sdn = dn;
1982 struct ldb_result *res = NULL;
1983 int ret = LDB_SUCCESS;
1984 const char *attrs[] = { NULL };
1986 local_ctx = talloc_new(mem_ctx);
1987 if (local_ctx == NULL) return ldb_oom(ldb);
1989 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1990 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1991 "(|(objectClass=domain)(objectClass=builtinDomain))");
1992 if (ret == LDB_SUCCESS) {
1993 if (res->count == 1) {
1994 break;
1996 } else {
1997 break;
2001 if (ret != LDB_SUCCESS) {
2002 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
2003 ldb_dn_get_linearized(dn),
2004 ldb_dn_get_linearized(sdn),
2005 ldb_errstring(ldb));
2006 talloc_free(local_ctx);
2007 return ret;
2009 if (res->count != 1) {
2010 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
2011 ldb_dn_get_linearized(dn));
2012 DEBUG(0,(__location__ ": %s\n", *errstring));
2013 talloc_free(local_ctx);
2014 return LDB_ERR_CONSTRAINT_VIOLATION;
2017 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2018 talloc_free(local_ctx);
2019 return ret;
2024 * Performs checks on a user password (plaintext UNIX format - attribute
2025 * "password"). The remaining parameters have to be extracted from the domain
2026 * object in the AD.
2028 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
2030 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *utf8_blob,
2031 const uint32_t pwdProperties,
2032 const uint32_t minPwdLength)
2034 const char *utf8_pw = (const char *)utf8_blob->data;
2035 size_t utf8_len = strlen_m(utf8_pw);
2037 /* checks if the "minPwdLength" property is satisfied */
2038 if (minPwdLength > utf8_len) {
2039 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2042 /* checks the password complexity */
2043 if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
2044 return SAMR_VALIDATION_STATUS_SUCCESS;
2047 if (utf8_len == 0) {
2048 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2051 if (!check_password_quality(utf8_pw)) {
2052 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2055 return SAMR_VALIDATION_STATUS_SUCCESS;
2059 * Callback for "samdb_set_password" password change
2061 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2063 int ret;
2065 if (!ares) {
2066 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2069 if (ares->error != LDB_SUCCESS) {
2070 ret = ares->error;
2071 req->context = talloc_steal(req,
2072 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2073 talloc_free(ares);
2074 return ldb_request_done(req, ret);
2077 if (ares->type != LDB_REPLY_DONE) {
2078 talloc_free(ares);
2079 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2082 req->context = talloc_steal(req,
2083 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2084 talloc_free(ares);
2085 return ldb_request_done(req, LDB_SUCCESS);
2089 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2090 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2091 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2092 * user change or not. The "rejectReason" gives some more information if the
2093 * change failed.
2095 * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2096 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2098 static NTSTATUS samdb_set_password_internal(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2099 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2100 const DATA_BLOB *new_password,
2101 const struct samr_Password *lmNewHash,
2102 const struct samr_Password *ntNewHash,
2103 const struct samr_Password *lmOldHash,
2104 const struct samr_Password *ntOldHash,
2105 enum samPwdChangeReason *reject_reason,
2106 struct samr_DomInfo1 **_dominfo,
2107 bool permit_interdomain_trust)
2109 struct ldb_message *msg;
2110 struct ldb_message_element *el;
2111 struct ldb_request *req;
2112 struct dsdb_control_password_change_status *pwd_stat = NULL;
2113 int ret;
2114 bool hash_values = false;
2115 NTSTATUS status = NT_STATUS_OK;
2117 #define CHECK_RET(x) \
2118 if (x != LDB_SUCCESS) { \
2119 talloc_free(msg); \
2120 return NT_STATUS_NO_MEMORY; \
2123 msg = ldb_msg_new(mem_ctx);
2124 if (msg == NULL) {
2125 return NT_STATUS_NO_MEMORY;
2127 msg->dn = user_dn;
2128 if ((new_password != NULL)
2129 && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2130 /* we have the password as plaintext UTF16 */
2131 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2132 new_password, NULL));
2133 el = ldb_msg_find_element(msg, "clearTextPassword");
2134 el->flags = LDB_FLAG_MOD_REPLACE;
2135 } else if ((new_password == NULL)
2136 && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2137 /* we have a password as LM and/or NT hash */
2138 if (lmNewHash != NULL) {
2139 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2140 "dBCSPwd", lmNewHash));
2141 el = ldb_msg_find_element(msg, "dBCSPwd");
2142 el->flags = LDB_FLAG_MOD_REPLACE;
2144 if (ntNewHash != NULL) {
2145 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2146 "unicodePwd", ntNewHash));
2147 el = ldb_msg_find_element(msg, "unicodePwd");
2148 el->flags = LDB_FLAG_MOD_REPLACE;
2150 hash_values = true;
2151 } else {
2152 /* the password wasn't specified correctly */
2153 talloc_free(msg);
2154 return NT_STATUS_INVALID_PARAMETER;
2157 /* build modify request */
2158 ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2159 samdb_set_password_callback, NULL);
2160 if (ret != LDB_SUCCESS) {
2161 talloc_free(msg);
2162 return NT_STATUS_NO_MEMORY;
2165 /* A password change operation */
2166 if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2167 struct dsdb_control_password_change *change;
2169 change = talloc(req, struct dsdb_control_password_change);
2170 if (change == NULL) {
2171 talloc_free(req);
2172 talloc_free(msg);
2173 return NT_STATUS_NO_MEMORY;
2176 change->old_nt_pwd_hash = ntOldHash;
2177 change->old_lm_pwd_hash = lmOldHash;
2179 ret = ldb_request_add_control(req,
2180 DSDB_CONTROL_PASSWORD_CHANGE_OID,
2181 true, change);
2182 if (ret != LDB_SUCCESS) {
2183 talloc_free(req);
2184 talloc_free(msg);
2185 return NT_STATUS_NO_MEMORY;
2188 if (hash_values) {
2189 ret = ldb_request_add_control(req,
2190 DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2191 true, NULL);
2192 if (ret != LDB_SUCCESS) {
2193 talloc_free(req);
2194 talloc_free(msg);
2195 return NT_STATUS_NO_MEMORY;
2198 if (permit_interdomain_trust) {
2199 ret = ldb_request_add_control(req,
2200 DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
2201 false, NULL);
2202 if (ret != LDB_SUCCESS) {
2203 talloc_free(req);
2204 talloc_free(msg);
2205 return NT_STATUS_NO_MEMORY;
2208 ret = ldb_request_add_control(req,
2209 DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2210 true, NULL);
2211 if (ret != LDB_SUCCESS) {
2212 talloc_free(req);
2213 talloc_free(msg);
2214 return NT_STATUS_NO_MEMORY;
2217 ret = dsdb_autotransaction_request(ldb, req);
2219 if (req->context != NULL) {
2220 struct ldb_control *control = talloc_get_type_abort(req->context,
2221 struct ldb_control);
2222 pwd_stat = talloc_get_type_abort(control->data,
2223 struct dsdb_control_password_change_status);
2224 talloc_steal(mem_ctx, pwd_stat);
2227 talloc_free(req);
2228 talloc_free(msg);
2230 /* Sets the domain info (if requested) */
2231 if (_dominfo != NULL) {
2232 struct samr_DomInfo1 *dominfo;
2234 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2235 if (dominfo == NULL) {
2236 return NT_STATUS_NO_MEMORY;
2239 if (pwd_stat != NULL) {
2240 dominfo->min_password_length = pwd_stat->domain_data.minPwdLength;
2241 dominfo->password_properties = pwd_stat->domain_data.pwdProperties;
2242 dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2243 dominfo->max_password_age = pwd_stat->domain_data.maxPwdAge;
2244 dominfo->min_password_age = pwd_stat->domain_data.minPwdAge;
2247 *_dominfo = dominfo;
2250 if (reject_reason != NULL) {
2251 if (pwd_stat != NULL) {
2252 *reject_reason = pwd_stat->reject_reason;
2253 } else {
2254 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2258 if (pwd_stat != NULL) {
2259 talloc_free(pwd_stat);
2262 if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2263 const char *errmsg = ldb_errstring(ldb);
2264 char *endptr = NULL;
2265 WERROR werr = WERR_GENERAL_FAILURE;
2266 status = NT_STATUS_UNSUCCESSFUL;
2267 if (errmsg != NULL) {
2268 werr = W_ERROR(strtol(errmsg, &endptr, 16));
2269 DBG_WARNING("%s\n", errmsg);
2271 if (endptr != errmsg) {
2272 if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2273 status = NT_STATUS_WRONG_PASSWORD;
2275 if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2276 status = NT_STATUS_PASSWORD_RESTRICTION;
2279 } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2280 /* don't let the caller know if an account doesn't exist */
2281 status = NT_STATUS_WRONG_PASSWORD;
2282 } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2283 status = NT_STATUS_ACCESS_DENIED;
2284 } else if (ret != LDB_SUCCESS) {
2285 DEBUG(1, ("Failed to set password on %s: %s\n",
2286 ldb_dn_get_linearized(msg->dn),
2287 ldb_errstring(ldb)));
2288 status = NT_STATUS_UNSUCCESSFUL;
2291 return status;
2294 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2295 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2296 const DATA_BLOB *new_password,
2297 const struct samr_Password *lmNewHash,
2298 const struct samr_Password *ntNewHash,
2299 const struct samr_Password *lmOldHash,
2300 const struct samr_Password *ntOldHash,
2301 enum samPwdChangeReason *reject_reason,
2302 struct samr_DomInfo1 **_dominfo)
2304 return samdb_set_password_internal(ldb, mem_ctx,
2305 user_dn, domain_dn,
2306 new_password,
2307 lmNewHash, ntNewHash,
2308 lmOldHash, ntOldHash,
2309 reject_reason, _dominfo,
2310 false); /* reject trusts */
2314 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2315 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2316 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2317 * user change or not. The "rejectReason" gives some more information if the
2318 * change failed.
2320 * This wrapper function for "samdb_set_password" takes a SID as input rather
2321 * than a user DN.
2323 * This call encapsulates a new LDB transaction for changing the password;
2324 * therefore the user hasn't to start a new one.
2326 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2327 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2328 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2329 * NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2331 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2332 const struct dom_sid *user_sid,
2333 const uint32_t *new_version, /* optional for trusts */
2334 const DATA_BLOB *new_password,
2335 const struct samr_Password *lmNewHash,
2336 const struct samr_Password *ntNewHash,
2337 const struct samr_Password *lmOldHash,
2338 const struct samr_Password *ntOldHash,
2339 enum samPwdChangeReason *reject_reason,
2340 struct samr_DomInfo1 **_dominfo)
2342 TALLOC_CTX *frame = talloc_stackframe();
2343 NTSTATUS nt_status;
2344 const char * const user_attrs[] = {
2345 "userAccountControl",
2346 "sAMAccountName",
2347 NULL
2349 struct ldb_message *user_msg = NULL;
2350 int ret;
2351 uint32_t uac = 0;
2353 ret = ldb_transaction_start(ldb);
2354 if (ret != LDB_SUCCESS) {
2355 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2356 TALLOC_FREE(frame);
2357 return NT_STATUS_TRANSACTION_ABORTED;
2360 ret = dsdb_search_one(ldb, frame, &user_msg, ldb_get_default_basedn(ldb),
2361 LDB_SCOPE_SUBTREE, user_attrs, 0,
2362 "(&(objectSid=%s)(objectClass=user))",
2363 ldap_encode_ndr_dom_sid(frame, user_sid));
2364 if (ret != LDB_SUCCESS) {
2365 ldb_transaction_cancel(ldb);
2366 DEBUG(3, ("samdb_set_password_sid: SID[%s] not found in samdb %s - %s, "
2367 "returning NO_SUCH_USER\n",
2368 dom_sid_string(frame, user_sid),
2369 ldb_strerror(ret), ldb_errstring(ldb)));
2370 TALLOC_FREE(frame);
2371 return NT_STATUS_NO_SUCH_USER;
2374 uac = ldb_msg_find_attr_as_uint(user_msg, "userAccountControl", 0);
2375 if (!(uac & UF_ACCOUNT_TYPE_MASK)) {
2376 ldb_transaction_cancel(ldb);
2377 DEBUG(1, ("samdb_set_password_sid: invalid "
2378 "userAccountControl[0x%08X] for SID[%s] DN[%s], "
2379 "returning NO_SUCH_USER\n",
2380 (unsigned)uac, dom_sid_string(frame, user_sid),
2381 ldb_dn_get_linearized(user_msg->dn)));
2382 TALLOC_FREE(frame);
2383 return NT_STATUS_NO_SUCH_USER;
2386 if (uac & UF_INTERDOMAIN_TRUST_ACCOUNT) {
2387 const char * const tdo_attrs[] = {
2388 "trustAuthIncoming",
2389 "trustDirection",
2390 NULL
2392 struct ldb_message *tdo_msg = NULL;
2393 const char *account_name = NULL;
2394 uint32_t trust_direction;
2395 uint32_t i;
2396 const struct ldb_val *old_val = NULL;
2397 struct trustAuthInOutBlob old_blob = {};
2398 uint32_t old_version = 0;
2399 struct AuthenticationInformation *old_version_a = NULL;
2400 uint32_t _new_version = 0;
2401 struct trustAuthInOutBlob new_blob = {};
2402 struct ldb_val new_val = {};
2403 struct timeval tv = timeval_current();
2404 NTTIME now = timeval_to_nttime(&tv);
2405 enum ndr_err_code ndr_err;
2407 if (new_password == NULL && ntNewHash == NULL) {
2408 ldb_transaction_cancel(ldb);
2409 DEBUG(1, ("samdb_set_password_sid: "
2410 "no new password provided "
2411 "sAMAccountName for SID[%s] DN[%s], "
2412 "returning INVALID_PARAMETER\n",
2413 dom_sid_string(frame, user_sid),
2414 ldb_dn_get_linearized(user_msg->dn)));
2415 TALLOC_FREE(frame);
2416 return NT_STATUS_INVALID_PARAMETER;
2419 if (new_password != NULL && ntNewHash != NULL) {
2420 ldb_transaction_cancel(ldb);
2421 DEBUG(1, ("samdb_set_password_sid: "
2422 "two new passwords provided "
2423 "sAMAccountName for SID[%s] DN[%s], "
2424 "returning INVALID_PARAMETER\n",
2425 dom_sid_string(frame, user_sid),
2426 ldb_dn_get_linearized(user_msg->dn)));
2427 TALLOC_FREE(frame);
2428 return NT_STATUS_INVALID_PARAMETER;
2431 if (new_password != NULL && (new_password->length % 2)) {
2432 ldb_transaction_cancel(ldb);
2433 DEBUG(2, ("samdb_set_password_sid: "
2434 "invalid utf16 length (%zu) "
2435 "sAMAccountName for SID[%s] DN[%s], "
2436 "returning WRONG_PASSWORD\n",
2437 new_password->length,
2438 dom_sid_string(frame, user_sid),
2439 ldb_dn_get_linearized(user_msg->dn)));
2440 TALLOC_FREE(frame);
2441 return NT_STATUS_WRONG_PASSWORD;
2444 if (new_password != NULL && new_password->length >= 500) {
2445 ldb_transaction_cancel(ldb);
2446 DEBUG(2, ("samdb_set_password_sid: "
2447 "utf16 password too long (%zu) "
2448 "sAMAccountName for SID[%s] DN[%s], "
2449 "returning WRONG_PASSWORD\n",
2450 new_password->length,
2451 dom_sid_string(frame, user_sid),
2452 ldb_dn_get_linearized(user_msg->dn)));
2453 TALLOC_FREE(frame);
2454 return NT_STATUS_WRONG_PASSWORD;
2457 account_name = ldb_msg_find_attr_as_string(user_msg,
2458 "sAMAccountName", NULL);
2459 if (account_name == NULL) {
2460 ldb_transaction_cancel(ldb);
2461 DEBUG(1, ("samdb_set_password_sid: missing "
2462 "sAMAccountName for SID[%s] DN[%s], "
2463 "returning NO_SUCH_USER\n",
2464 dom_sid_string(frame, user_sid),
2465 ldb_dn_get_linearized(user_msg->dn)));
2466 TALLOC_FREE(frame);
2467 return NT_STATUS_NO_SUCH_USER;
2470 nt_status = dsdb_trust_search_tdo_by_type(ldb,
2471 SEC_CHAN_DOMAIN,
2472 account_name,
2473 tdo_attrs,
2474 frame, &tdo_msg);
2475 if (!NT_STATUS_IS_OK(nt_status)) {
2476 ldb_transaction_cancel(ldb);
2477 DEBUG(1, ("samdb_set_password_sid: dsdb_trust_search_tdo "
2478 "failed(%s) for sAMAccountName[%s] SID[%s] DN[%s], "
2479 "returning INTERNAL_DB_CORRUPTION\n",
2480 nt_errstr(nt_status), account_name,
2481 dom_sid_string(frame, user_sid),
2482 ldb_dn_get_linearized(user_msg->dn)));
2483 TALLOC_FREE(frame);
2484 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2487 trust_direction = ldb_msg_find_attr_as_int(tdo_msg,
2488 "trustDirection", 0);
2489 if (!(trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {
2490 ldb_transaction_cancel(ldb);
2491 DEBUG(1, ("samdb_set_password_sid: direction[0x%08X] is "
2492 "not inbound for sAMAccountName[%s] "
2493 "DN[%s] TDO[%s], "
2494 "returning INTERNAL_DB_CORRUPTION\n",
2495 (unsigned)trust_direction,
2496 account_name,
2497 ldb_dn_get_linearized(user_msg->dn),
2498 ldb_dn_get_linearized(tdo_msg->dn)));
2499 TALLOC_FREE(frame);
2500 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2503 old_val = ldb_msg_find_ldb_val(tdo_msg, "trustAuthIncoming");
2504 if (old_val != NULL) {
2505 ndr_err = ndr_pull_struct_blob(old_val, frame, &old_blob,
2506 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2507 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2508 ldb_transaction_cancel(ldb);
2509 DEBUG(1, ("samdb_set_password_sid: "
2510 "failed(%s) to parse "
2511 "trustAuthOutgoing sAMAccountName[%s] "
2512 "DN[%s] TDO[%s], "
2513 "returning INTERNAL_DB_CORRUPTION\n",
2514 ndr_map_error2string(ndr_err),
2515 account_name,
2516 ldb_dn_get_linearized(user_msg->dn),
2517 ldb_dn_get_linearized(tdo_msg->dn)));
2519 TALLOC_FREE(frame);
2520 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2524 for (i = old_blob.current.count; i > 0; i--) {
2525 struct AuthenticationInformation *a =
2526 &old_blob.current.array[i - 1];
2528 switch (a->AuthType) {
2529 case TRUST_AUTH_TYPE_NONE:
2530 if (i == old_blob.current.count) {
2532 * remove TRUST_AUTH_TYPE_NONE at the
2533 * end
2535 old_blob.current.count--;
2537 break;
2539 case TRUST_AUTH_TYPE_VERSION:
2540 old_version_a = a;
2541 old_version = a->AuthInfo.version.version;
2542 break;
2544 case TRUST_AUTH_TYPE_CLEAR:
2545 break;
2547 case TRUST_AUTH_TYPE_NT4OWF:
2548 break;
2552 if (new_version == NULL) {
2553 _new_version = 0;
2554 new_version = &_new_version;
2557 if (old_version_a != NULL && *new_version != (old_version + 1)) {
2558 old_version_a->LastUpdateTime = now;
2559 old_version_a->AuthType = TRUST_AUTH_TYPE_NONE;
2562 new_blob.count = MAX(old_blob.current.count, 2);
2563 new_blob.current.array = talloc_zero_array(frame,
2564 struct AuthenticationInformation,
2565 new_blob.count);
2566 if (new_blob.current.array == NULL) {
2567 ldb_transaction_cancel(ldb);
2568 TALLOC_FREE(frame);
2569 return NT_STATUS_NO_MEMORY;
2571 new_blob.previous.array = talloc_zero_array(frame,
2572 struct AuthenticationInformation,
2573 new_blob.count);
2574 if (new_blob.current.array == NULL) {
2575 ldb_transaction_cancel(ldb);
2576 TALLOC_FREE(frame);
2577 return NT_STATUS_NO_MEMORY;
2580 for (i = 0; i < old_blob.current.count; i++) {
2581 struct AuthenticationInformation *o =
2582 &old_blob.current.array[i];
2583 struct AuthenticationInformation *p =
2584 &new_blob.previous.array[i];
2586 *p = *o;
2587 new_blob.previous.count++;
2589 for (; i < new_blob.count; i++) {
2590 struct AuthenticationInformation *pi =
2591 &new_blob.previous.array[i];
2593 if (i == 0) {
2595 * new_blob.previous is still empty so
2596 * we'll do new_blob.previous = new_blob.current
2597 * below.
2599 break;
2602 pi->LastUpdateTime = now;
2603 pi->AuthType = TRUST_AUTH_TYPE_NONE;
2604 new_blob.previous.count++;
2607 for (i = 0; i < new_blob.count; i++) {
2608 struct AuthenticationInformation *ci =
2609 &new_blob.current.array[i];
2611 ci->LastUpdateTime = now;
2612 switch (i) {
2613 case 0:
2614 if (ntNewHash != NULL) {
2615 ci->AuthType = TRUST_AUTH_TYPE_NT4OWF;
2616 ci->AuthInfo.nt4owf.password = *ntNewHash;
2617 break;
2620 ci->AuthType = TRUST_AUTH_TYPE_CLEAR;
2621 ci->AuthInfo.clear.size = new_password->length;
2622 ci->AuthInfo.clear.password = new_password->data;
2623 break;
2624 case 1:
2625 ci->AuthType = TRUST_AUTH_TYPE_VERSION;
2626 ci->AuthInfo.version.version = *new_version;
2627 break;
2628 default:
2629 ci->AuthType = TRUST_AUTH_TYPE_NONE;
2630 break;
2633 new_blob.current.count++;
2636 if (new_blob.previous.count == 0) {
2637 TALLOC_FREE(new_blob.previous.array);
2638 new_blob.previous = new_blob.current;
2641 ndr_err = ndr_push_struct_blob(&new_val, frame, &new_blob,
2642 (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2643 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2644 ldb_transaction_cancel(ldb);
2645 DEBUG(1, ("samdb_set_password_sid: "
2646 "failed(%s) to generate "
2647 "trustAuthOutgoing sAMAccountName[%s] "
2648 "DN[%s] TDO[%s], "
2649 "returning UNSUCCESSFUL\n",
2650 ndr_map_error2string(ndr_err),
2651 account_name,
2652 ldb_dn_get_linearized(user_msg->dn),
2653 ldb_dn_get_linearized(tdo_msg->dn)));
2654 TALLOC_FREE(frame);
2655 return NT_STATUS_UNSUCCESSFUL;
2658 tdo_msg->num_elements = 0;
2659 TALLOC_FREE(tdo_msg->elements);
2661 ret = ldb_msg_add_empty(tdo_msg, "trustAuthIncoming",
2662 LDB_FLAG_MOD_REPLACE, NULL);
2663 if (ret != LDB_SUCCESS) {
2664 ldb_transaction_cancel(ldb);
2665 TALLOC_FREE(frame);
2666 return NT_STATUS_NO_MEMORY;
2668 ret = ldb_msg_add_value(tdo_msg, "trustAuthIncoming",
2669 &new_val, NULL);
2670 if (ret != LDB_SUCCESS) {
2671 ldb_transaction_cancel(ldb);
2672 TALLOC_FREE(frame);
2673 return NT_STATUS_NO_MEMORY;
2676 ret = ldb_modify(ldb, tdo_msg);
2677 if (ret != LDB_SUCCESS) {
2678 nt_status = dsdb_ldb_err_to_ntstatus(ret);
2679 ldb_transaction_cancel(ldb);
2680 DEBUG(1, ("samdb_set_password_sid: "
2681 "failed to replace "
2682 "trustAuthOutgoing sAMAccountName[%s] "
2683 "DN[%s] TDO[%s], "
2684 "%s - %s\n",
2685 account_name,
2686 ldb_dn_get_linearized(user_msg->dn),
2687 ldb_dn_get_linearized(tdo_msg->dn),
2688 nt_errstr(nt_status), ldb_errstring(ldb)));
2689 TALLOC_FREE(frame);
2690 return nt_status;
2694 nt_status = samdb_set_password_internal(ldb, mem_ctx,
2695 user_msg->dn, NULL,
2696 new_password,
2697 lmNewHash, ntNewHash,
2698 lmOldHash, ntOldHash,
2699 reject_reason, _dominfo,
2700 true); /* permit trusts */
2701 if (!NT_STATUS_IS_OK(nt_status)) {
2702 ldb_transaction_cancel(ldb);
2703 TALLOC_FREE(frame);
2704 return nt_status;
2707 ret = ldb_transaction_commit(ldb);
2708 if (ret != LDB_SUCCESS) {
2709 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2710 ldb_dn_get_linearized(user_msg->dn),
2711 ldb_errstring(ldb)));
2712 TALLOC_FREE(frame);
2713 return NT_STATUS_TRANSACTION_ABORTED;
2716 TALLOC_FREE(frame);
2717 return NT_STATUS_OK;
2721 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
2722 struct dom_sid *sid, struct ldb_dn **ret_dn)
2724 struct ldb_message *msg;
2725 struct ldb_dn *basedn;
2726 char *sidstr;
2727 int ret;
2729 sidstr = dom_sid_string(mem_ctx, sid);
2730 NT_STATUS_HAVE_NO_MEMORY(sidstr);
2732 /* We might have to create a ForeignSecurityPrincipal, even if this user
2733 * is in our own domain */
2735 msg = ldb_msg_new(sidstr);
2736 if (msg == NULL) {
2737 talloc_free(sidstr);
2738 return NT_STATUS_NO_MEMORY;
2741 ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2742 ldb_get_default_basedn(sam_ctx),
2743 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2744 &basedn);
2745 if (ret != LDB_SUCCESS) {
2746 DEBUG(0, ("Failed to find DN for "
2747 "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2748 talloc_free(sidstr);
2749 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2752 /* add core elements to the ldb_message for the alias */
2753 msg->dn = basedn;
2754 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2755 talloc_free(sidstr);
2756 return NT_STATUS_NO_MEMORY;
2759 ret = ldb_msg_add_string(msg, "objectClass",
2760 "foreignSecurityPrincipal");
2761 if (ret != LDB_SUCCESS) {
2762 talloc_free(sidstr);
2763 return NT_STATUS_NO_MEMORY;
2766 /* create the alias */
2767 ret = ldb_add(sam_ctx, msg);
2768 if (ret != LDB_SUCCESS) {
2769 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2770 "record %s: %s\n",
2771 ldb_dn_get_linearized(msg->dn),
2772 ldb_errstring(sam_ctx)));
2773 talloc_free(sidstr);
2774 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2777 *ret_dn = talloc_steal(mem_ctx, msg->dn);
2778 talloc_free(sidstr);
2780 return NT_STATUS_OK;
2785 Find the DN of a domain, assuming it to be a dotted.dns name
2788 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
2790 unsigned int i;
2791 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2792 const char *binary_encoded;
2793 const char * const *split_realm;
2794 struct ldb_dn *dn;
2796 if (!tmp_ctx) {
2797 return NULL;
2800 split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
2801 if (!split_realm) {
2802 talloc_free(tmp_ctx);
2803 return NULL;
2805 dn = ldb_dn_new(mem_ctx, ldb, NULL);
2806 for (i=0; split_realm[i]; i++) {
2807 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2808 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2809 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2810 binary_encoded, ldb_dn_get_linearized(dn)));
2811 talloc_free(tmp_ctx);
2812 return NULL;
2815 if (!ldb_dn_validate(dn)) {
2816 DEBUG(2, ("Failed to validated DN %s\n",
2817 ldb_dn_get_linearized(dn)));
2818 talloc_free(tmp_ctx);
2819 return NULL;
2821 talloc_free(tmp_ctx);
2822 return dn;
2827 Find the DNS equivalent of a DN, in dotted DNS form
2829 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
2831 int i, num_components = ldb_dn_get_comp_num(dn);
2832 char *dns_name = talloc_strdup(mem_ctx, "");
2833 if (dns_name == NULL) {
2834 return NULL;
2837 for (i=0; i<num_components; i++) {
2838 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
2839 char *s;
2840 if (v == NULL) {
2841 talloc_free(dns_name);
2842 return NULL;
2844 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
2845 (int)v->length, (int)v->length, (char *)v->data);
2846 if (s == NULL) {
2847 talloc_free(dns_name);
2848 return NULL;
2850 dns_name = s;
2853 /* remove the last '.' */
2854 if (dns_name[0] != 0) {
2855 dns_name[strlen(dns_name)-1] = 0;
2858 return dns_name;
2862 Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
2863 name is based on the forest DNS name
2865 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
2866 TALLOC_CTX *mem_ctx,
2867 const struct GUID *ntds_guid)
2869 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2870 const char *guid_str;
2871 struct ldb_dn *forest_dn;
2872 const char *dnsforest;
2873 char *ret;
2875 guid_str = GUID_string(tmp_ctx, ntds_guid);
2876 if (guid_str == NULL) {
2877 talloc_free(tmp_ctx);
2878 return NULL;
2880 forest_dn = ldb_get_root_basedn(samdb);
2881 if (forest_dn == NULL) {
2882 talloc_free(tmp_ctx);
2883 return NULL;
2885 dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
2886 if (dnsforest == NULL) {
2887 talloc_free(tmp_ctx);
2888 return NULL;
2890 ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
2891 talloc_free(tmp_ctx);
2892 return ret;
2897 Find the DN of a domain, be it the netbios or DNS name
2899 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2900 const char *domain_name)
2902 const char * const domain_ref_attrs[] = {
2903 "ncName", NULL
2905 const char * const domain_ref2_attrs[] = {
2906 NULL
2908 struct ldb_result *res_domain_ref;
2909 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2910 /* find the domain's DN */
2911 int ret_domain = ldb_search(ldb, mem_ctx,
2912 &res_domain_ref,
2913 samdb_partitions_dn(ldb, mem_ctx),
2914 LDB_SCOPE_ONELEVEL,
2915 domain_ref_attrs,
2916 "(&(nETBIOSName=%s)(objectclass=crossRef))",
2917 escaped_domain);
2918 if (ret_domain != LDB_SUCCESS) {
2919 return NULL;
2922 if (res_domain_ref->count == 0) {
2923 ret_domain = ldb_search(ldb, mem_ctx,
2924 &res_domain_ref,
2925 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2926 LDB_SCOPE_BASE,
2927 domain_ref2_attrs,
2928 "(objectclass=domain)");
2929 if (ret_domain != LDB_SUCCESS) {
2930 return NULL;
2933 if (res_domain_ref->count == 1) {
2934 return res_domain_ref->msgs[0]->dn;
2936 return NULL;
2939 if (res_domain_ref->count > 1) {
2940 DEBUG(0,("Found %d records matching domain [%s]\n",
2941 ret_domain, domain_name));
2942 return NULL;
2945 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2951 use a GUID to find a DN
2953 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
2954 TALLOC_CTX *mem_ctx,
2955 const struct GUID *guid,
2956 uint32_t dsdb_flags,
2957 struct ldb_dn **dn)
2959 int ret;
2960 struct ldb_result *res;
2961 const char *attrs[] = { NULL };
2962 char *guid_str = GUID_string(mem_ctx, guid);
2964 if (!guid_str) {
2965 return ldb_operr(ldb);
2968 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2969 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2970 DSDB_SEARCH_SHOW_EXTENDED_DN |
2971 DSDB_SEARCH_ONE_ONLY | dsdb_flags,
2972 "objectGUID=%s", guid_str);
2973 talloc_free(guid_str);
2974 if (ret != LDB_SUCCESS) {
2975 return ret;
2978 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2979 talloc_free(res);
2981 return LDB_SUCCESS;
2985 use a DN to find a GUID with a given attribute name
2987 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2988 struct ldb_dn *dn, const char *attribute,
2989 struct GUID *guid)
2991 int ret;
2992 struct ldb_result *res;
2993 const char *attrs[2];
2994 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2996 attrs[0] = attribute;
2997 attrs[1] = NULL;
2999 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3000 DSDB_SEARCH_SHOW_DELETED |
3001 DSDB_SEARCH_SHOW_RECYCLED);
3002 if (ret != LDB_SUCCESS) {
3003 talloc_free(tmp_ctx);
3004 return ret;
3006 if (res->count < 1) {
3007 talloc_free(tmp_ctx);
3008 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3010 *guid = samdb_result_guid(res->msgs[0], attribute);
3011 talloc_free(tmp_ctx);
3012 return LDB_SUCCESS;
3016 use a DN to find a GUID
3018 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
3019 struct ldb_dn *dn, struct GUID *guid)
3021 return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
3027 adds the given GUID to the given ldb_message. This value is added
3028 for the given attr_name (may be either "objectGUID" or "parentGUID").
3030 int dsdb_msg_add_guid(struct ldb_message *msg,
3031 struct GUID *guid,
3032 const char *attr_name)
3034 int ret;
3035 struct ldb_val v;
3036 NTSTATUS status;
3037 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
3039 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
3040 if (!NT_STATUS_IS_OK(status)) {
3041 ret = LDB_ERR_OPERATIONS_ERROR;
3042 goto done;
3045 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
3046 if (ret != LDB_SUCCESS) {
3047 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
3048 attr_name));
3049 goto done;
3052 ret = LDB_SUCCESS;
3054 done:
3055 talloc_free(tmp_ctx);
3056 return ret;
3062 use a DN to find a SID
3064 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
3065 struct ldb_dn *dn, struct dom_sid *sid)
3067 int ret;
3068 struct ldb_result *res;
3069 const char *attrs[] = { "objectSid", NULL };
3070 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3071 struct dom_sid *s;
3073 ZERO_STRUCTP(sid);
3075 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3076 DSDB_SEARCH_SHOW_DELETED |
3077 DSDB_SEARCH_SHOW_RECYCLED);
3078 if (ret != LDB_SUCCESS) {
3079 talloc_free(tmp_ctx);
3080 return ret;
3082 if (res->count < 1) {
3083 talloc_free(tmp_ctx);
3084 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3086 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
3087 if (s == NULL) {
3088 talloc_free(tmp_ctx);
3089 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3091 *sid = *s;
3092 talloc_free(tmp_ctx);
3093 return LDB_SUCCESS;
3097 use a SID to find a DN
3099 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
3100 TALLOC_CTX *mem_ctx,
3101 struct dom_sid *sid, struct ldb_dn **dn)
3103 int ret;
3104 struct ldb_result *res;
3105 const char *attrs[] = { NULL };
3106 char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
3108 if (!sid_str) {
3109 return ldb_operr(ldb);
3112 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3113 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3114 DSDB_SEARCH_SHOW_EXTENDED_DN |
3115 DSDB_SEARCH_ONE_ONLY,
3116 "objectSid=%s", sid_str);
3117 talloc_free(sid_str);
3118 if (ret != LDB_SUCCESS) {
3119 return ret;
3122 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3123 talloc_free(res);
3125 return LDB_SUCCESS;
3129 load a repsFromTo blob list for a given partition GUID
3130 attr must be "repsFrom" or "repsTo"
3132 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3133 const char *attr, struct repsFromToBlob **r, uint32_t *count)
3135 const char *attrs[] = { attr, NULL };
3136 struct ldb_result *res = NULL;
3137 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3138 unsigned int i;
3139 struct ldb_message_element *el;
3140 int ret;
3142 *r = NULL;
3143 *count = 0;
3145 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
3146 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3147 /* partition hasn't been replicated yet */
3148 return WERR_OK;
3150 if (ret != LDB_SUCCESS) {
3151 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
3152 talloc_free(tmp_ctx);
3153 return WERR_DS_DRA_INTERNAL_ERROR;
3156 el = ldb_msg_find_element(res->msgs[0], attr);
3157 if (el == NULL) {
3158 /* it's OK to be empty */
3159 talloc_free(tmp_ctx);
3160 return WERR_OK;
3163 *count = el->num_values;
3164 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
3165 if (*r == NULL) {
3166 talloc_free(tmp_ctx);
3167 return WERR_DS_DRA_INTERNAL_ERROR;
3170 for (i=0; i<(*count); i++) {
3171 enum ndr_err_code ndr_err;
3172 ndr_err = ndr_pull_struct_blob(&el->values[i],
3173 mem_ctx,
3174 &(*r)[i],
3175 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3176 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3177 talloc_free(tmp_ctx);
3178 return WERR_DS_DRA_INTERNAL_ERROR;
3182 talloc_free(tmp_ctx);
3184 return WERR_OK;
3188 save the repsFromTo blob list for a given partition GUID
3189 attr must be "repsFrom" or "repsTo"
3191 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3192 const char *attr, struct repsFromToBlob *r, uint32_t count)
3194 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3195 struct ldb_message *msg;
3196 struct ldb_message_element *el;
3197 unsigned int i;
3199 msg = ldb_msg_new(tmp_ctx);
3200 msg->dn = dn;
3201 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
3202 goto failed;
3205 el->values = talloc_array(msg, struct ldb_val, count);
3206 if (!el->values) {
3207 goto failed;
3210 for (i=0; i<count; i++) {
3211 struct ldb_val v;
3212 enum ndr_err_code ndr_err;
3214 ndr_err = ndr_push_struct_blob(&v, tmp_ctx,
3215 &r[i],
3216 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3217 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3218 goto failed;
3221 el->num_values++;
3222 el->values[i] = v;
3225 if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
3226 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
3227 goto failed;
3230 talloc_free(tmp_ctx);
3232 return WERR_OK;
3234 failed:
3235 talloc_free(tmp_ctx);
3236 return WERR_DS_DRA_INTERNAL_ERROR;
3241 load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
3242 object for a partition
3244 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
3245 uint64_t *uSN, uint64_t *urgent_uSN)
3247 struct ldb_request *req;
3248 int ret;
3249 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3250 struct dsdb_control_current_partition *p_ctrl;
3251 struct ldb_result *res;
3253 res = talloc_zero(tmp_ctx, struct ldb_result);
3254 if (!res) {
3255 talloc_free(tmp_ctx);
3256 return ldb_oom(ldb);
3259 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3260 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
3261 LDB_SCOPE_BASE,
3262 NULL, NULL,
3263 NULL,
3264 res, ldb_search_default_callback,
3265 NULL);
3266 if (ret != LDB_SUCCESS) {
3267 talloc_free(tmp_ctx);
3268 return ret;
3271 p_ctrl = talloc(req, struct dsdb_control_current_partition);
3272 if (p_ctrl == NULL) {
3273 talloc_free(tmp_ctx);
3274 return ldb_oom(ldb);
3276 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
3277 p_ctrl->dn = dn;
3279 ret = ldb_request_add_control(req,
3280 DSDB_CONTROL_CURRENT_PARTITION_OID,
3281 false, p_ctrl);
3282 if (ret != LDB_SUCCESS) {
3283 talloc_free(tmp_ctx);
3284 return ret;
3287 /* Run the new request */
3288 ret = ldb_request(ldb, req);
3290 if (ret == LDB_SUCCESS) {
3291 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3294 if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
3295 /* it hasn't been created yet, which means
3296 an implicit value of zero */
3297 *uSN = 0;
3298 talloc_free(tmp_ctx);
3299 return LDB_SUCCESS;
3302 if (ret != LDB_SUCCESS) {
3303 talloc_free(tmp_ctx);
3304 return ret;
3307 if (res->count < 1) {
3308 *uSN = 0;
3309 if (urgent_uSN) {
3310 *urgent_uSN = 0;
3312 } else {
3313 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
3314 if (urgent_uSN) {
3315 *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
3319 talloc_free(tmp_ctx);
3321 return LDB_SUCCESS;
3324 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
3325 const struct drsuapi_DsReplicaCursor2 *c2)
3327 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3330 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
3331 const struct drsuapi_DsReplicaCursor *c2)
3333 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3338 see if a computer identified by its invocationId is a RODC
3340 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
3342 /* 1) find the DN for this servers NTDSDSA object
3343 2) search for the msDS-isRODC attribute
3344 3) if not present then not a RODC
3345 4) if present and TRUE then is a RODC
3347 struct ldb_dn *config_dn;
3348 const char *attrs[] = { "msDS-isRODC", NULL };
3349 int ret;
3350 struct ldb_result *res;
3351 TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
3353 config_dn = ldb_get_config_basedn(sam_ctx);
3354 if (!config_dn) {
3355 talloc_free(tmp_ctx);
3356 return ldb_operr(sam_ctx);
3359 ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
3360 DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
3362 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3363 *is_rodc = false;
3364 talloc_free(tmp_ctx);
3365 return LDB_SUCCESS;
3368 if (ret != LDB_SUCCESS) {
3369 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
3370 GUID_string(tmp_ctx, objectGUID)));
3371 *is_rodc = false;
3372 talloc_free(tmp_ctx);
3373 return ret;
3376 ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
3377 *is_rodc = (ret == 1);
3379 talloc_free(tmp_ctx);
3380 return LDB_SUCCESS;
3385 see if we are a RODC
3387 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
3389 const struct GUID *objectGUID;
3390 int ret;
3391 bool *cached;
3393 /* see if we have a cached copy */
3394 cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
3395 if (cached) {
3396 *am_rodc = *cached;
3397 return LDB_SUCCESS;
3400 objectGUID = samdb_ntds_objectGUID(sam_ctx);
3401 if (!objectGUID) {
3402 return ldb_operr(sam_ctx);
3405 ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
3406 if (ret != LDB_SUCCESS) {
3407 return ret;
3410 cached = talloc(sam_ctx, bool);
3411 if (cached == NULL) {
3412 return ldb_oom(sam_ctx);
3414 *cached = *am_rodc;
3416 ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
3417 if (ret != LDB_SUCCESS) {
3418 talloc_free(cached);
3419 return ldb_operr(sam_ctx);
3422 return LDB_SUCCESS;
3425 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3427 TALLOC_CTX *tmp_ctx;
3428 bool *cached;
3430 tmp_ctx = talloc_new(ldb);
3431 if (tmp_ctx == NULL) {
3432 goto failed;
3435 cached = talloc(tmp_ctx, bool);
3436 if (!cached) {
3437 goto failed;
3440 *cached = am_rodc;
3441 if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3442 goto failed;
3445 talloc_steal(ldb, cached);
3446 talloc_free(tmp_ctx);
3447 return true;
3449 failed:
3450 DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3451 talloc_free(tmp_ctx);
3452 return false;
3457 * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3458 * flags are DS_NTDSSETTINGS_OPT_*
3460 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3461 uint32_t *options)
3463 int rc;
3464 TALLOC_CTX *tmp_ctx;
3465 struct ldb_result *res;
3466 struct ldb_dn *site_dn;
3467 const char *attrs[] = { "options", NULL };
3469 tmp_ctx = talloc_new(ldb_ctx);
3470 if (tmp_ctx == NULL)
3471 goto failed;
3473 /* Retrieve the site dn for the ldb that we
3474 * have open. This is our local site.
3476 site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3477 if (site_dn == NULL)
3478 goto failed;
3480 /* Perform a one level (child) search from the local
3481 * site distinguided name. We're looking for the
3482 * "options" attribute within the nTDSSiteSettings
3483 * object
3485 rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3486 LDB_SCOPE_ONELEVEL, attrs,
3487 "objectClass=nTDSSiteSettings");
3489 if (rc != LDB_SUCCESS || res->count != 1)
3490 goto failed;
3492 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3494 talloc_free(tmp_ctx);
3496 return LDB_SUCCESS;
3498 failed:
3499 DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3500 talloc_free(tmp_ctx);
3501 return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
3505 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
3507 flags are DS_NTDS_OPTION_*
3509 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3511 TALLOC_CTX *tmp_ctx;
3512 const char *attrs[] = { "options", NULL };
3513 int ret;
3514 struct ldb_result *res;
3516 tmp_ctx = talloc_new(ldb);
3517 if (tmp_ctx == NULL) {
3518 goto failed;
3521 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3522 if (ret != LDB_SUCCESS) {
3523 goto failed;
3526 if (res->count != 1) {
3527 goto failed;
3530 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3532 talloc_free(tmp_ctx);
3534 return LDB_SUCCESS;
3536 failed:
3537 DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3538 talloc_free(tmp_ctx);
3539 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3542 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3544 const char *attrs[] = { "objectCategory", NULL };
3545 int ret;
3546 struct ldb_result *res;
3548 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3549 if (ret != LDB_SUCCESS) {
3550 goto failed;
3553 if (res->count != 1) {
3554 goto failed;
3557 return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3559 failed:
3560 DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3561 return NULL;
3565 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3566 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3568 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3570 char **tokens, *ret;
3571 size_t i;
3573 tokens = str_list_make(mem_ctx, cn, " -_");
3574 if (tokens == NULL || tokens[0] == NULL) {
3575 return NULL;
3578 /* "tolower()" and "toupper()" should also work properly on 0x00 */
3579 tokens[0][0] = tolower(tokens[0][0]);
3580 for (i = 1; tokens[i] != NULL; i++)
3581 tokens[i][0] = toupper(tokens[i][0]);
3583 ret = talloc_strdup(mem_ctx, tokens[0]);
3584 for (i = 1; tokens[i] != NULL; i++)
3585 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3587 talloc_free(tokens);
3589 return ret;
3593 * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3595 int dsdb_functional_level(struct ldb_context *ldb)
3597 int *domainFunctionality =
3598 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3599 if (!domainFunctionality) {
3600 /* this is expected during initial provision */
3601 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3602 return DS_DOMAIN_FUNCTION_2000;
3604 return *domainFunctionality;
3608 * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3610 int dsdb_forest_functional_level(struct ldb_context *ldb)
3612 int *forestFunctionality =
3613 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3614 if (!forestFunctionality) {
3615 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3616 return DS_DOMAIN_FUNCTION_2000;
3618 return *forestFunctionality;
3622 set a GUID in an extended DN structure
3624 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3626 struct ldb_val v;
3627 NTSTATUS status;
3628 int ret;
3630 status = GUID_to_ndr_blob(guid, dn, &v);
3631 if (!NT_STATUS_IS_OK(status)) {
3632 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3635 ret = ldb_dn_set_extended_component(dn, component_name, &v);
3636 data_blob_free(&v);
3637 return ret;
3641 return a GUID from a extended DN structure
3643 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3645 const struct ldb_val *v;
3647 v = ldb_dn_get_extended_component(dn, component_name);
3648 if (v == NULL) {
3649 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3652 return GUID_from_ndr_blob(v, guid);
3656 return a uint64_t from a extended DN structure
3658 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3660 const struct ldb_val *v;
3662 v = ldb_dn_get_extended_component(dn, component_name);
3663 if (v == NULL) {
3664 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3668 char s[v->length+1];
3669 memcpy(s, v->data, v->length);
3670 s[v->length] = 0;
3672 *val = strtoull(s, NULL, 0);
3674 return NT_STATUS_OK;
3678 return a NTTIME from a extended DN structure
3680 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3682 return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3686 return a uint32_t from a extended DN structure
3688 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3690 const struct ldb_val *v;
3692 v = ldb_dn_get_extended_component(dn, component_name);
3693 if (v == NULL) {
3694 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3698 char s[v->length + 1];
3699 memcpy(s, v->data, v->length);
3700 s[v->length] = 0;
3701 *val = strtoul(s, NULL, 0);
3704 return NT_STATUS_OK;
3708 return a dom_sid from a extended DN structure
3710 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3712 const struct ldb_val *sid_blob;
3713 enum ndr_err_code ndr_err;
3715 sid_blob = ldb_dn_get_extended_component(dn, component_name);
3716 if (!sid_blob) {
3717 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3720 ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
3721 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3722 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3723 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3724 return status;
3727 return NT_STATUS_OK;
3732 return RMD_FLAGS directly from a ldb_dn
3733 returns 0 if not found
3735 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3737 const struct ldb_val *v;
3738 char buf[32];
3739 v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
3740 if (!v || v->length > sizeof(buf)-1) return 0;
3741 strncpy(buf, (const char *)v->data, v->length);
3742 buf[v->length] = 0;
3743 return strtoul(buf, NULL, 10);
3747 return RMD_FLAGS directly from a ldb_val for a DN
3748 returns 0 if RMD_FLAGS is not found
3750 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3752 const char *p;
3753 uint32_t flags;
3754 char *end;
3756 if (val->length < 13) {
3757 return 0;
3759 p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3760 if (!p) {
3761 return 0;
3763 flags = strtoul(p+11, &end, 10);
3764 if (!end || *end != '>') {
3765 /* it must end in a > */
3766 return 0;
3768 return flags;
3772 return true if a ldb_val containing a DN in storage form is deleted
3774 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3776 return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3780 return true if a ldb_val containing a DN in storage form is
3781 in the upgraded w2k3 linked attribute format
3783 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
3785 return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
3789 return a DN for a wellknown GUID
3791 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3792 struct ldb_dn *nc_root, const char *wk_guid,
3793 struct ldb_dn **wkguid_dn)
3795 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3796 const char *attrs[] = { NULL };
3797 int ret;
3798 struct ldb_dn *dn;
3799 struct ldb_result *res;
3801 /* construct the magic WKGUID DN */
3802 dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3803 wk_guid, ldb_dn_get_linearized(nc_root));
3804 if (!wkguid_dn) {
3805 talloc_free(tmp_ctx);
3806 return ldb_operr(samdb);
3809 ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
3810 DSDB_SEARCH_SHOW_DELETED |
3811 DSDB_SEARCH_SHOW_RECYCLED);
3812 if (ret != LDB_SUCCESS) {
3813 talloc_free(tmp_ctx);
3814 return ret;
3817 (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3818 talloc_free(tmp_ctx);
3819 return LDB_SUCCESS;
3823 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3825 return ldb_dn_compare(*dn1, *dn2);
3829 find a NC root given a DN within the NC
3831 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3832 struct ldb_dn **nc_root)
3834 const char *root_attrs[] = { "namingContexts", NULL };
3835 TALLOC_CTX *tmp_ctx;
3836 int ret;
3837 struct ldb_message_element *el;
3838 struct ldb_result *root_res;
3839 unsigned int i;
3840 struct ldb_dn **nc_dns;
3842 tmp_ctx = talloc_new(samdb);
3843 if (tmp_ctx == NULL) {
3844 return ldb_oom(samdb);
3847 ret = ldb_search(samdb, tmp_ctx, &root_res,
3848 ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3849 if (ret != LDB_SUCCESS || root_res->count == 0) {
3850 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3851 talloc_free(tmp_ctx);
3852 return ret;
3855 el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3856 if ((el == NULL) || (el->num_values < 3)) {
3857 struct ldb_message *tmp_msg;
3859 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list."));
3861 /* This generates a temporary list of NCs in order to let the
3862 * provisioning work. */
3863 tmp_msg = ldb_msg_new(tmp_ctx);
3864 if (tmp_msg == NULL) {
3865 talloc_free(tmp_ctx);
3866 return ldb_oom(samdb);
3868 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3869 ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
3870 if (ret != LDB_SUCCESS) {
3871 talloc_free(tmp_ctx);
3872 return ret;
3874 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3875 ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
3876 if (ret != LDB_SUCCESS) {
3877 talloc_free(tmp_ctx);
3878 return ret;
3880 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3881 ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
3882 if (ret != LDB_SUCCESS) {
3883 talloc_free(tmp_ctx);
3884 return ret;
3886 el = &tmp_msg->elements[0];
3889 nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3890 if (!nc_dns) {
3891 talloc_free(tmp_ctx);
3892 return ldb_oom(samdb);
3895 for (i=0; i<el->num_values; i++) {
3896 nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3897 if (nc_dns[i] == NULL) {
3898 talloc_free(tmp_ctx);
3899 return ldb_operr(samdb);
3903 TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3905 for (i=0; i<el->num_values; i++) {
3906 if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3907 (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3908 talloc_free(tmp_ctx);
3909 return LDB_SUCCESS;
3913 talloc_free(tmp_ctx);
3914 return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3919 find the deleted objects DN for any object, by looking for the NC
3920 root, then looking up the wellknown GUID
3922 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3923 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3924 struct ldb_dn **do_dn)
3926 struct ldb_dn *nc_root;
3927 int ret;
3929 ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3930 if (ret != LDB_SUCCESS) {
3931 return ret;
3934 ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3935 talloc_free(nc_root);
3936 return ret;
3940 return the tombstoneLifetime, in days
3942 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3944 struct ldb_dn *dn;
3945 dn = ldb_get_config_basedn(ldb);
3946 if (!dn) {
3947 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3949 dn = ldb_dn_copy(ldb, dn);
3950 if (!dn) {
3951 return ldb_operr(ldb);
3953 /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3954 be a wellknown GUID for this */
3955 if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3956 talloc_free(dn);
3957 return ldb_operr(ldb);
3960 *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3961 talloc_free(dn);
3962 return LDB_SUCCESS;
3966 compare a ldb_val to a string case insensitively
3968 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3970 size_t len = strlen(s);
3971 int ret;
3972 if (len > v->length) return 1;
3973 ret = strncasecmp(s, (const char *)v->data, v->length);
3974 if (ret != 0) return ret;
3975 if (v->length > len && v->data[len] != 0) {
3976 return -1;
3978 return 0;
3983 load the UDV for a partition in v2 format
3984 The list is returned sorted, and with our local cursor added
3986 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3987 struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3989 static const char *attrs[] = { "replUpToDateVector", NULL };
3990 struct ldb_result *r;
3991 const struct ldb_val *ouv_value;
3992 unsigned int i;
3993 int ret;
3994 uint64_t highest_usn = 0;
3995 const struct GUID *our_invocation_id;
3996 static const struct timeval tv1970;
3997 NTTIME nt1970 = timeval_to_nttime(&tv1970);
3999 ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
4000 if (ret != LDB_SUCCESS) {
4001 return ret;
4004 ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
4005 if (ouv_value) {
4006 enum ndr_err_code ndr_err;
4007 struct replUpToDateVectorBlob ouv;
4009 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
4010 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
4011 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4012 talloc_free(r);
4013 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4015 if (ouv.version != 2) {
4016 /* we always store as version 2, and
4017 * replUpToDateVector is not replicated
4019 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4022 *count = ouv.ctr.ctr2.count;
4023 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
4024 } else {
4025 *count = 0;
4026 *cursors = NULL;
4029 talloc_free(r);
4031 our_invocation_id = samdb_ntds_invocation_id(samdb);
4032 if (!our_invocation_id) {
4033 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
4034 talloc_free(*cursors);
4035 return ldb_operr(samdb);
4038 ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
4039 if (ret != LDB_SUCCESS) {
4040 /* nothing to add - this can happen after a vampire */
4041 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4042 return LDB_SUCCESS;
4045 for (i=0; i<*count; i++) {
4046 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
4047 (*cursors)[i].highest_usn = highest_usn;
4048 (*cursors)[i].last_sync_success = nt1970;
4049 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4050 return LDB_SUCCESS;
4054 (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
4055 if (! *cursors) {
4056 return ldb_oom(samdb);
4059 (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
4060 (*cursors)[*count].highest_usn = highest_usn;
4061 (*cursors)[*count].last_sync_success = nt1970;
4062 (*count)++;
4064 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4066 return LDB_SUCCESS;
4070 load the UDV for a partition in version 1 format
4071 The list is returned sorted, and with our local cursor added
4073 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4074 struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
4076 struct drsuapi_DsReplicaCursor2 *v2;
4077 uint32_t i;
4078 int ret;
4080 ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
4081 if (ret != LDB_SUCCESS) {
4082 return ret;
4085 if (*count == 0) {
4086 talloc_free(v2);
4087 *cursors = NULL;
4088 return LDB_SUCCESS;
4091 *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
4092 if (*cursors == NULL) {
4093 talloc_free(v2);
4094 return ldb_oom(samdb);
4097 for (i=0; i<*count; i++) {
4098 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
4099 (*cursors)[i].highest_usn = v2[i].highest_usn;
4101 talloc_free(v2);
4102 return LDB_SUCCESS;
4106 add a set of controls to a ldb_request structure based on a set of
4107 flags. See util.h for a list of available flags
4109 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
4111 int ret;
4112 if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
4113 struct ldb_search_options_control *options;
4114 /* Using the phantom root control allows us to search all partitions */
4115 options = talloc(req, struct ldb_search_options_control);
4116 if (options == NULL) {
4117 return LDB_ERR_OPERATIONS_ERROR;
4119 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
4121 ret = ldb_request_add_control(req,
4122 LDB_CONTROL_SEARCH_OPTIONS_OID,
4123 true, options);
4124 if (ret != LDB_SUCCESS) {
4125 return ret;
4129 if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
4130 ret = ldb_request_add_control(req,
4131 DSDB_CONTROL_NO_GLOBAL_CATALOG,
4132 false, NULL);
4133 if (ret != LDB_SUCCESS) {
4134 return ret;
4138 if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
4139 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
4140 if (ret != LDB_SUCCESS) {
4141 return ret;
4145 if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
4146 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
4147 if (ret != LDB_SUCCESS) {
4148 return ret;
4152 if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
4153 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
4154 if (ret != LDB_SUCCESS) {
4155 return ret;
4159 if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
4160 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
4161 if (!extended_ctrl) {
4162 return LDB_ERR_OPERATIONS_ERROR;
4164 extended_ctrl->type = 1;
4166 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
4167 if (ret != LDB_SUCCESS) {
4168 return ret;
4172 if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
4173 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
4174 if (ret != LDB_SUCCESS) {
4175 return ret;
4179 if (dsdb_flags & DSDB_MODIFY_RELAX) {
4180 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
4181 if (ret != LDB_SUCCESS) {
4182 return ret;
4186 if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
4187 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
4188 if (ret != LDB_SUCCESS) {
4189 return ret;
4193 if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
4194 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
4195 if (ret != LDB_SUCCESS) {
4196 return ret;
4200 if (dsdb_flags & DSDB_TREE_DELETE) {
4201 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
4202 if (ret != LDB_SUCCESS) {
4203 return ret;
4207 if (dsdb_flags & DSDB_PROVISION) {
4208 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
4209 if (ret != LDB_SUCCESS) {
4210 return ret;
4214 /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
4215 if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
4216 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
4217 if (ret != LDB_SUCCESS) {
4218 return ret;
4222 if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
4224 * This must not be critical, as it will only be
4225 * handled (and need to be handled) if the other
4226 * attributes in the request bring password_hash into
4227 * action
4229 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
4230 if (ret != LDB_SUCCESS) {
4231 return ret;
4235 if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
4236 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
4237 if (ret != LDB_SUCCESS) {
4238 return ret;
4242 return LDB_SUCCESS;
4246 an add with a set of controls
4248 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
4249 uint32_t dsdb_flags)
4251 struct ldb_request *req;
4252 int ret;
4254 ret = ldb_build_add_req(&req, ldb, ldb,
4255 message,
4256 NULL,
4257 NULL,
4258 ldb_op_default_callback,
4259 NULL);
4261 if (ret != LDB_SUCCESS) return ret;
4263 ret = dsdb_request_add_controls(req, dsdb_flags);
4264 if (ret != LDB_SUCCESS) {
4265 talloc_free(req);
4266 return ret;
4269 ret = dsdb_autotransaction_request(ldb, req);
4271 talloc_free(req);
4272 return ret;
4276 a modify with a set of controls
4278 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
4279 uint32_t dsdb_flags)
4281 struct ldb_request *req;
4282 int ret;
4284 ret = ldb_build_mod_req(&req, ldb, ldb,
4285 message,
4286 NULL,
4287 NULL,
4288 ldb_op_default_callback,
4289 NULL);
4291 if (ret != LDB_SUCCESS) return ret;
4293 ret = dsdb_request_add_controls(req, dsdb_flags);
4294 if (ret != LDB_SUCCESS) {
4295 talloc_free(req);
4296 return ret;
4299 ret = dsdb_autotransaction_request(ldb, req);
4301 talloc_free(req);
4302 return ret;
4306 a delete with a set of flags
4308 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
4309 uint32_t dsdb_flags)
4311 struct ldb_request *req;
4312 int ret;
4314 ret = ldb_build_del_req(&req, ldb, ldb,
4316 NULL,
4317 NULL,
4318 ldb_op_default_callback,
4319 NULL);
4321 if (ret != LDB_SUCCESS) return ret;
4323 ret = dsdb_request_add_controls(req, dsdb_flags);
4324 if (ret != LDB_SUCCESS) {
4325 talloc_free(req);
4326 return ret;
4329 ret = dsdb_autotransaction_request(ldb, req);
4331 talloc_free(req);
4332 return ret;
4336 like dsdb_modify() but set all the element flags to
4337 LDB_FLAG_MOD_REPLACE
4339 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
4341 unsigned int i;
4343 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
4344 for (i=0;i<msg->num_elements;i++) {
4345 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
4348 return dsdb_modify(ldb, msg, dsdb_flags);
4353 search for attrs on one DN, allowing for dsdb_flags controls
4355 int dsdb_search_dn(struct ldb_context *ldb,
4356 TALLOC_CTX *mem_ctx,
4357 struct ldb_result **_result,
4358 struct ldb_dn *basedn,
4359 const char * const *attrs,
4360 uint32_t dsdb_flags)
4362 int ret;
4363 struct ldb_request *req;
4364 struct ldb_result *res;
4366 res = talloc_zero(mem_ctx, struct ldb_result);
4367 if (!res) {
4368 return ldb_oom(ldb);
4371 ret = ldb_build_search_req(&req, ldb, res,
4372 basedn,
4373 LDB_SCOPE_BASE,
4374 NULL,
4375 attrs,
4376 NULL,
4377 res,
4378 ldb_search_default_callback,
4379 NULL);
4380 if (ret != LDB_SUCCESS) {
4381 talloc_free(res);
4382 return ret;
4385 ret = dsdb_request_add_controls(req, dsdb_flags);
4386 if (ret != LDB_SUCCESS) {
4387 talloc_free(res);
4388 return ret;
4391 ret = ldb_request(ldb, req);
4392 if (ret == LDB_SUCCESS) {
4393 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4396 talloc_free(req);
4397 if (ret != LDB_SUCCESS) {
4398 talloc_free(res);
4399 return ret;
4402 *_result = res;
4403 return LDB_SUCCESS;
4407 search for attrs on one DN, by the GUID of the DN, allowing for
4408 dsdb_flags controls
4410 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
4411 TALLOC_CTX *mem_ctx,
4412 struct ldb_result **_result,
4413 const struct GUID *guid,
4414 const char * const *attrs,
4415 uint32_t dsdb_flags)
4417 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4418 struct ldb_dn *dn;
4419 int ret;
4421 dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
4422 if (dn == NULL) {
4423 talloc_free(tmp_ctx);
4424 return ldb_oom(ldb);
4427 ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
4428 talloc_free(tmp_ctx);
4429 return ret;
4433 general search with dsdb_flags for controls
4435 int dsdb_search(struct ldb_context *ldb,
4436 TALLOC_CTX *mem_ctx,
4437 struct ldb_result **_result,
4438 struct ldb_dn *basedn,
4439 enum ldb_scope scope,
4440 const char * const *attrs,
4441 uint32_t dsdb_flags,
4442 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4444 int ret;
4445 struct ldb_request *req;
4446 struct ldb_result *res;
4447 va_list ap;
4448 char *expression = NULL;
4449 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4451 /* cross-partitions searches with a basedn break multi-domain support */
4452 SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
4454 res = talloc_zero(tmp_ctx, struct ldb_result);
4455 if (!res) {
4456 talloc_free(tmp_ctx);
4457 return ldb_oom(ldb);
4460 if (exp_fmt) {
4461 va_start(ap, exp_fmt);
4462 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4463 va_end(ap);
4465 if (!expression) {
4466 talloc_free(tmp_ctx);
4467 return ldb_oom(ldb);
4471 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
4472 basedn,
4473 scope,
4474 expression,
4475 attrs,
4476 NULL,
4477 res,
4478 ldb_search_default_callback,
4479 NULL);
4480 if (ret != LDB_SUCCESS) {
4481 talloc_free(tmp_ctx);
4482 return ret;
4485 ret = dsdb_request_add_controls(req, dsdb_flags);
4486 if (ret != LDB_SUCCESS) {
4487 talloc_free(tmp_ctx);
4488 ldb_reset_err_string(ldb);
4489 return ret;
4492 ret = ldb_request(ldb, req);
4493 if (ret == LDB_SUCCESS) {
4494 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4497 if (ret != LDB_SUCCESS) {
4498 talloc_free(tmp_ctx);
4499 return ret;
4502 if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
4503 if (res->count == 0) {
4504 talloc_free(tmp_ctx);
4505 ldb_reset_err_string(ldb);
4506 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4508 if (res->count != 1) {
4509 talloc_free(tmp_ctx);
4510 ldb_reset_err_string(ldb);
4511 return LDB_ERR_CONSTRAINT_VIOLATION;
4515 *_result = talloc_steal(mem_ctx, res);
4516 talloc_free(tmp_ctx);
4518 return LDB_SUCCESS;
4523 general search with dsdb_flags for controls
4524 returns exactly 1 record or an error
4526 int dsdb_search_one(struct ldb_context *ldb,
4527 TALLOC_CTX *mem_ctx,
4528 struct ldb_message **msg,
4529 struct ldb_dn *basedn,
4530 enum ldb_scope scope,
4531 const char * const *attrs,
4532 uint32_t dsdb_flags,
4533 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4535 int ret;
4536 struct ldb_result *res;
4537 va_list ap;
4538 char *expression = NULL;
4539 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4541 dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4543 res = talloc_zero(tmp_ctx, struct ldb_result);
4544 if (!res) {
4545 talloc_free(tmp_ctx);
4546 return ldb_oom(ldb);
4549 if (exp_fmt) {
4550 va_start(ap, exp_fmt);
4551 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4552 va_end(ap);
4554 if (!expression) {
4555 talloc_free(tmp_ctx);
4556 return ldb_oom(ldb);
4558 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4559 dsdb_flags, "%s", expression);
4560 } else {
4561 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4562 dsdb_flags, NULL);
4565 if (ret != LDB_SUCCESS) {
4566 talloc_free(tmp_ctx);
4567 return ret;
4570 *msg = talloc_steal(mem_ctx, res->msgs[0]);
4571 talloc_free(tmp_ctx);
4573 return LDB_SUCCESS;
4576 /* returns back the forest DNS name */
4577 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4579 const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4580 ldb_get_root_basedn(ldb));
4581 char *p;
4583 if (forest_name == NULL) {
4584 return NULL;
4587 p = strchr(forest_name, '/');
4588 if (p) {
4589 *p = '\0';
4592 return forest_name;
4595 /* returns back the default domain DNS name */
4596 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4598 const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4599 ldb_get_default_basedn(ldb));
4600 char *p;
4602 if (domain_name == NULL) {
4603 return NULL;
4606 p = strchr(domain_name, '/');
4607 if (p) {
4608 *p = '\0';
4611 return domain_name;
4615 validate that an DSA GUID belongs to the specified user sid.
4616 The user SID must be a domain controller account (either RODC or
4617 RWDC)
4619 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4620 const struct GUID *dsa_guid,
4621 const struct dom_sid *sid)
4623 /* strategy:
4624 - find DN of record with the DSA GUID in the
4625 configuration partition (objectGUID)
4626 - remove "NTDS Settings" component from DN
4627 - do a base search on that DN for serverReference with
4628 extended-dn enabled
4629 - extract objectSid from resulting serverReference
4630 attribute
4631 - check this sid matches the sid argument
4633 struct ldb_dn *config_dn;
4634 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4635 struct ldb_message *msg;
4636 const char *attrs1[] = { NULL };
4637 const char *attrs2[] = { "serverReference", NULL };
4638 int ret;
4639 struct ldb_dn *dn, *account_dn;
4640 struct dom_sid sid2;
4641 NTSTATUS status;
4643 config_dn = ldb_get_config_basedn(ldb);
4645 ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4646 attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4647 if (ret != LDB_SUCCESS) {
4648 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4649 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4650 talloc_free(tmp_ctx);
4651 return ldb_operr(ldb);
4653 dn = msg->dn;
4655 if (!ldb_dn_remove_child_components(dn, 1)) {
4656 talloc_free(tmp_ctx);
4657 return ldb_operr(ldb);
4660 ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4661 attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4662 "(objectClass=server)");
4663 if (ret != LDB_SUCCESS) {
4664 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4665 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4666 talloc_free(tmp_ctx);
4667 return ldb_operr(ldb);
4670 account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4671 if (account_dn == NULL) {
4672 DEBUG(1,(__location__ ": Failed to find account dn "
4673 "(serverReference) for %s, parent of DSA with "
4674 "objectGUID %s, sid %s\n",
4675 ldb_dn_get_linearized(msg->dn),
4676 GUID_string(tmp_ctx, dsa_guid),
4677 dom_sid_string(tmp_ctx, sid)));
4678 talloc_free(tmp_ctx);
4679 return ldb_operr(ldb);
4682 status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4683 if (!NT_STATUS_IS_OK(status)) {
4684 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4685 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4686 talloc_free(tmp_ctx);
4687 return ldb_operr(ldb);
4690 if (!dom_sid_equal(sid, &sid2)) {
4691 /* someone is trying to spoof another account */
4692 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4693 GUID_string(tmp_ctx, dsa_guid),
4694 dom_sid_string(tmp_ctx, sid),
4695 dom_sid_string(tmp_ctx, &sid2)));
4696 talloc_free(tmp_ctx);
4697 return ldb_operr(ldb);
4700 talloc_free(tmp_ctx);
4701 return LDB_SUCCESS;
4704 static const char * const secret_attributes[] = {
4705 DSDB_SECRET_ATTRIBUTES,
4706 NULL
4710 check if the attribute belongs to the RODC filtered attribute set
4711 Note that attributes that are in the filtered attribute set are the
4712 ones that _are_ always sent to a RODC
4714 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4716 /* they never get secret attributes */
4717 if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4718 return false;
4721 /* they do get non-secret critical attributes */
4722 if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4723 return true;
4726 /* they do get non-secret attributes marked as being in the FAS */
4727 if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4728 return true;
4731 /* other attributes are denied */
4732 return false;
4735 /* return fsmo role dn and role owner dn for a particular role*/
4736 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4737 struct ldb_context *ldb,
4738 uint32_t role,
4739 struct ldb_dn **fsmo_role_dn,
4740 struct ldb_dn **role_owner_dn)
4742 int ret;
4743 switch (role) {
4744 case DREPL_NAMING_MASTER:
4745 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4746 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4747 if (ret != LDB_SUCCESS) {
4748 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4749 ldb_errstring(ldb)));
4750 talloc_free(tmp_ctx);
4751 return WERR_DS_DRA_INTERNAL_ERROR;
4753 break;
4754 case DREPL_INFRASTRUCTURE_MASTER:
4755 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4756 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4757 if (ret != LDB_SUCCESS) {
4758 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4759 ldb_errstring(ldb)));
4760 talloc_free(tmp_ctx);
4761 return WERR_DS_DRA_INTERNAL_ERROR;
4763 break;
4764 case DREPL_RID_MASTER:
4765 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
4766 if (ret != LDB_SUCCESS) {
4767 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
4768 talloc_free(tmp_ctx);
4769 return WERR_DS_DRA_INTERNAL_ERROR;
4772 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4773 if (ret != LDB_SUCCESS) {
4774 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
4775 ldb_errstring(ldb)));
4776 talloc_free(tmp_ctx);
4777 return WERR_DS_DRA_INTERNAL_ERROR;
4779 break;
4780 case DREPL_SCHEMA_MASTER:
4781 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
4782 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4783 if (ret != LDB_SUCCESS) {
4784 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4785 ldb_errstring(ldb)));
4786 talloc_free(tmp_ctx);
4787 return WERR_DS_DRA_INTERNAL_ERROR;
4789 break;
4790 case DREPL_PDC_MASTER:
4791 *fsmo_role_dn = ldb_get_default_basedn(ldb);
4792 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4793 if (ret != LDB_SUCCESS) {
4794 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
4795 ldb_errstring(ldb)));
4796 talloc_free(tmp_ctx);
4797 return WERR_DS_DRA_INTERNAL_ERROR;
4799 break;
4800 default:
4801 return WERR_DS_DRA_INTERNAL_ERROR;
4803 return WERR_OK;
4806 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
4807 TALLOC_CTX *mem_ctx,
4808 struct ldb_dn *server_dn)
4810 int ldb_ret;
4811 struct ldb_result *res = NULL;
4812 const char * const attrs[] = { "dNSHostName", NULL};
4814 ldb_ret = ldb_search(ldb, mem_ctx, &res,
4815 server_dn,
4816 LDB_SCOPE_BASE,
4817 attrs, NULL);
4818 if (ldb_ret != LDB_SUCCESS) {
4819 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
4820 ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
4821 return NULL;
4824 return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
4828 returns true if an attribute is in the filter,
4829 false otherwise, provided that attribute value is provided with the expression
4831 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
4832 const char *attr)
4834 unsigned int i;
4835 switch (tree->operation) {
4836 case LDB_OP_AND:
4837 case LDB_OP_OR:
4838 for (i=0;i<tree->u.list.num_elements;i++) {
4839 if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
4840 attr))
4841 return true;
4843 return false;
4844 case LDB_OP_NOT:
4845 return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
4846 case LDB_OP_EQUALITY:
4847 case LDB_OP_GREATER:
4848 case LDB_OP_LESS:
4849 case LDB_OP_APPROX:
4850 if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
4851 return true;
4853 return false;
4854 case LDB_OP_SUBSTRING:
4855 if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
4856 return true;
4858 return false;
4859 case LDB_OP_PRESENT:
4860 /* (attrname=*) is not filtered out */
4861 return false;
4862 case LDB_OP_EXTENDED:
4863 if (tree->u.extended.attr &&
4864 ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
4865 return true;
4867 return false;
4869 return false;
4872 bool is_attr_in_list(const char * const * attrs, const char *attr)
4874 unsigned int i;
4876 for (i = 0; attrs[i]; i++) {
4877 if (ldb_attr_cmp(attrs[i], attr) == 0)
4878 return true;
4881 return false;
4884 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
4885 const char *location, const char *func,
4886 const char *reason)
4888 if (reason == NULL) {
4889 reason = win_errstr(werr);
4891 ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
4892 W_ERROR_V(werr), reason, location, func);
4893 return ldb_ecode;
4897 map an ldb error code to an approximate NTSTATUS code
4899 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
4901 switch (err) {
4902 case LDB_SUCCESS:
4903 return NT_STATUS_OK;
4905 case LDB_ERR_PROTOCOL_ERROR:
4906 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
4908 case LDB_ERR_TIME_LIMIT_EXCEEDED:
4909 return NT_STATUS_IO_TIMEOUT;
4911 case LDB_ERR_SIZE_LIMIT_EXCEEDED:
4912 return NT_STATUS_BUFFER_TOO_SMALL;
4914 case LDB_ERR_COMPARE_FALSE:
4915 case LDB_ERR_COMPARE_TRUE:
4916 return NT_STATUS_REVISION_MISMATCH;
4918 case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
4919 return NT_STATUS_NOT_SUPPORTED;
4921 case LDB_ERR_STRONG_AUTH_REQUIRED:
4922 case LDB_ERR_CONFIDENTIALITY_REQUIRED:
4923 case LDB_ERR_SASL_BIND_IN_PROGRESS:
4924 case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
4925 case LDB_ERR_INVALID_CREDENTIALS:
4926 case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
4927 case LDB_ERR_UNWILLING_TO_PERFORM:
4928 return NT_STATUS_ACCESS_DENIED;
4930 case LDB_ERR_NO_SUCH_OBJECT:
4931 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4933 case LDB_ERR_REFERRAL:
4934 case LDB_ERR_NO_SUCH_ATTRIBUTE:
4935 return NT_STATUS_NOT_FOUND;
4937 case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
4938 return NT_STATUS_NOT_SUPPORTED;
4940 case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
4941 return NT_STATUS_BUFFER_TOO_SMALL;
4943 case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
4944 case LDB_ERR_INAPPROPRIATE_MATCHING:
4945 case LDB_ERR_CONSTRAINT_VIOLATION:
4946 case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
4947 case LDB_ERR_INVALID_DN_SYNTAX:
4948 case LDB_ERR_NAMING_VIOLATION:
4949 case LDB_ERR_OBJECT_CLASS_VIOLATION:
4950 case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
4951 case LDB_ERR_NOT_ALLOWED_ON_RDN:
4952 return NT_STATUS_INVALID_PARAMETER;
4954 case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
4955 case LDB_ERR_ENTRY_ALREADY_EXISTS:
4956 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
4958 case LDB_ERR_BUSY:
4959 return NT_STATUS_NETWORK_BUSY;
4961 case LDB_ERR_ALIAS_PROBLEM:
4962 case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
4963 case LDB_ERR_UNAVAILABLE:
4964 case LDB_ERR_LOOP_DETECT:
4965 case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
4966 case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
4967 case LDB_ERR_OTHER:
4968 case LDB_ERR_OPERATIONS_ERROR:
4969 break;
4971 return NT_STATUS_UNSUCCESSFUL;
4976 create a new naming context that will hold a partial replica
4978 int dsdb_create_partial_replica_NC(struct ldb_context *ldb, struct ldb_dn *dn)
4980 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4981 struct ldb_message *msg;
4982 int ret;
4984 msg = ldb_msg_new(tmp_ctx);
4985 if (msg == NULL) {
4986 talloc_free(tmp_ctx);
4987 return ldb_oom(ldb);
4990 msg->dn = dn;
4991 ret = ldb_msg_add_string(msg, "objectClass", "top");
4992 if (ret != LDB_SUCCESS) {
4993 talloc_free(tmp_ctx);
4994 return ldb_oom(ldb);
4997 /* [MS-DRSR] implies that we should only add the 'top'
4998 * objectclass, but that would cause lots of problems with our
4999 * objectclass code as top is not structural, so we add
5000 * 'domainDNS' as well to keep things sane. We're expecting
5001 * this new NC to be of objectclass domainDNS after
5002 * replication anyway
5004 ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
5005 if (ret != LDB_SUCCESS) {
5006 talloc_free(tmp_ctx);
5007 return ldb_oom(ldb);
5010 ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
5011 INSTANCE_TYPE_IS_NC_HEAD|
5012 INSTANCE_TYPE_NC_ABOVE|
5013 INSTANCE_TYPE_UNINSTANT);
5014 if (ret != LDB_SUCCESS) {
5015 talloc_free(tmp_ctx);
5016 return ldb_oom(ldb);
5019 ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
5020 if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
5021 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
5022 ldb_dn_get_linearized(dn),
5023 ldb_errstring(ldb), ldb_strerror(ret)));
5024 talloc_free(tmp_ctx);
5025 return ret;
5028 DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
5030 talloc_free(tmp_ctx);
5031 return LDB_SUCCESS;
5035 build a GUID from a string
5037 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
5039 NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
5040 uint32_t time_low;
5041 uint32_t time_mid, time_hi_and_version;
5042 uint32_t clock_seq[2];
5043 uint32_t node[6];
5044 int i;
5046 if (s == NULL) {
5047 return NT_STATUS_INVALID_PARAMETER;
5050 if (11 == sscanf(s, "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5051 &time_low, &time_mid, &time_hi_and_version,
5052 &clock_seq[0], &clock_seq[1],
5053 &node[0], &node[1], &node[2], &node[3], &node[4], &node[5])) {
5054 status = NT_STATUS_OK;
5057 if (!NT_STATUS_IS_OK(status)) {
5058 return status;
5061 guid->time_low = time_low;
5062 guid->time_mid = time_mid;
5063 guid->time_hi_and_version = time_hi_and_version;
5064 guid->clock_seq[0] = clock_seq[0];
5065 guid->clock_seq[1] = clock_seq[1];
5066 for (i=0;i<6;i++) {
5067 guid->node[i] = node[i];
5070 return NT_STATUS_OK;
5073 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
5075 return talloc_asprintf(mem_ctx,
5076 "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5077 guid->time_low, guid->time_mid,
5078 guid->time_hi_and_version,
5079 guid->clock_seq[0],
5080 guid->clock_seq[1],
5081 guid->node[0], guid->node[1],
5082 guid->node[2], guid->node[3],
5083 guid->node[4], guid->node[5]);
5087 * Return the effective badPwdCount
5089 * This requires that the user_msg have (if present):
5090 * - badPasswordTime
5091 * - badPwdCount
5093 * This also requires that the domain_msg have (if present):
5094 * - lockOutObservationWindow
5096 static int dsdb_effective_badPwdCount(struct ldb_message *user_msg,
5097 int64_t lockOutObservationWindow,
5098 NTTIME now)
5100 int64_t badPasswordTime;
5101 badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
5103 if (badPasswordTime - lockOutObservationWindow >= now) {
5104 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
5105 } else {
5106 return 0;
5111 * Return the effective badPwdCount
5113 * This requires that the user_msg have (if present):
5114 * - badPasswordTime
5115 * - badPwdCount
5118 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
5119 TALLOC_CTX *mem_ctx,
5120 struct ldb_dn *domain_dn,
5121 struct ldb_message *user_msg)
5123 struct timeval tv_now = timeval_current();
5124 NTTIME now = timeval_to_nttime(&tv_now);
5125 int64_t lockOutObservationWindow = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
5126 "lockOutObservationWindow", NULL);
5127 return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5131 * Prepare an update to the badPwdCount and associated attributes.
5133 * This requires that the user_msg have (if present):
5134 * - objectSid
5135 * - badPasswordTime
5136 * - badPwdCount
5138 * This also requires that the domain_msg have (if present):
5139 * - pwdProperties
5140 * - lockoutThreshold
5141 * - lockOutObservationWindow
5143 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
5144 struct ldb_context *sam_ctx,
5145 struct ldb_message *user_msg,
5146 struct ldb_message *domain_msg,
5147 struct ldb_message **_mod_msg)
5149 int i, ret, badPwdCount;
5150 int64_t lockoutThreshold, lockOutObservationWindow;
5151 struct dom_sid *sid;
5152 struct timeval tv_now = timeval_current();
5153 NTTIME now = timeval_to_nttime(&tv_now);
5154 NTSTATUS status;
5155 uint32_t pwdProperties, rid = 0;
5156 struct ldb_message *mod_msg;
5158 sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
5160 pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
5161 "pwdProperties", -1);
5162 if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
5163 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
5164 if (!NT_STATUS_IS_OK(status)) {
5166 * This can't happen anyway, but always try
5167 * and update the badPwdCount on failure
5169 rid = 0;
5172 TALLOC_FREE(sid);
5175 * Work out if we are doing password lockout on the domain.
5176 * Also, the built in administrator account is exempt:
5177 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
5179 lockoutThreshold = ldb_msg_find_attr_as_int(domain_msg,
5180 "lockoutThreshold", 0);
5181 if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
5182 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
5183 ldb_dn_get_linearized(user_msg->dn)));
5184 return NT_STATUS_OK;
5187 mod_msg = ldb_msg_new(mem_ctx);
5188 if (mod_msg == NULL) {
5189 return NT_STATUS_NO_MEMORY;
5191 mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
5192 if (mod_msg->dn == NULL) {
5193 TALLOC_FREE(mod_msg);
5194 return NT_STATUS_NO_MEMORY;
5197 lockOutObservationWindow = ldb_msg_find_attr_as_int64(domain_msg,
5198 "lockOutObservationWindow", 0);
5200 badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5202 badPwdCount++;
5204 ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
5205 if (ret != LDB_SUCCESS) {
5206 TALLOC_FREE(mod_msg);
5207 return NT_STATUS_NO_MEMORY;
5209 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
5210 if (ret != LDB_SUCCESS) {
5211 TALLOC_FREE(mod_msg);
5212 return NT_STATUS_NO_MEMORY;
5215 if (badPwdCount >= lockoutThreshold) {
5216 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
5217 if (ret != LDB_SUCCESS) {
5218 TALLOC_FREE(mod_msg);
5219 return NT_STATUS_NO_MEMORY;
5221 DEBUG(5, ("Locked out user %s after %d wrong passwords\n",
5222 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5223 } else {
5224 DEBUG(5, ("Updated badPwdCount on %s after %d wrong passwords\n",
5225 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5228 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5229 for (i=0; i< mod_msg->num_elements; i++) {
5230 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5233 *_mod_msg = mod_msg;
5234 return NT_STATUS_OK;
5238 * Sets defaults for a User object
5239 * List of default attributes set:
5240 * accountExpires, badPasswordTime, badPwdCount,
5241 * codePage, countryCode, lastLogoff, lastLogon
5242 * logonCount, pwdLastSet
5244 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
5245 struct ldb_message *usr_obj,
5246 struct ldb_request *req)
5248 int i, ret;
5249 const struct attribute_values {
5250 const char *name;
5251 const char *value;
5252 const char *add_control;
5253 } map[] = {
5255 .name = "accountExpires",
5256 .value = "9223372036854775807"
5259 .name = "badPasswordTime",
5260 .value = "0"
5263 .name = "badPwdCount",
5264 .value = "0"
5267 .name = "codePage",
5268 .value = "0"
5271 .name = "countryCode",
5272 .value = "0"
5275 .name = "lastLogoff",
5276 .value = "0"
5279 .name = "lastLogon",
5280 .value = "0"
5283 .name = "logonCount",
5284 .value = "0"
5287 .name = "pwdLastSet",
5288 .value = "0",
5289 .add_control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
5293 for (i = 0; i < ARRAY_SIZE(map); i++) {
5294 bool added = false;
5296 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
5297 map[i].name,
5298 map[i].value,
5299 &added);
5300 if (ret != LDB_SUCCESS) {
5301 return ret;
5304 if (req != NULL && added && map[i].add_control != NULL) {
5305 ret = ldb_request_add_control(req,
5306 map[i].add_control,
5307 false, NULL);
5308 if (ret != LDB_SUCCESS) {
5309 return ret;
5314 return LDB_SUCCESS;
5318 * Sets 'sAMAccountType on user object based on userAccountControl
5319 * @param ldb Current ldb_context
5320 * @param usr_obj ldb_message representing User object
5321 * @param user_account_control Value for userAccountControl flags
5322 * @param account_type_p Optional pointer to account_type to return
5323 * @return LDB_SUCCESS or LDB_ERR* code on failure
5325 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
5326 uint32_t user_account_control, uint32_t *account_type_p)
5328 int ret;
5329 uint32_t account_type;
5330 struct ldb_message_element *el;
5332 account_type = ds_uf2atype(user_account_control);
5333 if (account_type == 0) {
5334 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
5335 return LDB_ERR_UNWILLING_TO_PERFORM;
5337 ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5338 "sAMAccountType",
5339 account_type);
5340 if (ret != LDB_SUCCESS) {
5341 return ret;
5343 el = ldb_msg_find_element(usr_obj, "sAMAccountType");
5344 el->flags = LDB_FLAG_MOD_REPLACE;
5346 if (account_type_p) {
5347 *account_type_p = account_type;
5350 return LDB_SUCCESS;
5354 * Determine and set primaryGroupID based on userAccountControl value
5355 * @param ldb Current ldb_context
5356 * @param usr_obj ldb_message representing User object
5357 * @param user_account_control Value for userAccountControl flags
5358 * @param group_rid_p Optional pointer to group RID to return
5359 * @return LDB_SUCCESS or LDB_ERR* code on failure
5361 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
5362 uint32_t user_account_control, uint32_t *group_rid_p)
5364 int ret;
5365 uint32_t rid;
5366 struct ldb_message_element *el;
5368 rid = ds_uf2prim_group_rid(user_account_control);
5370 ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5371 "primaryGroupID", rid);
5372 if (ret != LDB_SUCCESS) {
5373 return ret;
5375 el = ldb_msg_find_element(usr_obj, "primaryGroupID");
5376 el->flags = LDB_FLAG_MOD_REPLACE;
5378 if (group_rid_p) {
5379 *group_rid_p = rid;
5382 return LDB_SUCCESS;