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/>.
25 #include "events/events.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 "system/filesys.h"
43 #include "lib/util/tsort.h"
44 #include "dsdb/common/util.h"
45 #include "lib/socket/socket.h"
46 #include "librpc/gen_ndr/irpc.h"
47 #include "libds/common/flag_mapping.h"
48 #include "lib/util/access.h"
49 #include "lib/util/util_str_hex.h"
50 #include "libcli/util/ntstatus.h"
53 * This included to allow us to handle DSDB_FLAG_REPLICATED_UPDATE in
54 * dsdb_request_add_controls()
56 #include "dsdb/samdb/ldb_modules/util.h"
58 /* default is 30 minutes: -1e7 * 30 * 60 */
59 #define DEFAULT_OBSERVATION_WINDOW -18000000000
62 search the sam for the specified attributes in a specific domain, filter on
63 objectSid being in domain_sid.
65 int samdb_search_domain(struct ldb_context *sam_ldb,
67 struct ldb_dn *basedn,
68 struct ldb_message ***res,
69 const char * const *attrs,
70 const struct dom_sid *domain_sid,
71 const char *format, ...) _PRINTF_ATTRIBUTE(7,8)
77 count = gendb_search_v(sam_ldb, mem_ctx, basedn,
78 res, attrs, format, ap);
84 struct dom_sid *entry_sid;
86 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
88 if ((entry_sid == NULL) ||
89 (!dom_sid_in_domain(domain_sid, entry_sid))) {
90 /* Delete that entry from the result set */
91 (*res)[i] = (*res)[count-1];
93 talloc_free(entry_sid);
96 talloc_free(entry_sid);
104 search the sam for a single string attribute in exactly 1 record
106 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
108 struct ldb_dn *basedn,
109 const char *attr_name,
110 const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
113 const char *attrs[2] = { NULL, NULL };
114 struct ldb_message **res = NULL;
116 attrs[0] = attr_name;
118 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
120 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
121 attr_name, format, count));
128 return ldb_msg_find_attr_as_string(res[0], attr_name, NULL);
132 search the sam for a single string attribute in exactly 1 record
134 const char *samdb_search_string(struct ldb_context *sam_ldb,
136 struct ldb_dn *basedn,
137 const char *attr_name,
138 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
143 va_start(ap, format);
144 str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
150 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
152 struct ldb_dn *basedn,
153 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
157 struct ldb_message **res = NULL;
160 va_start(ap, format);
161 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
164 if (count != 1) return NULL;
166 ret = talloc_steal(mem_ctx, res[0]->dn);
173 search the sam for a dom_sid attribute in exactly 1 record
175 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
177 struct ldb_dn *basedn,
178 const char *attr_name,
179 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
183 struct ldb_message **res;
184 const char *attrs[2] = { NULL, NULL };
187 attrs[0] = attr_name;
189 va_start(ap, format);
190 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
193 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
194 attr_name, format, count));
200 sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
206 search the sam for a single integer attribute in exactly 1 record
208 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
210 unsigned int default_value,
211 struct ldb_dn *basedn,
212 const char *attr_name,
213 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
217 struct ldb_message **res;
218 const char *attrs[2] = { NULL, NULL };
220 attrs[0] = attr_name;
222 va_start(ap, format);
223 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
227 return default_value;
230 return ldb_msg_find_attr_as_uint(res[0], attr_name, default_value);
234 search the sam for a single signed 64 bit integer attribute in exactly 1 record
236 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
238 int64_t default_value,
239 struct ldb_dn *basedn,
240 const char *attr_name,
241 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
245 struct ldb_message **res;
246 const char *attrs[2] = { NULL, NULL };
248 attrs[0] = attr_name;
250 va_start(ap, format);
251 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
255 return default_value;
258 return ldb_msg_find_attr_as_int64(res[0], attr_name, default_value);
262 search the sam for multipe records each giving a single string attribute
263 return the number of matches, or -1 on error
265 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
267 struct ldb_dn *basedn,
269 const char *attr_name,
270 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
274 const char *attrs[2] = { NULL, NULL };
275 struct ldb_message **res = NULL;
277 attrs[0] = attr_name;
279 va_start(ap, format);
280 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
287 /* make sure its single valued */
288 for (i=0;i<count;i++) {
289 if (res[i]->num_elements != 1) {
290 DEBUG(1,("samdb: search for %s %s not single valued\n",
297 *strs = talloc_array(mem_ctx, const char *, count+1);
303 for (i=0;i<count;i++) {
304 (*strs)[i] = ldb_msg_find_attr_as_string(res[i], attr_name, NULL);
306 (*strs)[count] = NULL;
311 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
312 const char *attr, struct ldb_dn *default_value)
314 struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
316 return default_value;
322 pull a rid from a objectSid in a result set.
324 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
325 const char *attr, uint32_t default_value)
330 sid = samdb_result_dom_sid(mem_ctx, msg, attr);
332 return default_value;
334 rid = sid->sub_auths[sid->num_auths-1];
340 pull a dom_sid structure from a objectSid in a result set.
342 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
346 const struct ldb_val *v;
348 v = ldb_msg_find_ldb_val(msg, attr);
352 sid = talloc(mem_ctx, struct dom_sid);
356 ok = sid_parse(v->data, v->length, sid);
365 pull a guid structure from a objectGUID in a result set.
367 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
369 const struct ldb_val *v;
373 v = ldb_msg_find_ldb_val(msg, attr);
374 if (!v) return GUID_zero();
376 status = GUID_from_ndr_blob(v, &guid);
377 if (!NT_STATUS_IS_OK(status)) {
385 pull a sid prefix from a objectSid in a result set.
386 this is used to find the domain sid for a user
388 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
391 struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
392 if (!sid || sid->num_auths < 1) return NULL;
398 pull a NTTIME in a result set.
400 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
401 NTTIME default_value)
403 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
407 * Windows stores 0 for lastLogoff.
408 * But when a MS DC return the lastLogoff (as Logoff Time)
409 * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
410 * cause windows 2008 and newer version to fail for SMB requests
412 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
414 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
417 ret = 0x7FFFFFFFFFFFFFFFULL;
423 * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
424 * indicate an account doesn't expire.
426 * When Windows initially creates an account, it sets
427 * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF). However,
428 * when changing from an account having a specific expiration date to
429 * that account never expiring, it sets accountExpires = 0.
431 * Consolidate that logic here to allow clearer logic for account expiry in
432 * the rest of the code.
434 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
436 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
440 ret = 0x7FFFFFFFFFFFFFFFULL;
446 construct the allow_password_change field from the PwdLastSet attribute and the
447 domain password settings
449 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb,
451 struct ldb_dn *domain_dn,
452 struct ldb_message *msg,
455 uint64_t attr_time = ldb_msg_find_attr_as_uint64(msg, attr, 0);
458 if (attr_time == 0) {
462 minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
464 /* yes, this is a -= not a += as minPwdAge is stored as the negative
465 of the number of 100-nano-seconds */
466 attr_time -= minPwdAge;
472 pull a samr_Password structutre from a result set.
474 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
476 struct samr_Password *hash = NULL;
477 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
478 if (val && (val->length >= sizeof(hash->hash))) {
479 hash = talloc(mem_ctx, struct samr_Password);
480 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
486 pull an array of samr_Password structures from a result set.
488 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
489 const char *attr, struct samr_Password **hashes)
491 unsigned int count, i;
492 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
498 count = val->length / 16;
503 *hashes = talloc_array(mem_ctx, struct samr_Password, count);
508 for (i=0;i<count;i++) {
509 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
515 NTSTATUS samdb_result_passwords_from_history(TALLOC_CTX *mem_ctx,
516 struct loadparm_context *lp_ctx,
517 struct ldb_message *msg,
519 struct samr_Password **lm_pwd,
520 struct samr_Password **nt_pwd)
522 struct samr_Password *lmPwdHash, *ntPwdHash;
526 num_nt = samdb_result_hashes(mem_ctx, msg, "ntPwdHistory", &ntPwdHash);
530 *nt_pwd = &ntPwdHash[idx];
534 /* Ensure that if we have turned off LM
535 * authentication, that we never use the LM hash, even
537 if (lpcfg_lanman_auth(lp_ctx)) {
539 num_lm = samdb_result_hashes(mem_ctx, msg, "lmPwdHistory", &lmPwdHash);
543 *lm_pwd = &lmPwdHash[idx];
552 NTSTATUS samdb_result_passwords_no_lockout(TALLOC_CTX *mem_ctx,
553 struct loadparm_context *lp_ctx,
554 const struct ldb_message *msg,
555 struct samr_Password **lm_pwd,
556 struct samr_Password **nt_pwd)
558 struct samr_Password *lmPwdHash, *ntPwdHash;
562 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
565 } else if (num_nt > 1) {
566 return NT_STATUS_INTERNAL_DB_CORRUPTION;
568 *nt_pwd = &ntPwdHash[0];
572 /* Ensure that if we have turned off LM
573 * authentication, that we never use the LM hash, even
575 if (lpcfg_lanman_auth(lp_ctx)) {
577 num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
580 } else if (num_lm > 1) {
581 return NT_STATUS_INTERNAL_DB_CORRUPTION;
583 *lm_pwd = &lmPwdHash[0];
592 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx,
593 struct loadparm_context *lp_ctx,
594 const struct ldb_message *msg,
595 struct samr_Password **lm_pwd,
596 struct samr_Password **nt_pwd)
600 acct_flags = samdb_result_acct_flags(msg,
601 "msDS-User-Account-Control-Computed");
602 /* Quit if the account was locked out. */
603 if (acct_flags & ACB_AUTOLOCK) {
604 DEBUG(3,("samdb_result_passwords: Account for user %s was locked out.\n",
605 ldb_dn_get_linearized(msg->dn)));
606 return NT_STATUS_ACCOUNT_LOCKED_OUT;
609 return samdb_result_passwords_no_lockout(mem_ctx, lp_ctx, msg,
614 pull a samr_LogonHours structutre from a result set.
616 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
618 struct samr_LogonHours hours;
619 size_t units_per_week = 168;
620 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
625 units_per_week = val->length * 8;
628 hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
632 hours.units_per_week = units_per_week;
633 memset(hours.bits, 0xFF, units_per_week/8);
635 memcpy(hours.bits, val->data, val->length);
642 pull a set of account_flags from a result set.
644 Naturally, this requires that userAccountControl and
645 (if not null) the attributes 'attr' be already
648 uint32_t samdb_result_acct_flags(const struct ldb_message *msg, const char *attr)
650 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
651 uint32_t attr_flags = 0;
652 uint32_t acct_flags = ds_uf2acb(userAccountControl);
654 attr_flags = ldb_msg_find_attr_as_uint(msg, attr, UF_ACCOUNTDISABLE);
655 if (attr_flags == UF_ACCOUNTDISABLE) {
656 DEBUG(0, ("Attribute %s not found, disabling account %s!\n", attr,
657 ldb_dn_get_linearized(msg->dn)));
659 acct_flags |= ds_uf2acb(attr_flags);
665 NTSTATUS samdb_result_parameters(TALLOC_CTX *mem_ctx,
666 struct ldb_message *msg,
668 struct lsa_BinaryString *s)
671 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
679 if ((val->length % 2) != 0) {
681 * If the on-disk data is not even in length, we know
682 * it is corrupt, and can not be safely pushed. We
683 * would either truncate, send either a un-initilaised
684 * byte or send a forced zero byte
686 return NT_STATUS_INTERNAL_DB_CORRUPTION;
689 s->array = talloc_array(mem_ctx, uint16_t, val->length/2);
691 return NT_STATUS_NO_MEMORY;
693 s->length = s->size = val->length;
695 /* The on-disk format is the 'network' format, being UTF16LE (sort of) */
696 for (i = 0; i < s->length / 2; i++) {
697 s->array[i] = SVAL(val->data, i * 2);
703 /* Find an attribute, with a particular value */
705 /* The current callers of this function expect a very specific
706 * behaviour: In particular, objectClass subclass equivilance is not
707 * wanted. This means that we should not lookup the schema for the
708 * comparison function */
709 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
710 const struct ldb_message *msg,
711 const char *name, const char *value)
714 struct ldb_message_element *el = ldb_msg_find_element(msg, name);
720 for (i=0;i<el->num_values;i++) {
721 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
729 static int samdb_find_or_add_attribute_ex(struct ldb_context *ldb,
730 struct ldb_message *msg,
732 const char *set_value,
737 struct ldb_message_element *el;
739 SMB_ASSERT(attr_flags != 0);
741 el = ldb_msg_find_element(msg, name);
750 ret = ldb_msg_add_empty(msg, name,
753 if (ret != LDB_SUCCESS) {
757 if (set_value != NULL) {
758 ret = ldb_msg_add_string(msg, name, set_value);
759 if (ret != LDB_SUCCESS) {
770 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
772 return samdb_find_or_add_attribute_ex(ldb, msg, name, set_value, LDB_FLAG_MOD_ADD, NULL);
776 add a dom_sid element to a message
778 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
779 const char *attr_name, const struct dom_sid *sid)
782 enum ndr_err_code ndr_err;
784 ndr_err = ndr_push_struct_blob(&v, mem_ctx,
786 (ndr_push_flags_fn_t)ndr_push_dom_sid);
787 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
788 return ldb_operr(sam_ldb);
790 return ldb_msg_add_value(msg, attr_name, &v, NULL);
795 add a delete element operation to a message
797 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
798 const char *attr_name)
800 /* we use an empty replace rather than a delete, as it allows for
801 dsdb_replace() to be used everywhere */
802 return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
806 add an add attribute value to a message or enhance an existing attribute
807 which has the same name and the add flag set.
809 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
810 struct ldb_message *msg, const char *attr_name,
813 struct ldb_message_element *el;
814 struct ldb_val val, *vals;
820 v = talloc_strdup(mem_ctx, value);
822 return ldb_oom(sam_ldb);
825 val.data = (uint8_t *) v;
826 val.length = strlen(v);
828 if (val.length == 0) {
829 /* allow empty strings as non-existent attributes */
833 for (i = 0; i < msg->num_elements; i++) {
834 el = &msg->elements[i];
835 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
836 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
842 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
844 if (ret != LDB_SUCCESS) {
849 vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
852 return ldb_oom(sam_ldb);
855 el->values[el->num_values] = val;
862 add a delete attribute value to a message or enhance an existing attribute
863 which has the same name and the delete flag set.
865 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
866 struct ldb_message *msg, const char *attr_name,
869 struct ldb_message_element *el;
870 struct ldb_val val, *vals;
876 v = talloc_strdup(mem_ctx, value);
878 return ldb_oom(sam_ldb);
881 val.data = (uint8_t *) v;
882 val.length = strlen(v);
884 if (val.length == 0) {
885 /* allow empty strings as non-existent attributes */
889 for (i = 0; i < msg->num_elements; i++) {
890 el = &msg->elements[i];
891 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
892 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
898 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
900 if (ret != LDB_SUCCESS) {
905 vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
908 return ldb_oom(sam_ldb);
911 el->values[el->num_values] = val;
918 add a int element to a message
920 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
921 const char *attr_name, int v)
923 const char *s = talloc_asprintf(mem_ctx, "%d", v);
925 return ldb_oom(sam_ldb);
927 return ldb_msg_add_string(msg, attr_name, s);
931 * Add an unsigned int element to a message
933 * The issue here is that we have not yet first cast to int32_t explicitly,
934 * before we cast to an signed int to printf() into the %d or cast to a
935 * int64_t before we then cast to a long long to printf into a %lld.
937 * There are *no* unsigned integers in Active Directory LDAP, even the RID
938 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
939 * (See the schema, and the syntax definitions in schema_syntax.c).
942 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
943 const char *attr_name, unsigned int v)
945 return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
949 add a (signed) int64_t element to a message
951 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
952 const char *attr_name, int64_t v)
954 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
956 return ldb_oom(sam_ldb);
958 return ldb_msg_add_string(msg, attr_name, s);
962 * Add an unsigned int64_t (uint64_t) element to a message
964 * The issue here is that we have not yet first cast to int32_t explicitly,
965 * before we cast to an signed int to printf() into the %d or cast to a
966 * int64_t before we then cast to a long long to printf into a %lld.
968 * There are *no* unsigned integers in Active Directory LDAP, even the RID
969 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
970 * (See the schema, and the syntax definitions in schema_syntax.c).
973 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
974 const char *attr_name, uint64_t v)
976 return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
980 add a samr_Password element to a message
982 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
983 const char *attr_name, const struct samr_Password *hash)
986 val.data = talloc_memdup(mem_ctx, hash->hash, 16);
988 return ldb_oom(sam_ldb);
991 return ldb_msg_add_value(msg, attr_name, &val, NULL);
995 add a samr_Password array to a message
997 int samdb_msg_add_hashes(struct ldb_context *ldb,
998 TALLOC_CTX *mem_ctx, struct ldb_message *msg,
999 const char *attr_name, struct samr_Password *hashes,
1004 val.data = talloc_array_size(mem_ctx, 16, count);
1005 val.length = count*16;
1007 return ldb_oom(ldb);
1009 for (i=0;i<count;i++) {
1010 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
1012 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1016 add a acct_flags element to a message
1018 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1019 const char *attr_name, uint32_t v)
1021 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1025 add a logon_hours element to a message
1027 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1028 const char *attr_name, struct samr_LogonHours *hours)
1031 val.length = hours->units_per_week / 8;
1032 val.data = hours->bits;
1033 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1037 add a parameters element to a message
1039 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1040 const char *attr_name, struct lsa_BinaryString *parameters)
1044 if ((parameters->length % 2) != 0) {
1045 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
1048 val.data = talloc_array(mem_ctx, uint8_t, parameters->length);
1049 if (val.data == NULL) {
1050 return LDB_ERR_OPERATIONS_ERROR;
1052 val.length = parameters->length;
1053 for (i = 0; i < parameters->length / 2; i++) {
1055 * The on-disk format needs to be in the 'network'
1056 * format, parmeters->array is a uint16_t array of
1057 * length parameters->length / 2
1059 SSVAL(val.data, i * 2, parameters->array[i]);
1061 return ldb_msg_add_steal_value(msg, attr_name, &val);
1065 * Sets an unsigned int element in a message
1067 * The issue here is that we have not yet first cast to int32_t explicitly,
1068 * before we cast to an signed int to printf() into the %d or cast to a
1069 * int64_t before we then cast to a long long to printf into a %lld.
1071 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1072 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1073 * (See the schema, and the syntax definitions in schema_syntax.c).
1076 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1077 struct ldb_message *msg, const char *attr_name,
1080 struct ldb_message_element *el;
1082 el = ldb_msg_find_element(msg, attr_name);
1086 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1090 * Handle ldb_request in transaction
1092 int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1093 struct ldb_request *req)
1097 ret = ldb_transaction_start(sam_ldb);
1098 if (ret != LDB_SUCCESS) {
1102 ret = ldb_request(sam_ldb, req);
1103 if (ret == LDB_SUCCESS) {
1104 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1107 if (ret == LDB_SUCCESS) {
1108 return ldb_transaction_commit(sam_ldb);
1110 ldb_transaction_cancel(sam_ldb);
1116 return a default security descriptor
1118 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1120 struct security_descriptor *sd;
1122 sd = security_descriptor_initialise(mem_ctx);
1127 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1129 struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1130 struct ldb_dn *aggregate_dn;
1135 aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1136 if (!aggregate_dn) {
1139 if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1142 return aggregate_dn;
1145 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1147 struct ldb_dn *new_dn;
1149 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1150 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1151 talloc_free(new_dn);
1157 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1159 struct ldb_dn *new_dn;
1161 new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1162 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1163 talloc_free(new_dn);
1169 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1171 struct ldb_dn *new_dn;
1173 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1174 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1175 talloc_free(new_dn);
1182 work out the domain sid for the current open ldb
1184 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1186 TALLOC_CTX *tmp_ctx;
1187 const struct dom_sid *domain_sid;
1188 const char *attrs[] = {
1192 struct ldb_result *res;
1195 /* see if we have a cached copy */
1196 domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1201 tmp_ctx = talloc_new(ldb);
1202 if (tmp_ctx == NULL) {
1206 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1208 if (ret != LDB_SUCCESS) {
1212 if (res->count != 1) {
1216 domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1217 if (domain_sid == NULL) {
1221 /* cache the domain_sid in the ldb */
1222 if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1226 talloc_steal(ldb, domain_sid);
1227 talloc_free(tmp_ctx);
1232 talloc_free(tmp_ctx);
1237 get domain sid from cache
1239 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1241 return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1244 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1246 TALLOC_CTX *tmp_ctx;
1247 struct dom_sid *dom_sid_new;
1248 struct dom_sid *dom_sid_old;
1250 /* see if we have a cached copy */
1251 dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1252 "cache.domain_sid"), struct dom_sid);
1254 tmp_ctx = talloc_new(ldb);
1255 if (tmp_ctx == NULL) {
1259 dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1264 /* cache the domain_sid in the ldb */
1265 if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1269 talloc_steal(ldb, dom_sid_new);
1270 talloc_free(tmp_ctx);
1271 talloc_free(dom_sid_old);
1276 DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1277 talloc_free(tmp_ctx);
1282 work out the domain guid for the current open ldb
1284 const struct GUID *samdb_domain_guid(struct ldb_context *ldb)
1286 TALLOC_CTX *tmp_ctx = NULL;
1287 struct GUID *domain_guid = NULL;
1288 const char *attrs[] = {
1292 struct ldb_result *res = NULL;
1295 /* see if we have a cached copy */
1296 domain_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.domain_guid");
1301 tmp_ctx = talloc_new(ldb);
1302 if (tmp_ctx == NULL) {
1306 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectGUID=*");
1307 if (ret != LDB_SUCCESS) {
1311 if (res->count != 1) {
1315 domain_guid = talloc(tmp_ctx, struct GUID);
1316 if (domain_guid == NULL) {
1319 *domain_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1321 /* cache the domain_sid in the ldb */
1322 if (ldb_set_opaque(ldb, "cache.domain_guid", domain_guid) != LDB_SUCCESS) {
1326 talloc_steal(ldb, domain_guid);
1327 talloc_free(tmp_ctx);
1332 talloc_free(tmp_ctx);
1336 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1338 TALLOC_CTX *tmp_ctx;
1339 struct ldb_dn *ntds_settings_dn_new;
1340 struct ldb_dn *ntds_settings_dn_old;
1342 /* see if we have a forced copy from provision */
1343 ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb,
1344 "forced.ntds_settings_dn"), struct ldb_dn);
1346 tmp_ctx = talloc_new(ldb);
1347 if (tmp_ctx == NULL) {
1351 ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1352 if (!ntds_settings_dn_new) {
1356 /* set the DN in the ldb to avoid lookups during provision */
1357 if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1361 talloc_steal(ldb, ntds_settings_dn_new);
1362 talloc_free(tmp_ctx);
1363 talloc_free(ntds_settings_dn_old);
1368 DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1369 talloc_free(tmp_ctx);
1374 work out the ntds settings dn for the current open ldb
1376 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1378 TALLOC_CTX *tmp_ctx;
1379 const char *root_attrs[] = { "dsServiceName", NULL };
1381 struct ldb_result *root_res;
1382 struct ldb_dn *settings_dn;
1384 /* see if we have a cached copy */
1385 settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1387 return ldb_dn_copy(mem_ctx, settings_dn);
1390 tmp_ctx = talloc_new(mem_ctx);
1391 if (tmp_ctx == NULL) {
1395 ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1396 if (ret != LDB_SUCCESS) {
1397 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1398 ldb_errstring(ldb)));
1402 if (root_res->count != 1) {
1406 settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1408 /* note that we do not cache the DN here, as that would mean
1409 * we could not handle server renames at runtime. Only
1410 * provision sets up forced.ntds_settings_dn */
1412 talloc_steal(mem_ctx, settings_dn);
1413 talloc_free(tmp_ctx);
1418 DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1419 talloc_free(tmp_ctx);
1424 work out the ntds settings invocationId for the current open ldb
1426 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1428 TALLOC_CTX *tmp_ctx;
1429 const char *attrs[] = { "invocationId", NULL };
1431 struct ldb_result *res;
1432 struct GUID *invocation_id;
1434 /* see if we have a cached copy */
1435 invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1436 if (invocation_id) {
1437 SMB_ASSERT(!GUID_all_zero(invocation_id));
1438 return invocation_id;
1441 tmp_ctx = talloc_new(ldb);
1442 if (tmp_ctx == NULL) {
1446 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1451 if (res->count != 1) {
1455 invocation_id = talloc(tmp_ctx, struct GUID);
1456 if (!invocation_id) {
1460 *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1461 if (GUID_all_zero(invocation_id)) {
1462 if (ldb_msg_find_ldb_val(res->msgs[0], "invocationId")) {
1463 DEBUG(0, ("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1465 DEBUG(0, ("Failed to find parse own NTDS Settings invocationId from the ldb!\n"));
1470 /* cache the domain_sid in the ldb */
1471 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1475 talloc_steal(ldb, invocation_id);
1476 talloc_free(tmp_ctx);
1478 return invocation_id;
1481 DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1482 talloc_free(tmp_ctx);
1486 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1488 TALLOC_CTX *tmp_ctx;
1489 struct GUID *invocation_id_new;
1490 struct GUID *invocation_id_old;
1492 /* see if we have a cached copy */
1493 invocation_id_old = (struct GUID *)ldb_get_opaque(ldb,
1494 "cache.invocation_id");
1496 tmp_ctx = talloc_new(ldb);
1497 if (tmp_ctx == NULL) {
1501 invocation_id_new = talloc(tmp_ctx, struct GUID);
1502 if (!invocation_id_new) {
1506 SMB_ASSERT(!GUID_all_zero(invocation_id_in));
1507 *invocation_id_new = *invocation_id_in;
1509 /* cache the domain_sid in the ldb */
1510 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1514 talloc_steal(ldb, invocation_id_new);
1515 talloc_free(tmp_ctx);
1516 talloc_free(invocation_id_old);
1521 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1522 talloc_free(tmp_ctx);
1527 work out the ntds settings objectGUID for the current open ldb
1529 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1531 TALLOC_CTX *tmp_ctx;
1532 const char *attrs[] = { "objectGUID", NULL };
1534 struct ldb_result *res;
1535 struct GUID *ntds_guid;
1537 /* see if we have a cached copy */
1538 ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1543 tmp_ctx = talloc_new(ldb);
1544 if (tmp_ctx == NULL) {
1548 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1553 if (res->count != 1) {
1557 ntds_guid = talloc(tmp_ctx, struct GUID);
1562 *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1564 /* cache the domain_sid in the ldb */
1565 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1569 talloc_steal(ldb, ntds_guid);
1570 talloc_free(tmp_ctx);
1575 DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1576 talloc_free(tmp_ctx);
1580 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1582 TALLOC_CTX *tmp_ctx;
1583 struct GUID *ntds_guid_new;
1584 struct GUID *ntds_guid_old;
1586 /* see if we have a cached copy */
1587 ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1589 tmp_ctx = talloc_new(ldb);
1590 if (tmp_ctx == NULL) {
1594 ntds_guid_new = talloc(tmp_ctx, struct GUID);
1595 if (!ntds_guid_new) {
1599 *ntds_guid_new = *ntds_guid_in;
1601 /* cache the domain_sid in the ldb */
1602 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1606 talloc_steal(ldb, ntds_guid_new);
1607 talloc_free(tmp_ctx);
1608 talloc_free(ntds_guid_old);
1613 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1614 talloc_free(tmp_ctx);
1619 work out the server dn for the current open ldb
1621 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1623 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1628 dn = ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb, tmp_ctx));
1629 talloc_free(tmp_ctx);
1635 work out the server dn for the current open ldb
1637 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1639 struct ldb_dn *server_dn;
1640 struct ldb_dn *servers_dn;
1641 struct ldb_dn *server_site_dn;
1643 /* TODO: there must be a saner way to do this!! */
1644 server_dn = samdb_server_dn(ldb, mem_ctx);
1645 if (!server_dn) return NULL;
1647 servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1648 talloc_free(server_dn);
1649 if (!servers_dn) return NULL;
1651 server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1652 talloc_free(servers_dn);
1654 return server_site_dn;
1658 find the site name from a computers DN record
1660 int samdb_find_site_for_computer(struct ldb_context *ldb,
1661 TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1662 const char **site_name)
1666 const struct ldb_val *rdn_val;
1670 ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1671 if (ret != LDB_SUCCESS) {
1675 if (!ldb_dn_remove_child_components(dn, 2)) {
1677 return LDB_ERR_INVALID_DN_SYNTAX;
1680 rdn_val = ldb_dn_get_rdn_val(dn);
1681 if (rdn_val == NULL) {
1682 return LDB_ERR_OPERATIONS_ERROR;
1685 (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1688 return LDB_ERR_OPERATIONS_ERROR;
1694 find the NTDS GUID from a computers DN record
1696 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1697 struct GUID *ntds_guid)
1702 *ntds_guid = GUID_zero();
1704 ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1705 if (ret != LDB_SUCCESS) {
1709 if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1711 return LDB_ERR_OPERATIONS_ERROR;
1714 ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1720 find a 'reference' DN that points at another object
1721 (eg. serverReference, rIDManagerReference etc)
1723 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1724 const char *attribute, struct ldb_dn **dn)
1726 const char *attrs[2];
1727 struct ldb_result *res;
1730 attrs[0] = attribute;
1733 ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY|DSDB_SEARCH_SHOW_EXTENDED_DN, NULL);
1734 if (ret != LDB_SUCCESS) {
1735 ldb_asprintf_errstring(ldb, "Cannot find DN %s to get attribute %s for reference dn: %s",
1736 ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb));
1740 *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1742 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1743 ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1744 ldb_dn_get_linearized(base));
1746 ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1747 ldb_dn_get_linearized(base));
1750 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1758 find if a DN (must have GUID component!) is our ntdsDsa
1760 int samdb_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *dn, bool *is_ntdsa)
1763 struct GUID dn_guid;
1764 const struct GUID *our_ntds_guid;
1765 status = dsdb_get_extended_dn_guid(dn, &dn_guid, "GUID");
1766 if (!NT_STATUS_IS_OK(status)) {
1767 return LDB_ERR_OPERATIONS_ERROR;
1770 our_ntds_guid = samdb_ntds_objectGUID(ldb);
1771 if (!our_ntds_guid) {
1772 DEBUG(0, ("Failed to find our NTDS Settings GUID for comparison with %s - %s\n", ldb_dn_get_linearized(dn), ldb_errstring(ldb)));
1773 return LDB_ERR_OPERATIONS_ERROR;
1776 *is_ntdsa = GUID_equal(&dn_guid, our_ntds_guid);
1781 find a 'reference' DN that points at another object and indicate if it is our ntdsDsa
1783 int samdb_reference_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *base,
1784 const char *attribute, bool *is_ntdsa)
1787 struct ldb_dn *referenced_dn;
1788 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1789 if (tmp_ctx == NULL) {
1790 return LDB_ERR_OPERATIONS_ERROR;
1792 ret = samdb_reference_dn(ldb, tmp_ctx, base, attribute, &referenced_dn);
1793 if (ret != LDB_SUCCESS) {
1794 DEBUG(0, ("Failed to find object %s for attribute %s - %s\n", ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb)));
1798 ret = samdb_dn_is_our_ntdsa(ldb, referenced_dn, is_ntdsa);
1800 talloc_free(tmp_ctx);
1805 find our machine account via the serverReference attribute in the
1808 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1810 struct ldb_dn *server_dn;
1813 server_dn = samdb_server_dn(ldb, mem_ctx);
1814 if (server_dn == NULL) {
1815 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
1818 ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1819 talloc_free(server_dn);
1825 find the RID Manager$ DN via the rIDManagerReference attribute in the
1828 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1830 return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1831 "rIDManagerReference", dn);
1835 find the RID Set DN via the rIDSetReferences attribute in our
1838 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1840 struct ldb_dn *server_ref_dn;
1843 ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1844 if (ret != LDB_SUCCESS) {
1847 ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1848 talloc_free(server_ref_dn);
1852 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1854 const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1861 return (const char *) val->data;
1865 * Finds the client site by using the client's IP address.
1866 * The "subnet_name" returns the name of the subnet if parameter != NULL
1868 * Has a Windows-based fallback to provide the only site available, or an empty
1869 * string if there are multiple sites.
1871 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1872 const char *ip_address, char **subnet_name,
1875 const char *attrs[] = { "cn", "siteObject", NULL };
1876 struct ldb_dn *sites_container_dn = NULL;
1877 struct ldb_dn *subnets_dn = NULL;
1878 struct ldb_dn *sites_dn = NULL;
1879 struct ldb_result *res = NULL;
1880 const struct ldb_val *val = NULL;
1881 const char *site_name = NULL;
1882 const char *l_subnet_name = NULL;
1883 const char *allow_list[2] = { NULL, NULL };
1884 unsigned int i, count;
1888 * if we don't have a client ip e.g. ncalrpc
1889 * the server site is the client site
1891 if (ip_address == NULL) {
1892 return samdb_server_site_name(ldb, mem_ctx);
1895 sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1896 if (sites_container_dn == NULL) {
1900 subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1901 if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1905 ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1907 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1909 } else if (ret != LDB_SUCCESS) {
1915 for (i = 0; i < count; i++) {
1916 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1919 allow_list[0] = l_subnet_name;
1921 if (allow_access_nolog(NULL, allow_list, "", ip_address)) {
1922 sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1925 if (sites_dn == NULL) {
1926 /* No reference, maybe another subnet matches */
1930 /* "val" cannot be NULL here since "sites_dn" != NULL */
1931 val = ldb_dn_get_rdn_val(sites_dn);
1932 site_name = talloc_strdup(mem_ctx,
1933 (const char *) val->data);
1935 TALLOC_FREE(sites_dn);
1941 if (site_name == NULL && fallback) {
1942 /* This is the Windows Server fallback rule: when no subnet
1943 * exists and we have only one site available then use it (it
1944 * is for sure the same as our server site). If more sites do
1945 * exist then we don't know which one to use and set the site
1948 ret = dsdb_domain_count(
1954 "(objectClass=site)");
1955 if (ret != LDB_SUCCESS) {
1959 site_name = samdb_server_site_name(ldb, mem_ctx);
1961 site_name = talloc_strdup(mem_ctx, "");
1963 l_subnet_name = NULL;
1966 if (subnet_name != NULL) {
1967 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1971 TALLOC_FREE(sites_container_dn);
1972 TALLOC_FREE(subnets_dn);
1979 work out if we are the PDC for the domain of the current open ldb
1981 bool samdb_is_pdc(struct ldb_context *ldb)
1986 ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner",
1988 if (ret != LDB_SUCCESS) {
1989 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n",
1990 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
1991 ldb_errstring(ldb)));
1999 work out if we are a Global Catalog server for the domain of the current open ldb
2001 bool samdb_is_gc(struct ldb_context *ldb)
2004 if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
2007 return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
2010 /* Find a domain object in the parents of a particular DN. */
2011 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2012 struct ldb_dn **parent_dn, const char **errstring)
2014 TALLOC_CTX *local_ctx;
2015 struct ldb_dn *sdn = dn;
2016 struct ldb_result *res = NULL;
2017 int ret = LDB_SUCCESS;
2018 const char *attrs[] = { NULL };
2020 local_ctx = talloc_new(mem_ctx);
2021 if (local_ctx == NULL) return ldb_oom(ldb);
2023 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
2024 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
2025 "(|(objectClass=domain)(objectClass=builtinDomain))");
2026 if (ret == LDB_SUCCESS) {
2027 if (res->count == 1) {
2035 if (ret != LDB_SUCCESS) {
2036 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
2037 ldb_dn_get_linearized(dn),
2038 ldb_dn_get_linearized(sdn),
2039 ldb_errstring(ldb));
2040 talloc_free(local_ctx);
2043 if (res->count != 1) {
2044 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
2045 ldb_dn_get_linearized(dn));
2046 DEBUG(0,(__location__ ": %s\n", *errstring));
2047 talloc_free(local_ctx);
2048 return LDB_ERR_CONSTRAINT_VIOLATION;
2051 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2052 talloc_free(local_ctx);
2056 static void pwd_timeout_debug(struct tevent_context *unused1,
2057 struct tevent_timer *unused2,
2058 struct timeval unused3,
2061 DEBUG(0, ("WARNING: check_password_complexity: password script "
2062 "took more than 1 second to run\n"));
2067 * Performs checks on a user password (plaintext UNIX format - attribute
2068 * "password"). The remaining parameters have to be extracted from the domain
2071 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
2073 enum samr_ValidationStatus samdb_check_password(TALLOC_CTX *mem_ctx,
2074 struct loadparm_context *lp_ctx,
2075 const char *account_name,
2076 const char *user_principal_name,
2077 const char *full_name,
2078 const DATA_BLOB *utf8_blob,
2079 const uint32_t pwdProperties,
2080 const uint32_t minPwdLength)
2082 const char *utf8_pw = (const char *)utf8_blob->data;
2083 size_t utf8_len = strlen_m(utf8_pw);
2084 char *password_script = NULL;
2086 /* checks if the "minPwdLength" property is satisfied */
2087 if (minPwdLength > utf8_len) {
2088 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2091 /* checks the password complexity */
2092 if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
2093 return SAMR_VALIDATION_STATUS_SUCCESS;
2096 if (utf8_len == 0) {
2097 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2100 password_script = lpcfg_check_password_script(lp_ctx, mem_ctx);
2101 if (password_script != NULL && *password_script != '\0') {
2104 struct tevent_context *event_ctx = NULL;
2105 struct tevent_req *req = NULL;
2107 const char * const cmd[4] = {
2113 event_ctx = tevent_context_init(mem_ctx);
2114 if (event_ctx == NULL) {
2115 TALLOC_FREE(password_script);
2116 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2119 /* Gives a warning after 1 second, terminates after 10 */
2120 tevent_add_timer(event_ctx, event_ctx,
2121 tevent_timeval_current_ofs(1, 0),
2122 pwd_timeout_debug, NULL);
2124 check_ret = setenv("SAMBA_CPS_ACCOUNT_NAME", account_name, 1);
2125 if (check_ret != 0) {
2126 TALLOC_FREE(password_script);
2127 TALLOC_FREE(event_ctx);
2128 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2130 if (user_principal_name != NULL) {
2131 check_ret = setenv("SAMBA_CPS_USER_PRINCIPAL_NAME",
2132 user_principal_name, 1);
2134 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2136 if (check_ret != 0) {
2137 TALLOC_FREE(password_script);
2138 TALLOC_FREE(event_ctx);
2139 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2141 if (full_name != NULL) {
2142 check_ret = setenv("SAMBA_CPS_FULL_NAME", full_name, 1);
2144 unsetenv("SAMBA_CPS_FULL_NAME");
2146 if (check_ret != 0) {
2147 TALLOC_FREE(password_script);
2148 TALLOC_FREE(event_ctx);
2149 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2152 req = samba_runcmd_send(event_ctx, event_ctx,
2153 tevent_timeval_current_ofs(10, 0),
2154 100, 100, cmd, NULL);
2155 unsetenv("SAMBA_CPS_ACCOUNT_NAME");
2156 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2157 unsetenv("SAMBA_CPS_FULL_NAME");
2159 TALLOC_FREE(password_script);
2160 TALLOC_FREE(event_ctx);
2161 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2164 cps_stdin = samba_runcmd_export_stdin(req);
2166 if (write(cps_stdin, utf8_pw, utf8_len) != utf8_len) {
2169 TALLOC_FREE(password_script);
2170 TALLOC_FREE(event_ctx);
2171 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2177 if (!tevent_req_poll(req, event_ctx)) {
2178 TALLOC_FREE(password_script);
2179 TALLOC_FREE(event_ctx);
2180 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2183 check_ret = samba_runcmd_recv(req, &error);
2184 TALLOC_FREE(event_ctx);
2186 if (error == ETIMEDOUT) {
2187 DEBUG(0, ("check_password_complexity: check password script took too long!\n"));
2188 TALLOC_FREE(password_script);
2189 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2191 DEBUG(5,("check_password_complexity: check password script (%s) "
2192 "returned [%d]\n", password_script, check_ret));
2194 if (check_ret != 0) {
2195 DEBUG(1,("check_password_complexity: "
2196 "check password script said new password is not good "
2198 TALLOC_FREE(password_script);
2199 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2202 TALLOC_FREE(password_script);
2203 return SAMR_VALIDATION_STATUS_SUCCESS;
2206 TALLOC_FREE(password_script);
2209 * Here are the standard AD password quality rules, which we
2210 * run after the script.
2213 if (!check_password_quality(utf8_pw)) {
2214 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2217 return SAMR_VALIDATION_STATUS_SUCCESS;
2221 * Callback for "samdb_set_password" password change
2223 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2228 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2231 if (ares->error != LDB_SUCCESS) {
2233 req->context = talloc_steal(req,
2234 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2236 return ldb_request_done(req, ret);
2239 if (ares->type != LDB_REPLY_DONE) {
2241 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2244 req->context = talloc_steal(req,
2245 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2247 return ldb_request_done(req, LDB_SUCCESS);
2251 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2252 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2253 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2254 * user change or not. The "rejectReason" gives some more information if the
2257 * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2258 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2260 static NTSTATUS samdb_set_password_internal(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2261 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2262 const DATA_BLOB *new_password,
2263 const struct samr_Password *lmNewHash,
2264 const struct samr_Password *ntNewHash,
2265 const struct samr_Password *lmOldHash,
2266 const struct samr_Password *ntOldHash,
2267 enum samPwdChangeReason *reject_reason,
2268 struct samr_DomInfo1 **_dominfo,
2269 bool permit_interdomain_trust)
2271 struct ldb_message *msg;
2272 struct ldb_message_element *el;
2273 struct ldb_request *req;
2274 struct dsdb_control_password_change_status *pwd_stat = NULL;
2276 bool hash_values = false;
2277 NTSTATUS status = NT_STATUS_OK;
2279 #define CHECK_RET(x) \
2280 if (x != LDB_SUCCESS) { \
2282 return NT_STATUS_NO_MEMORY; \
2285 msg = ldb_msg_new(mem_ctx);
2287 return NT_STATUS_NO_MEMORY;
2290 if ((new_password != NULL)
2291 && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2292 /* we have the password as plaintext UTF16 */
2293 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2294 new_password, NULL));
2295 el = ldb_msg_find_element(msg, "clearTextPassword");
2296 el->flags = LDB_FLAG_MOD_REPLACE;
2297 } else if ((new_password == NULL)
2298 && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2299 /* we have a password as LM and/or NT hash */
2300 if (lmNewHash != NULL) {
2301 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2302 "dBCSPwd", lmNewHash));
2303 el = ldb_msg_find_element(msg, "dBCSPwd");
2304 el->flags = LDB_FLAG_MOD_REPLACE;
2306 if (ntNewHash != NULL) {
2307 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2308 "unicodePwd", ntNewHash));
2309 el = ldb_msg_find_element(msg, "unicodePwd");
2310 el->flags = LDB_FLAG_MOD_REPLACE;
2314 /* the password wasn't specified correctly */
2316 return NT_STATUS_INVALID_PARAMETER;
2319 /* build modify request */
2320 ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2321 samdb_set_password_callback, NULL);
2322 if (ret != LDB_SUCCESS) {
2324 return NT_STATUS_NO_MEMORY;
2327 /* A password change operation */
2328 if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2329 struct dsdb_control_password_change *change;
2331 change = talloc(req, struct dsdb_control_password_change);
2332 if (change == NULL) {
2335 return NT_STATUS_NO_MEMORY;
2338 change->old_nt_pwd_hash = ntOldHash;
2339 change->old_lm_pwd_hash = lmOldHash;
2341 ret = ldb_request_add_control(req,
2342 DSDB_CONTROL_PASSWORD_CHANGE_OID,
2344 if (ret != LDB_SUCCESS) {
2347 return NT_STATUS_NO_MEMORY;
2351 ret = ldb_request_add_control(req,
2352 DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2354 if (ret != LDB_SUCCESS) {
2357 return NT_STATUS_NO_MEMORY;
2360 if (permit_interdomain_trust) {
2361 ret = ldb_request_add_control(req,
2362 DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
2364 if (ret != LDB_SUCCESS) {
2367 return NT_STATUS_NO_MEMORY;
2370 ret = ldb_request_add_control(req,
2371 DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2373 if (ret != LDB_SUCCESS) {
2376 return NT_STATUS_NO_MEMORY;
2379 ret = dsdb_autotransaction_request(ldb, req);
2381 if (req->context != NULL) {
2382 struct ldb_control *control = talloc_get_type_abort(req->context,
2383 struct ldb_control);
2384 pwd_stat = talloc_get_type_abort(control->data,
2385 struct dsdb_control_password_change_status);
2386 talloc_steal(mem_ctx, pwd_stat);
2392 /* Sets the domain info (if requested) */
2393 if (_dominfo != NULL) {
2394 struct samr_DomInfo1 *dominfo;
2396 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2397 if (dominfo == NULL) {
2398 return NT_STATUS_NO_MEMORY;
2401 if (pwd_stat != NULL) {
2402 dominfo->min_password_length = pwd_stat->domain_data.minPwdLength;
2403 dominfo->password_properties = pwd_stat->domain_data.pwdProperties;
2404 dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2405 dominfo->max_password_age = pwd_stat->domain_data.maxPwdAge;
2406 dominfo->min_password_age = pwd_stat->domain_data.minPwdAge;
2409 *_dominfo = dominfo;
2412 if (reject_reason != NULL) {
2413 if (pwd_stat != NULL) {
2414 *reject_reason = pwd_stat->reject_reason;
2416 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2420 if (pwd_stat != NULL) {
2421 talloc_free(pwd_stat);
2424 if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2425 const char *errmsg = ldb_errstring(ldb);
2426 char *endptr = NULL;
2427 WERROR werr = WERR_GEN_FAILURE;
2428 status = NT_STATUS_UNSUCCESSFUL;
2429 if (errmsg != NULL) {
2430 werr = W_ERROR(strtol(errmsg, &endptr, 16));
2431 DBG_WARNING("%s\n", errmsg);
2433 if (endptr != errmsg) {
2434 if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2435 status = NT_STATUS_WRONG_PASSWORD;
2437 if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2438 status = NT_STATUS_PASSWORD_RESTRICTION;
2441 } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2442 /* don't let the caller know if an account doesn't exist */
2443 status = NT_STATUS_WRONG_PASSWORD;
2444 } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2445 status = NT_STATUS_ACCESS_DENIED;
2446 } else if (ret != LDB_SUCCESS) {
2447 DEBUG(1, ("Failed to set password on %s: %s\n",
2448 ldb_dn_get_linearized(user_dn),
2449 ldb_errstring(ldb)));
2450 status = NT_STATUS_UNSUCCESSFUL;
2456 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2457 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2458 const DATA_BLOB *new_password,
2459 const struct samr_Password *lmNewHash,
2460 const struct samr_Password *ntNewHash,
2461 const struct samr_Password *lmOldHash,
2462 const struct samr_Password *ntOldHash,
2463 enum samPwdChangeReason *reject_reason,
2464 struct samr_DomInfo1 **_dominfo)
2466 return samdb_set_password_internal(ldb, mem_ctx,
2469 lmNewHash, ntNewHash,
2470 lmOldHash, ntOldHash,
2471 reject_reason, _dominfo,
2472 false); /* reject trusts */
2476 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2477 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2478 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2479 * user change or not. The "rejectReason" gives some more information if the
2482 * This wrapper function for "samdb_set_password" takes a SID as input rather
2485 * This call encapsulates a new LDB transaction for changing the password;
2486 * therefore the user hasn't to start a new one.
2488 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2489 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2490 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2491 * NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2493 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2494 const struct dom_sid *user_sid,
2495 const uint32_t *new_version, /* optional for trusts */
2496 const DATA_BLOB *new_password,
2497 const struct samr_Password *lmNewHash,
2498 const struct samr_Password *ntNewHash,
2499 const struct samr_Password *lmOldHash,
2500 const struct samr_Password *ntOldHash,
2501 enum samPwdChangeReason *reject_reason,
2502 struct samr_DomInfo1 **_dominfo)
2504 TALLOC_CTX *frame = talloc_stackframe();
2506 const char * const user_attrs[] = {
2507 "userAccountControl",
2511 struct ldb_message *user_msg = NULL;
2515 ret = ldb_transaction_start(ldb);
2516 if (ret != LDB_SUCCESS) {
2517 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2519 return NT_STATUS_TRANSACTION_ABORTED;
2522 ret = dsdb_search_one(ldb, frame, &user_msg, ldb_get_default_basedn(ldb),
2523 LDB_SCOPE_SUBTREE, user_attrs, 0,
2524 "(&(objectSid=%s)(objectClass=user))",
2525 ldap_encode_ndr_dom_sid(frame, user_sid));
2526 if (ret != LDB_SUCCESS) {
2527 ldb_transaction_cancel(ldb);
2528 DEBUG(3, ("samdb_set_password_sid: SID[%s] not found in samdb %s - %s, "
2529 "returning NO_SUCH_USER\n",
2530 dom_sid_string(frame, user_sid),
2531 ldb_strerror(ret), ldb_errstring(ldb)));
2533 return NT_STATUS_NO_SUCH_USER;
2536 uac = ldb_msg_find_attr_as_uint(user_msg, "userAccountControl", 0);
2537 if (!(uac & UF_ACCOUNT_TYPE_MASK)) {
2538 ldb_transaction_cancel(ldb);
2539 DEBUG(1, ("samdb_set_password_sid: invalid "
2540 "userAccountControl[0x%08X] for SID[%s] DN[%s], "
2541 "returning NO_SUCH_USER\n",
2542 (unsigned)uac, dom_sid_string(frame, user_sid),
2543 ldb_dn_get_linearized(user_msg->dn)));
2545 return NT_STATUS_NO_SUCH_USER;
2548 if (uac & UF_INTERDOMAIN_TRUST_ACCOUNT) {
2549 const char * const tdo_attrs[] = {
2550 "trustAuthIncoming",
2554 struct ldb_message *tdo_msg = NULL;
2555 const char *account_name = NULL;
2556 uint32_t trust_direction;
2558 const struct ldb_val *old_val = NULL;
2559 struct trustAuthInOutBlob old_blob = {
2562 uint32_t old_version = 0;
2563 struct AuthenticationInformation *old_version_a = NULL;
2564 uint32_t _new_version = 0;
2565 struct trustAuthInOutBlob new_blob = {
2568 struct ldb_val new_val = {
2571 struct timeval tv = timeval_current();
2572 NTTIME now = timeval_to_nttime(&tv);
2573 enum ndr_err_code ndr_err;
2575 if (new_password == NULL && ntNewHash == NULL) {
2576 ldb_transaction_cancel(ldb);
2577 DEBUG(1, ("samdb_set_password_sid: "
2578 "no new password provided "
2579 "sAMAccountName for SID[%s] DN[%s], "
2580 "returning INVALID_PARAMETER\n",
2581 dom_sid_string(frame, user_sid),
2582 ldb_dn_get_linearized(user_msg->dn)));
2584 return NT_STATUS_INVALID_PARAMETER;
2587 if (new_password != NULL && ntNewHash != NULL) {
2588 ldb_transaction_cancel(ldb);
2589 DEBUG(1, ("samdb_set_password_sid: "
2590 "two new passwords provided "
2591 "sAMAccountName for SID[%s] DN[%s], "
2592 "returning INVALID_PARAMETER\n",
2593 dom_sid_string(frame, user_sid),
2594 ldb_dn_get_linearized(user_msg->dn)));
2596 return NT_STATUS_INVALID_PARAMETER;
2599 if (new_password != NULL && (new_password->length % 2)) {
2600 ldb_transaction_cancel(ldb);
2601 DEBUG(2, ("samdb_set_password_sid: "
2602 "invalid utf16 length (%zu) "
2603 "sAMAccountName for SID[%s] DN[%s], "
2604 "returning WRONG_PASSWORD\n",
2605 new_password->length,
2606 dom_sid_string(frame, user_sid),
2607 ldb_dn_get_linearized(user_msg->dn)));
2609 return NT_STATUS_WRONG_PASSWORD;
2612 if (new_password != NULL && new_password->length >= 500) {
2613 ldb_transaction_cancel(ldb);
2614 DEBUG(2, ("samdb_set_password_sid: "
2615 "utf16 password too long (%zu) "
2616 "sAMAccountName for SID[%s] DN[%s], "
2617 "returning WRONG_PASSWORD\n",
2618 new_password->length,
2619 dom_sid_string(frame, user_sid),
2620 ldb_dn_get_linearized(user_msg->dn)));
2622 return NT_STATUS_WRONG_PASSWORD;
2625 account_name = ldb_msg_find_attr_as_string(user_msg,
2626 "sAMAccountName", NULL);
2627 if (account_name == NULL) {
2628 ldb_transaction_cancel(ldb);
2629 DEBUG(1, ("samdb_set_password_sid: missing "
2630 "sAMAccountName for SID[%s] DN[%s], "
2631 "returning NO_SUCH_USER\n",
2632 dom_sid_string(frame, user_sid),
2633 ldb_dn_get_linearized(user_msg->dn)));
2635 return NT_STATUS_NO_SUCH_USER;
2638 nt_status = dsdb_trust_search_tdo_by_type(ldb,
2643 if (!NT_STATUS_IS_OK(nt_status)) {
2644 ldb_transaction_cancel(ldb);
2645 DEBUG(1, ("samdb_set_password_sid: dsdb_trust_search_tdo "
2646 "failed(%s) for sAMAccountName[%s] SID[%s] DN[%s], "
2647 "returning INTERNAL_DB_CORRUPTION\n",
2648 nt_errstr(nt_status), account_name,
2649 dom_sid_string(frame, user_sid),
2650 ldb_dn_get_linearized(user_msg->dn)));
2652 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2655 trust_direction = ldb_msg_find_attr_as_int(tdo_msg,
2656 "trustDirection", 0);
2657 if (!(trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {
2658 ldb_transaction_cancel(ldb);
2659 DEBUG(1, ("samdb_set_password_sid: direction[0x%08X] is "
2660 "not inbound for sAMAccountName[%s] "
2662 "returning INTERNAL_DB_CORRUPTION\n",
2663 (unsigned)trust_direction,
2665 ldb_dn_get_linearized(user_msg->dn),
2666 ldb_dn_get_linearized(tdo_msg->dn)));
2668 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2671 old_val = ldb_msg_find_ldb_val(tdo_msg, "trustAuthIncoming");
2672 if (old_val != NULL) {
2673 ndr_err = ndr_pull_struct_blob(old_val, frame, &old_blob,
2674 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2675 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2676 ldb_transaction_cancel(ldb);
2677 DEBUG(1, ("samdb_set_password_sid: "
2678 "failed(%s) to parse "
2679 "trustAuthOutgoing sAMAccountName[%s] "
2681 "returning INTERNAL_DB_CORRUPTION\n",
2682 ndr_map_error2string(ndr_err),
2684 ldb_dn_get_linearized(user_msg->dn),
2685 ldb_dn_get_linearized(tdo_msg->dn)));
2688 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2692 for (i = old_blob.current.count; i > 0; i--) {
2693 struct AuthenticationInformation *a =
2694 &old_blob.current.array[i - 1];
2696 switch (a->AuthType) {
2697 case TRUST_AUTH_TYPE_NONE:
2698 if (i == old_blob.current.count) {
2700 * remove TRUST_AUTH_TYPE_NONE at the
2703 old_blob.current.count--;
2707 case TRUST_AUTH_TYPE_VERSION:
2709 old_version = a->AuthInfo.version.version;
2712 case TRUST_AUTH_TYPE_CLEAR:
2715 case TRUST_AUTH_TYPE_NT4OWF:
2720 if (new_version == NULL) {
2722 new_version = &_new_version;
2725 if (old_version_a != NULL && *new_version != (old_version + 1)) {
2726 old_version_a->LastUpdateTime = now;
2727 old_version_a->AuthType = TRUST_AUTH_TYPE_NONE;
2730 new_blob.count = MAX(old_blob.current.count, 2);
2731 new_blob.current.array = talloc_zero_array(frame,
2732 struct AuthenticationInformation,
2734 if (new_blob.current.array == NULL) {
2735 ldb_transaction_cancel(ldb);
2737 return NT_STATUS_NO_MEMORY;
2739 new_blob.previous.array = talloc_zero_array(frame,
2740 struct AuthenticationInformation,
2742 if (new_blob.current.array == NULL) {
2743 ldb_transaction_cancel(ldb);
2745 return NT_STATUS_NO_MEMORY;
2748 for (i = 0; i < old_blob.current.count; i++) {
2749 struct AuthenticationInformation *o =
2750 &old_blob.current.array[i];
2751 struct AuthenticationInformation *p =
2752 &new_blob.previous.array[i];
2755 new_blob.previous.count++;
2757 for (; i < new_blob.count; i++) {
2758 struct AuthenticationInformation *pi =
2759 &new_blob.previous.array[i];
2763 * new_blob.previous is still empty so
2764 * we'll do new_blob.previous = new_blob.current
2770 pi->LastUpdateTime = now;
2771 pi->AuthType = TRUST_AUTH_TYPE_NONE;
2772 new_blob.previous.count++;
2775 for (i = 0; i < new_blob.count; i++) {
2776 struct AuthenticationInformation *ci =
2777 &new_blob.current.array[i];
2779 ci->LastUpdateTime = now;
2782 if (ntNewHash != NULL) {
2783 ci->AuthType = TRUST_AUTH_TYPE_NT4OWF;
2784 ci->AuthInfo.nt4owf.password = *ntNewHash;
2788 ci->AuthType = TRUST_AUTH_TYPE_CLEAR;
2789 ci->AuthInfo.clear.size = new_password->length;
2790 ci->AuthInfo.clear.password = new_password->data;
2793 ci->AuthType = TRUST_AUTH_TYPE_VERSION;
2794 ci->AuthInfo.version.version = *new_version;
2797 ci->AuthType = TRUST_AUTH_TYPE_NONE;
2801 new_blob.current.count++;
2804 if (new_blob.previous.count == 0) {
2805 TALLOC_FREE(new_blob.previous.array);
2806 new_blob.previous = new_blob.current;
2809 ndr_err = ndr_push_struct_blob(&new_val, frame, &new_blob,
2810 (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2811 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2812 ldb_transaction_cancel(ldb);
2813 DEBUG(1, ("samdb_set_password_sid: "
2814 "failed(%s) to generate "
2815 "trustAuthOutgoing sAMAccountName[%s] "
2817 "returning UNSUCCESSFUL\n",
2818 ndr_map_error2string(ndr_err),
2820 ldb_dn_get_linearized(user_msg->dn),
2821 ldb_dn_get_linearized(tdo_msg->dn)));
2823 return NT_STATUS_UNSUCCESSFUL;
2826 tdo_msg->num_elements = 0;
2827 TALLOC_FREE(tdo_msg->elements);
2829 ret = ldb_msg_add_empty(tdo_msg, "trustAuthIncoming",
2830 LDB_FLAG_MOD_REPLACE, NULL);
2831 if (ret != LDB_SUCCESS) {
2832 ldb_transaction_cancel(ldb);
2834 return NT_STATUS_NO_MEMORY;
2836 ret = ldb_msg_add_value(tdo_msg, "trustAuthIncoming",
2838 if (ret != LDB_SUCCESS) {
2839 ldb_transaction_cancel(ldb);
2841 return NT_STATUS_NO_MEMORY;
2844 ret = ldb_modify(ldb, tdo_msg);
2845 if (ret != LDB_SUCCESS) {
2846 nt_status = dsdb_ldb_err_to_ntstatus(ret);
2847 ldb_transaction_cancel(ldb);
2848 DEBUG(1, ("samdb_set_password_sid: "
2849 "failed to replace "
2850 "trustAuthOutgoing sAMAccountName[%s] "
2854 ldb_dn_get_linearized(user_msg->dn),
2855 ldb_dn_get_linearized(tdo_msg->dn),
2856 nt_errstr(nt_status), ldb_errstring(ldb)));
2862 nt_status = samdb_set_password_internal(ldb, mem_ctx,
2865 lmNewHash, ntNewHash,
2866 lmOldHash, ntOldHash,
2867 reject_reason, _dominfo,
2868 true); /* permit trusts */
2869 if (!NT_STATUS_IS_OK(nt_status)) {
2870 ldb_transaction_cancel(ldb);
2875 ret = ldb_transaction_commit(ldb);
2876 if (ret != LDB_SUCCESS) {
2877 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2878 ldb_dn_get_linearized(user_msg->dn),
2879 ldb_errstring(ldb)));
2881 return NT_STATUS_TRANSACTION_ABORTED;
2885 return NT_STATUS_OK;
2889 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
2890 struct dom_sid *sid, struct ldb_dn **ret_dn)
2892 struct ldb_message *msg;
2893 struct ldb_dn *basedn;
2897 sidstr = dom_sid_string(mem_ctx, sid);
2898 NT_STATUS_HAVE_NO_MEMORY(sidstr);
2900 /* We might have to create a ForeignSecurityPrincipal, even if this user
2901 * is in our own domain */
2903 msg = ldb_msg_new(sidstr);
2905 talloc_free(sidstr);
2906 return NT_STATUS_NO_MEMORY;
2909 ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2910 ldb_get_default_basedn(sam_ctx),
2911 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2913 if (ret != LDB_SUCCESS) {
2914 DEBUG(0, ("Failed to find DN for "
2915 "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2916 talloc_free(sidstr);
2917 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2920 /* add core elements to the ldb_message for the alias */
2922 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2923 talloc_free(sidstr);
2924 return NT_STATUS_NO_MEMORY;
2927 ret = ldb_msg_add_string(msg, "objectClass",
2928 "foreignSecurityPrincipal");
2929 if (ret != LDB_SUCCESS) {
2930 talloc_free(sidstr);
2931 return NT_STATUS_NO_MEMORY;
2934 /* create the alias */
2935 ret = ldb_add(sam_ctx, msg);
2936 if (ret != LDB_SUCCESS) {
2937 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2939 ldb_dn_get_linearized(msg->dn),
2940 ldb_errstring(sam_ctx)));
2941 talloc_free(sidstr);
2942 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2945 *ret_dn = talloc_steal(mem_ctx, msg->dn);
2946 talloc_free(sidstr);
2948 return NT_STATUS_OK;
2953 Find the DN of a domain, assuming it to be a dotted.dns name
2956 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
2959 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2960 const char *binary_encoded;
2961 const char * const *split_realm;
2968 split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
2970 talloc_free(tmp_ctx);
2973 dn = ldb_dn_new(mem_ctx, ldb, NULL);
2974 for (i=0; split_realm[i]; i++) {
2975 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2976 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2977 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2978 binary_encoded, ldb_dn_get_linearized(dn)));
2979 talloc_free(tmp_ctx);
2983 if (!ldb_dn_validate(dn)) {
2984 DEBUG(2, ("Failed to validated DN %s\n",
2985 ldb_dn_get_linearized(dn)));
2986 talloc_free(tmp_ctx);
2989 talloc_free(tmp_ctx);
2995 Find the DNS equivalent of a DN, in dotted DNS form
2997 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
2999 int i, num_components = ldb_dn_get_comp_num(dn);
3000 char *dns_name = talloc_strdup(mem_ctx, "");
3001 if (dns_name == NULL) {
3005 for (i=0; i<num_components; i++) {
3006 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
3009 talloc_free(dns_name);
3012 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
3013 (int)v->length, (int)v->length, (char *)v->data);
3015 talloc_free(dns_name);
3021 /* remove the last '.' */
3022 if (dns_name[0] != 0) {
3023 dns_name[strlen(dns_name)-1] = 0;
3030 Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
3031 name is based on the forest DNS name
3033 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
3034 TALLOC_CTX *mem_ctx,
3035 const struct GUID *ntds_guid)
3037 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3038 const char *guid_str;
3039 struct ldb_dn *forest_dn;
3040 const char *dnsforest;
3043 guid_str = GUID_string(tmp_ctx, ntds_guid);
3044 if (guid_str == NULL) {
3045 talloc_free(tmp_ctx);
3048 forest_dn = ldb_get_root_basedn(samdb);
3049 if (forest_dn == NULL) {
3050 talloc_free(tmp_ctx);
3053 dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
3054 if (dnsforest == NULL) {
3055 talloc_free(tmp_ctx);
3058 ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
3059 talloc_free(tmp_ctx);
3065 Find the DN of a domain, be it the netbios or DNS name
3067 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
3068 const char *domain_name)
3070 const char * const domain_ref_attrs[] = {
3073 const char * const domain_ref2_attrs[] = {
3076 struct ldb_result *res_domain_ref;
3077 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
3078 /* find the domain's DN */
3079 int ret_domain = ldb_search(ldb, mem_ctx,
3081 samdb_partitions_dn(ldb, mem_ctx),
3084 "(&(nETBIOSName=%s)(objectclass=crossRef))",
3086 if (ret_domain != LDB_SUCCESS) {
3090 if (res_domain_ref->count == 0) {
3091 ret_domain = ldb_search(ldb, mem_ctx,
3093 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
3096 "(objectclass=domain)");
3097 if (ret_domain != LDB_SUCCESS) {
3101 if (res_domain_ref->count == 1) {
3102 return res_domain_ref->msgs[0]->dn;
3107 if (res_domain_ref->count > 1) {
3108 DEBUG(0,("Found %d records matching domain [%s]\n",
3109 ret_domain, domain_name));
3113 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
3119 use a GUID to find a DN
3121 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
3122 TALLOC_CTX *mem_ctx,
3123 const struct GUID *guid,
3124 uint32_t dsdb_flags,
3128 struct ldb_result *res;
3129 const char *attrs[] = { NULL };
3130 char *guid_str = GUID_string(mem_ctx, guid);
3133 return ldb_operr(ldb);
3136 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3137 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3138 DSDB_SEARCH_SHOW_EXTENDED_DN |
3139 DSDB_SEARCH_ONE_ONLY | dsdb_flags,
3140 "objectGUID=%s", guid_str);
3141 talloc_free(guid_str);
3142 if (ret != LDB_SUCCESS) {
3146 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3153 use a DN to find a GUID with a given attribute name
3155 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
3156 struct ldb_dn *dn, const char *attribute,
3160 struct ldb_result *res;
3161 const char *attrs[2];
3162 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3164 attrs[0] = attribute;
3167 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3168 DSDB_SEARCH_SHOW_DELETED |
3169 DSDB_SEARCH_SHOW_RECYCLED);
3170 if (ret != LDB_SUCCESS) {
3171 talloc_free(tmp_ctx);
3174 if (res->count < 1) {
3175 talloc_free(tmp_ctx);
3176 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3178 *guid = samdb_result_guid(res->msgs[0], attribute);
3179 talloc_free(tmp_ctx);
3184 use a DN to find a GUID
3186 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
3187 struct ldb_dn *dn, struct GUID *guid)
3189 return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
3195 adds the given GUID to the given ldb_message. This value is added
3196 for the given attr_name (may be either "objectGUID" or "parentGUID").
3198 int dsdb_msg_add_guid(struct ldb_message *msg,
3200 const char *attr_name)
3205 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
3207 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
3208 if (!NT_STATUS_IS_OK(status)) {
3209 ret = LDB_ERR_OPERATIONS_ERROR;
3213 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
3214 if (ret != LDB_SUCCESS) {
3215 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
3223 talloc_free(tmp_ctx);
3230 use a DN to find a SID
3232 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
3233 struct ldb_dn *dn, struct dom_sid *sid)
3236 struct ldb_result *res;
3237 const char *attrs[] = { "objectSid", NULL };
3238 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3243 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3244 DSDB_SEARCH_SHOW_DELETED |
3245 DSDB_SEARCH_SHOW_RECYCLED);
3246 if (ret != LDB_SUCCESS) {
3247 talloc_free(tmp_ctx);
3250 if (res->count < 1) {
3251 talloc_free(tmp_ctx);
3252 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3254 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
3256 talloc_free(tmp_ctx);
3257 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3260 talloc_free(tmp_ctx);
3265 use a SID to find a DN
3267 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
3268 TALLOC_CTX *mem_ctx,
3269 struct dom_sid *sid, struct ldb_dn **dn)
3272 struct ldb_result *res;
3273 const char *attrs[] = { NULL };
3274 char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
3277 return ldb_operr(ldb);
3280 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3281 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3282 DSDB_SEARCH_SHOW_EXTENDED_DN |
3283 DSDB_SEARCH_ONE_ONLY,
3284 "objectSid=%s", sid_str);
3285 talloc_free(sid_str);
3286 if (ret != LDB_SUCCESS) {
3290 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3297 load a repsFromTo blob list for a given partition GUID
3298 attr must be "repsFrom" or "repsTo"
3300 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3301 const char *attr, struct repsFromToBlob **r, uint32_t *count)
3303 const char *attrs[] = { attr, NULL };
3304 struct ldb_result *res = NULL;
3305 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3307 struct ldb_message_element *el;
3313 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
3314 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3315 /* partition hasn't been replicated yet */
3318 if (ret != LDB_SUCCESS) {
3319 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
3320 talloc_free(tmp_ctx);
3321 return WERR_DS_DRA_INTERNAL_ERROR;
3324 el = ldb_msg_find_element(res->msgs[0], attr);
3326 /* it's OK to be empty */
3327 talloc_free(tmp_ctx);
3331 *count = el->num_values;
3332 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
3334 talloc_free(tmp_ctx);
3335 return WERR_DS_DRA_INTERNAL_ERROR;
3338 for (i=0; i<(*count); i++) {
3339 enum ndr_err_code ndr_err;
3340 ndr_err = ndr_pull_struct_blob(&el->values[i],
3343 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3344 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3345 talloc_free(tmp_ctx);
3346 return WERR_DS_DRA_INTERNAL_ERROR;
3350 talloc_free(tmp_ctx);
3356 save the repsFromTo blob list for a given partition GUID
3357 attr must be "repsFrom" or "repsTo"
3359 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3360 const char *attr, struct repsFromToBlob *r, uint32_t count)
3362 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3363 struct ldb_message *msg;
3364 struct ldb_message_element *el;
3367 msg = ldb_msg_new(tmp_ctx);
3369 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
3373 el->values = talloc_array(msg, struct ldb_val, count);
3378 for (i=0; i<count; i++) {
3380 enum ndr_err_code ndr_err;
3382 ndr_err = ndr_push_struct_blob(&v, tmp_ctx,
3384 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3385 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3393 if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
3394 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
3398 talloc_free(tmp_ctx);
3403 talloc_free(tmp_ctx);
3404 return WERR_DS_DRA_INTERNAL_ERROR;
3409 load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
3410 object for a partition
3412 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
3413 uint64_t *uSN, uint64_t *urgent_uSN)
3415 struct ldb_request *req;
3417 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3418 struct dsdb_control_current_partition *p_ctrl;
3419 struct ldb_result *res;
3421 res = talloc_zero(tmp_ctx, struct ldb_result);
3423 talloc_free(tmp_ctx);
3424 return ldb_oom(ldb);
3427 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3428 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
3432 res, ldb_search_default_callback,
3434 if (ret != LDB_SUCCESS) {
3435 talloc_free(tmp_ctx);
3439 p_ctrl = talloc(req, struct dsdb_control_current_partition);
3440 if (p_ctrl == NULL) {
3441 talloc_free(tmp_ctx);
3442 return ldb_oom(ldb);
3444 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
3447 ret = ldb_request_add_control(req,
3448 DSDB_CONTROL_CURRENT_PARTITION_OID,
3450 if (ret != LDB_SUCCESS) {
3451 talloc_free(tmp_ctx);
3455 /* Run the new request */
3456 ret = ldb_request(ldb, req);
3458 if (ret == LDB_SUCCESS) {
3459 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3462 if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
3463 /* it hasn't been created yet, which means
3464 an implicit value of zero */
3466 talloc_free(tmp_ctx);
3470 if (ret != LDB_SUCCESS) {
3471 talloc_free(tmp_ctx);
3475 if (res->count < 1) {
3481 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
3483 *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
3487 talloc_free(tmp_ctx);
3492 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
3493 const struct drsuapi_DsReplicaCursor2 *c2)
3495 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3498 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
3499 const struct drsuapi_DsReplicaCursor *c2)
3501 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3506 see if a computer identified by its invocationId is a RODC
3508 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
3510 /* 1) find the DN for this servers NTDSDSA object
3511 2) search for the msDS-isRODC attribute
3512 3) if not present then not a RODC
3513 4) if present and TRUE then is a RODC
3515 struct ldb_dn *config_dn;
3516 const char *attrs[] = { "msDS-isRODC", NULL };
3518 struct ldb_result *res;
3519 TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
3521 config_dn = ldb_get_config_basedn(sam_ctx);
3523 talloc_free(tmp_ctx);
3524 return ldb_operr(sam_ctx);
3527 ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
3528 DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
3530 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3532 talloc_free(tmp_ctx);
3536 if (ret != LDB_SUCCESS) {
3537 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
3538 GUID_string(tmp_ctx, objectGUID)));
3540 talloc_free(tmp_ctx);
3544 ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
3545 *is_rodc = (ret == 1);
3547 talloc_free(tmp_ctx);
3553 see if we are a RODC
3555 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
3557 const struct GUID *objectGUID;
3561 /* see if we have a cached copy */
3562 cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
3568 objectGUID = samdb_ntds_objectGUID(sam_ctx);
3570 return ldb_operr(sam_ctx);
3573 ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
3574 if (ret != LDB_SUCCESS) {
3578 cached = talloc(sam_ctx, bool);
3579 if (cached == NULL) {
3580 return ldb_oom(sam_ctx);
3584 ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
3585 if (ret != LDB_SUCCESS) {
3586 talloc_free(cached);
3587 return ldb_operr(sam_ctx);
3593 int samdb_dns_host_name(struct ldb_context *sam_ctx, const char **host_name)
3595 const char *_host_name = NULL;
3596 const char *attrs[] = { "dnsHostName", NULL };
3597 TALLOC_CTX *tmp_ctx = NULL;
3599 struct ldb_result *res = NULL;
3601 _host_name = (const char *)ldb_get_opaque(sam_ctx, "cache.dns_host_name");
3602 if (_host_name != NULL) {
3603 *host_name = _host_name;
3607 tmp_ctx = talloc_new(sam_ctx);
3609 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, NULL, attrs, 0);
3611 if (res->count != 1 || ret != LDB_SUCCESS) {
3612 DEBUG(0, ("Failed to get rootDSE for dnsHostName: %s",
3613 ldb_errstring(sam_ctx)));
3614 TALLOC_FREE(tmp_ctx);
3619 _host_name = ldb_msg_find_attr_as_string(res->msgs[0],
3622 if (_host_name == NULL) {
3623 DEBUG(0, ("Failed to get dnsHostName from rootDSE"));
3624 TALLOC_FREE(tmp_ctx);
3625 return LDB_ERR_OPERATIONS_ERROR;
3627 ret = ldb_set_opaque(sam_ctx, "cache.dns_host_name",
3628 discard_const_p(char *, _host_name));
3629 if (ret != LDB_SUCCESS) {
3630 TALLOC_FREE(tmp_ctx);
3631 return ldb_operr(sam_ctx);
3634 *host_name = talloc_steal(sam_ctx, _host_name);
3636 TALLOC_FREE(tmp_ctx);
3640 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3642 TALLOC_CTX *tmp_ctx;
3645 tmp_ctx = talloc_new(ldb);
3646 if (tmp_ctx == NULL) {
3650 cached = talloc(tmp_ctx, bool);
3656 if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3660 talloc_steal(ldb, cached);
3661 talloc_free(tmp_ctx);
3665 DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3666 talloc_free(tmp_ctx);
3672 * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3673 * flags are DS_NTDSSETTINGS_OPT_*
3675 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3679 TALLOC_CTX *tmp_ctx;
3680 struct ldb_result *res;
3681 struct ldb_dn *site_dn;
3682 const char *attrs[] = { "options", NULL };
3684 tmp_ctx = talloc_new(ldb_ctx);
3685 if (tmp_ctx == NULL)
3688 /* Retrieve the site dn for the ldb that we
3689 * have open. This is our local site.
3691 site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3692 if (site_dn == NULL)
3695 /* Perform a one level (child) search from the local
3696 * site distinguided name. We're looking for the
3697 * "options" attribute within the nTDSSiteSettings
3700 rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3701 LDB_SCOPE_ONELEVEL, attrs,
3702 "objectClass=nTDSSiteSettings");
3704 if (rc != LDB_SUCCESS || res->count != 1)
3707 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3709 talloc_free(tmp_ctx);
3714 DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3715 talloc_free(tmp_ctx);
3716 return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
3720 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
3722 flags are DS_NTDS_OPTION_*
3724 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3726 TALLOC_CTX *tmp_ctx;
3727 const char *attrs[] = { "options", NULL };
3729 struct ldb_result *res;
3731 tmp_ctx = talloc_new(ldb);
3732 if (tmp_ctx == NULL) {
3736 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3737 if (ret != LDB_SUCCESS) {
3741 if (res->count != 1) {
3745 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3747 talloc_free(tmp_ctx);
3752 DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3753 talloc_free(tmp_ctx);
3754 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3757 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3759 const char *attrs[] = { "objectCategory", NULL };
3761 struct ldb_result *res;
3763 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3764 if (ret != LDB_SUCCESS) {
3768 if (res->count != 1) {
3772 return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3775 DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3780 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3781 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3783 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3785 char **tokens, *ret;
3788 tokens = str_list_make(mem_ctx, cn, " -_");
3789 if (tokens == NULL || tokens[0] == NULL) {
3793 /* "tolower()" and "toupper()" should also work properly on 0x00 */
3794 tokens[0][0] = tolower(tokens[0][0]);
3795 for (i = 1; tokens[i] != NULL; i++)
3796 tokens[i][0] = toupper(tokens[i][0]);
3798 ret = talloc_strdup(mem_ctx, tokens[0]);
3799 for (i = 1; tokens[i] != NULL; i++)
3800 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3802 talloc_free(tokens);
3808 * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3810 int dsdb_functional_level(struct ldb_context *ldb)
3812 int *domainFunctionality =
3813 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3814 if (!domainFunctionality) {
3815 /* this is expected during initial provision */
3816 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3817 return DS_DOMAIN_FUNCTION_2000;
3819 return *domainFunctionality;
3823 * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3825 int dsdb_forest_functional_level(struct ldb_context *ldb)
3827 int *forestFunctionality =
3828 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3829 if (!forestFunctionality) {
3830 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3831 return DS_DOMAIN_FUNCTION_2000;
3833 return *forestFunctionality;
3837 set a GUID in an extended DN structure
3839 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3845 status = GUID_to_ndr_blob(guid, dn, &v);
3846 if (!NT_STATUS_IS_OK(status)) {
3847 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3850 ret = ldb_dn_set_extended_component(dn, component_name, &v);
3856 return a GUID from a extended DN structure
3858 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3860 const struct ldb_val *v;
3862 v = ldb_dn_get_extended_component(dn, component_name);
3864 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3867 return GUID_from_ndr_blob(v, guid);
3871 return a uint64_t from a extended DN structure
3873 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3875 const struct ldb_val *v;
3877 v = ldb_dn_get_extended_component(dn, component_name);
3879 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3882 /* Just check we don't allow the caller to fill our stack */
3883 if (v->length >= 64) {
3884 return NT_STATUS_INVALID_PARAMETER;
3886 char s[v->length+1];
3887 memcpy(s, v->data, v->length);
3890 *val = strtoull(s, NULL, 0);
3892 return NT_STATUS_OK;
3896 return a NTTIME from a extended DN structure
3898 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3900 return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3904 return a uint32_t from a extended DN structure
3906 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3908 const struct ldb_val *v;
3910 v = ldb_dn_get_extended_component(dn, component_name);
3912 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3915 /* Just check we don't allow the caller to fill our stack */
3916 if (v->length >= 32) {
3917 return NT_STATUS_INVALID_PARAMETER;
3919 char s[v->length + 1];
3920 memcpy(s, v->data, v->length);
3922 *val = strtoul(s, NULL, 0);
3925 return NT_STATUS_OK;
3929 return a dom_sid from a extended DN structure
3931 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3933 const struct ldb_val *sid_blob;
3934 enum ndr_err_code ndr_err;
3936 sid_blob = ldb_dn_get_extended_component(dn, component_name);
3938 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3941 ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
3942 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3943 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3944 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3948 return NT_STATUS_OK;
3953 return RMD_FLAGS directly from a ldb_dn
3954 returns 0 if not found
3956 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3958 uint32_t rmd_flags = 0;
3959 NTSTATUS status = dsdb_get_extended_dn_uint32(dn, &rmd_flags,
3961 if (NT_STATUS_IS_OK(status)) {
3968 return RMD_FLAGS directly from a ldb_val for a DN
3969 returns 0 if RMD_FLAGS is not found
3971 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3977 if (val->length < 13) {
3980 p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3984 flags = strtoul(p+11, &end, 10);
3985 if (!end || *end != '>') {
3986 /* it must end in a > */
3993 return true if a ldb_val containing a DN in storage form is deleted
3995 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3997 return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
4001 return true if a ldb_val containing a DN in storage form is
4002 in the upgraded w2k3 linked attribute format
4004 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
4006 return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
4010 return a DN for a wellknown GUID
4012 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
4013 struct ldb_dn *nc_root, const char *wk_guid,
4014 struct ldb_dn **wkguid_dn)
4016 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4017 const char *attrs[] = { NULL };
4020 struct ldb_result *res;
4022 /* construct the magic WKGUID DN */
4023 dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
4024 wk_guid, ldb_dn_get_linearized(nc_root));
4026 talloc_free(tmp_ctx);
4027 return ldb_operr(samdb);
4030 ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
4031 DSDB_SEARCH_SHOW_DELETED |
4032 DSDB_SEARCH_SHOW_RECYCLED);
4033 if (ret != LDB_SUCCESS) {
4034 talloc_free(tmp_ctx);
4038 (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
4039 talloc_free(tmp_ctx);
4044 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
4046 return ldb_dn_compare(*dn1, *dn2);
4050 find a NC root given a DN within the NC
4052 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
4053 struct ldb_dn **nc_root)
4055 const char *root_attrs[] = { "namingContexts", NULL };
4056 TALLOC_CTX *tmp_ctx;
4058 struct ldb_message_element *el;
4059 struct ldb_result *root_res;
4061 struct ldb_dn **nc_dns;
4063 tmp_ctx = talloc_new(samdb);
4064 if (tmp_ctx == NULL) {
4065 return ldb_oom(samdb);
4068 ret = ldb_search(samdb, tmp_ctx, &root_res,
4069 ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
4070 if (ret != LDB_SUCCESS || root_res->count == 0) {
4071 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
4072 talloc_free(tmp_ctx);
4076 el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
4077 if ((el == NULL) || (el->num_values < 3)) {
4078 struct ldb_message *tmp_msg;
4080 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list.\n"));
4082 /* This generates a temporary list of NCs in order to let the
4083 * provisioning work. */
4084 tmp_msg = ldb_msg_new(tmp_ctx);
4085 if (tmp_msg == NULL) {
4086 talloc_free(tmp_ctx);
4087 return ldb_oom(samdb);
4089 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4090 ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
4091 if (ret != LDB_SUCCESS) {
4092 talloc_free(tmp_ctx);
4095 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4096 ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
4097 if (ret != LDB_SUCCESS) {
4098 talloc_free(tmp_ctx);
4101 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4102 ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
4103 if (ret != LDB_SUCCESS) {
4104 talloc_free(tmp_ctx);
4107 el = &tmp_msg->elements[0];
4110 nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
4112 talloc_free(tmp_ctx);
4113 return ldb_oom(samdb);
4116 for (i=0; i<el->num_values; i++) {
4117 nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
4118 if (nc_dns[i] == NULL) {
4119 talloc_free(tmp_ctx);
4120 return ldb_operr(samdb);
4124 TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
4126 for (i=0; i<el->num_values; i++) {
4127 if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
4128 (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
4129 talloc_free(tmp_ctx);
4134 talloc_free(tmp_ctx);
4135 return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4140 find the deleted objects DN for any object, by looking for the NC
4141 root, then looking up the wellknown GUID
4143 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
4144 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
4145 struct ldb_dn **do_dn)
4147 struct ldb_dn *nc_root;
4150 ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
4151 if (ret != LDB_SUCCESS) {
4155 ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
4156 talloc_free(nc_root);
4161 return the tombstoneLifetime, in days
4163 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
4166 dn = ldb_get_config_basedn(ldb);
4168 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4170 dn = ldb_dn_copy(ldb, dn);
4172 return ldb_operr(ldb);
4174 /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
4175 be a wellknown GUID for this */
4176 if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
4178 return ldb_operr(ldb);
4181 *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
4187 compare a ldb_val to a string case insensitively
4189 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
4191 size_t len = strlen(s);
4193 if (len > v->length) return 1;
4194 ret = strncasecmp(s, (const char *)v->data, v->length);
4195 if (ret != 0) return ret;
4196 if (v->length > len && v->data[len] != 0) {
4204 load the UDV for a partition in v2 format
4205 The list is returned sorted, and with our local cursor added
4207 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4208 struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
4210 static const char *attrs[] = { "replUpToDateVector", NULL };
4211 struct ldb_result *r;
4212 const struct ldb_val *ouv_value;
4215 uint64_t highest_usn = 0;
4216 const struct GUID *our_invocation_id;
4217 static const struct timeval tv1970;
4218 NTTIME nt1970 = timeval_to_nttime(&tv1970);
4220 ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
4221 if (ret != LDB_SUCCESS) {
4225 ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
4227 enum ndr_err_code ndr_err;
4228 struct replUpToDateVectorBlob ouv;
4230 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
4231 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
4232 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4234 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4236 if (ouv.version != 2) {
4237 /* we always store as version 2, and
4238 * replUpToDateVector is not replicated
4240 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4243 *count = ouv.ctr.ctr2.count;
4244 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
4252 our_invocation_id = samdb_ntds_invocation_id(samdb);
4253 if (!our_invocation_id) {
4254 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
4255 talloc_free(*cursors);
4256 return ldb_operr(samdb);
4259 ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
4260 if (ret != LDB_SUCCESS) {
4261 /* nothing to add - this can happen after a vampire */
4262 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4266 for (i=0; i<*count; i++) {
4267 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
4268 (*cursors)[i].highest_usn = highest_usn;
4269 (*cursors)[i].last_sync_success = nt1970;
4270 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4275 (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
4277 return ldb_oom(samdb);
4280 (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
4281 (*cursors)[*count].highest_usn = highest_usn;
4282 (*cursors)[*count].last_sync_success = nt1970;
4285 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4291 load the UDV for a partition in version 1 format
4292 The list is returned sorted, and with our local cursor added
4294 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4295 struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
4297 struct drsuapi_DsReplicaCursor2 *v2;
4301 ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
4302 if (ret != LDB_SUCCESS) {
4312 *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
4313 if (*cursors == NULL) {
4315 return ldb_oom(samdb);
4318 for (i=0; i<*count; i++) {
4319 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
4320 (*cursors)[i].highest_usn = v2[i].highest_usn;
4327 add a set of controls to a ldb_request structure based on a set of
4328 flags. See util.h for a list of available flags
4330 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
4333 if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
4334 struct ldb_search_options_control *options;
4335 /* Using the phantom root control allows us to search all partitions */
4336 options = talloc(req, struct ldb_search_options_control);
4337 if (options == NULL) {
4338 return LDB_ERR_OPERATIONS_ERROR;
4340 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
4342 ret = ldb_request_add_control(req,
4343 LDB_CONTROL_SEARCH_OPTIONS_OID,
4345 if (ret != LDB_SUCCESS) {
4350 if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
4351 ret = ldb_request_add_control(req,
4352 DSDB_CONTROL_NO_GLOBAL_CATALOG,
4354 if (ret != LDB_SUCCESS) {
4359 if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
4360 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
4361 if (ret != LDB_SUCCESS) {
4366 if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
4367 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
4368 if (ret != LDB_SUCCESS) {
4373 if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
4374 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
4375 if (ret != LDB_SUCCESS) {
4380 if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
4381 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
4382 if (!extended_ctrl) {
4383 return LDB_ERR_OPERATIONS_ERROR;
4385 extended_ctrl->type = 1;
4387 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
4388 if (ret != LDB_SUCCESS) {
4393 if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
4394 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
4395 if (ret != LDB_SUCCESS) {
4400 if (dsdb_flags & DSDB_MODIFY_RELAX) {
4401 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
4402 if (ret != LDB_SUCCESS) {
4407 if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
4408 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
4409 if (ret != LDB_SUCCESS) {
4414 if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
4415 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
4416 if (ret != LDB_SUCCESS) {
4421 if (dsdb_flags & DSDB_TREE_DELETE) {
4422 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
4423 if (ret != LDB_SUCCESS) {
4428 if (dsdb_flags & DSDB_PROVISION) {
4429 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
4430 if (ret != LDB_SUCCESS) {
4435 /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
4436 if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
4437 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
4438 if (ret != LDB_SUCCESS) {
4443 if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
4445 * This must not be critical, as it will only be
4446 * handled (and need to be handled) if the other
4447 * attributes in the request bring password_hash into
4450 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
4451 if (ret != LDB_SUCCESS) {
4456 if (dsdb_flags & DSDB_REPLMD_VANISH_LINKS) {
4457 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLMD_VANISH_LINKS, true, NULL);
4458 if (ret != LDB_SUCCESS) {
4463 if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
4464 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
4465 if (ret != LDB_SUCCESS) {
4470 if (dsdb_flags & DSDB_FLAG_REPLICATED_UPDATE) {
4471 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
4472 if (ret != LDB_SUCCESS) {
4481 returns true if a control with the specified "oid" exists
4483 bool dsdb_request_has_control(struct ldb_request *req, const char *oid)
4485 return (ldb_request_get_control(req, oid) != NULL);
4489 an add with a set of controls
4491 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
4492 uint32_t dsdb_flags)
4494 struct ldb_request *req;
4497 ret = ldb_build_add_req(&req, ldb, ldb,
4501 ldb_op_default_callback,
4504 if (ret != LDB_SUCCESS) return ret;
4506 ret = dsdb_request_add_controls(req, dsdb_flags);
4507 if (ret != LDB_SUCCESS) {
4512 ret = dsdb_autotransaction_request(ldb, req);
4519 a modify with a set of controls
4521 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
4522 uint32_t dsdb_flags)
4524 struct ldb_request *req;
4527 ret = ldb_build_mod_req(&req, ldb, ldb,
4531 ldb_op_default_callback,
4534 if (ret != LDB_SUCCESS) return ret;
4536 ret = dsdb_request_add_controls(req, dsdb_flags);
4537 if (ret != LDB_SUCCESS) {
4542 ret = dsdb_autotransaction_request(ldb, req);
4549 a delete with a set of flags
4551 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
4552 uint32_t dsdb_flags)
4554 struct ldb_request *req;
4557 ret = ldb_build_del_req(&req, ldb, ldb,
4561 ldb_op_default_callback,
4564 if (ret != LDB_SUCCESS) return ret;
4566 ret = dsdb_request_add_controls(req, dsdb_flags);
4567 if (ret != LDB_SUCCESS) {
4572 ret = dsdb_autotransaction_request(ldb, req);
4579 like dsdb_modify() but set all the element flags to
4580 LDB_FLAG_MOD_REPLACE
4582 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
4586 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
4587 for (i=0;i<msg->num_elements;i++) {
4588 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
4591 return dsdb_modify(ldb, msg, dsdb_flags);
4596 search for attrs on one DN, allowing for dsdb_flags controls
4598 int dsdb_search_dn(struct ldb_context *ldb,
4599 TALLOC_CTX *mem_ctx,
4600 struct ldb_result **_result,
4601 struct ldb_dn *basedn,
4602 const char * const *attrs,
4603 uint32_t dsdb_flags)
4606 struct ldb_request *req;
4607 struct ldb_result *res;
4609 res = talloc_zero(mem_ctx, struct ldb_result);
4611 return ldb_oom(ldb);
4614 ret = ldb_build_search_req(&req, ldb, res,
4621 ldb_search_default_callback,
4623 if (ret != LDB_SUCCESS) {
4628 ret = dsdb_request_add_controls(req, dsdb_flags);
4629 if (ret != LDB_SUCCESS) {
4634 ret = ldb_request(ldb, req);
4635 if (ret == LDB_SUCCESS) {
4636 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4640 if (ret != LDB_SUCCESS) {
4650 search for attrs on one DN, by the GUID of the DN, allowing for
4653 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
4654 TALLOC_CTX *mem_ctx,
4655 struct ldb_result **_result,
4656 const struct GUID *guid,
4657 const char * const *attrs,
4658 uint32_t dsdb_flags)
4660 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4664 dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
4666 talloc_free(tmp_ctx);
4667 return ldb_oom(ldb);
4670 ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
4671 talloc_free(tmp_ctx);
4676 general search with dsdb_flags for controls
4678 int dsdb_search(struct ldb_context *ldb,
4679 TALLOC_CTX *mem_ctx,
4680 struct ldb_result **_result,
4681 struct ldb_dn *basedn,
4682 enum ldb_scope scope,
4683 const char * const *attrs,
4684 uint32_t dsdb_flags,
4685 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4688 struct ldb_request *req;
4689 struct ldb_result *res;
4691 char *expression = NULL;
4692 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4694 /* cross-partitions searches with a basedn break multi-domain support */
4695 SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
4697 res = talloc_zero(tmp_ctx, struct ldb_result);
4699 talloc_free(tmp_ctx);
4700 return ldb_oom(ldb);
4704 va_start(ap, exp_fmt);
4705 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4709 talloc_free(tmp_ctx);
4710 return ldb_oom(ldb);
4714 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
4721 ldb_search_default_callback,
4723 if (ret != LDB_SUCCESS) {
4724 talloc_free(tmp_ctx);
4728 ret = dsdb_request_add_controls(req, dsdb_flags);
4729 if (ret != LDB_SUCCESS) {
4730 talloc_free(tmp_ctx);
4731 ldb_reset_err_string(ldb);
4735 ret = ldb_request(ldb, req);
4736 if (ret == LDB_SUCCESS) {
4737 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4740 if (ret != LDB_SUCCESS) {
4741 talloc_free(tmp_ctx);
4745 if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
4746 if (res->count == 0) {
4747 talloc_free(tmp_ctx);
4748 ldb_reset_err_string(ldb);
4749 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4751 if (res->count != 1) {
4752 talloc_free(tmp_ctx);
4753 ldb_reset_err_string(ldb);
4754 return LDB_ERR_CONSTRAINT_VIOLATION;
4758 *_result = talloc_steal(mem_ctx, res);
4759 talloc_free(tmp_ctx);
4766 general search with dsdb_flags for controls
4767 returns exactly 1 record or an error
4769 int dsdb_search_one(struct ldb_context *ldb,
4770 TALLOC_CTX *mem_ctx,
4771 struct ldb_message **msg,
4772 struct ldb_dn *basedn,
4773 enum ldb_scope scope,
4774 const char * const *attrs,
4775 uint32_t dsdb_flags,
4776 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4779 struct ldb_result *res;
4781 char *expression = NULL;
4782 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4784 dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4786 res = talloc_zero(tmp_ctx, struct ldb_result);
4788 talloc_free(tmp_ctx);
4789 return ldb_oom(ldb);
4793 va_start(ap, exp_fmt);
4794 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4798 talloc_free(tmp_ctx);
4799 return ldb_oom(ldb);
4801 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4802 dsdb_flags, "%s", expression);
4804 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4808 if (ret != LDB_SUCCESS) {
4809 talloc_free(tmp_ctx);
4813 *msg = talloc_steal(mem_ctx, res->msgs[0]);
4814 talloc_free(tmp_ctx);
4819 /* returns back the forest DNS name */
4820 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4822 const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4823 ldb_get_root_basedn(ldb));
4826 if (forest_name == NULL) {
4830 p = strchr(forest_name, '/');
4838 /* returns back the default domain DNS name */
4839 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4841 const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4842 ldb_get_default_basedn(ldb));
4845 if (domain_name == NULL) {
4849 p = strchr(domain_name, '/');
4858 validate that an DSA GUID belongs to the specified user sid.
4859 The user SID must be a domain controller account (either RODC or
4862 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4863 const struct GUID *dsa_guid,
4864 const struct dom_sid *sid)
4867 - find DN of record with the DSA GUID in the
4868 configuration partition (objectGUID)
4869 - remove "NTDS Settings" component from DN
4870 - do a base search on that DN for serverReference with
4872 - extract objectSid from resulting serverReference
4874 - check this sid matches the sid argument
4876 struct ldb_dn *config_dn;
4877 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4878 struct ldb_message *msg;
4879 const char *attrs1[] = { NULL };
4880 const char *attrs2[] = { "serverReference", NULL };
4882 struct ldb_dn *dn, *account_dn;
4883 struct dom_sid sid2;
4886 config_dn = ldb_get_config_basedn(ldb);
4888 ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4889 attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4890 if (ret != LDB_SUCCESS) {
4891 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4892 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4893 talloc_free(tmp_ctx);
4894 return ldb_operr(ldb);
4898 if (!ldb_dn_remove_child_components(dn, 1)) {
4899 talloc_free(tmp_ctx);
4900 return ldb_operr(ldb);
4903 ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4904 attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4905 "(objectClass=server)");
4906 if (ret != LDB_SUCCESS) {
4907 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4908 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4909 talloc_free(tmp_ctx);
4910 return ldb_operr(ldb);
4913 account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4914 if (account_dn == NULL) {
4915 DEBUG(1,(__location__ ": Failed to find account dn "
4916 "(serverReference) for %s, parent of DSA with "
4917 "objectGUID %s, sid %s\n",
4918 ldb_dn_get_linearized(msg->dn),
4919 GUID_string(tmp_ctx, dsa_guid),
4920 dom_sid_string(tmp_ctx, sid)));
4921 talloc_free(tmp_ctx);
4922 return ldb_operr(ldb);
4925 status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4926 if (!NT_STATUS_IS_OK(status)) {
4927 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4928 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4929 talloc_free(tmp_ctx);
4930 return ldb_operr(ldb);
4933 if (!dom_sid_equal(sid, &sid2)) {
4934 /* someone is trying to spoof another account */
4935 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4936 GUID_string(tmp_ctx, dsa_guid),
4937 dom_sid_string(tmp_ctx, sid),
4938 dom_sid_string(tmp_ctx, &sid2)));
4939 talloc_free(tmp_ctx);
4940 return ldb_operr(ldb);
4943 talloc_free(tmp_ctx);
4947 static const char * const secret_attributes[] = {
4948 DSDB_SECRET_ATTRIBUTES,
4953 check if the attribute belongs to the RODC filtered attribute set
4954 Note that attributes that are in the filtered attribute set are the
4955 ones that _are_ always sent to a RODC
4957 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4959 /* they never get secret attributes */
4960 if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4964 /* they do get non-secret critical attributes */
4965 if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4969 /* they do get non-secret attributes marked as being in the FAS */
4970 if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4974 /* other attributes are denied */
4978 /* return fsmo role dn and role owner dn for a particular role*/
4979 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4980 struct ldb_context *ldb,
4982 struct ldb_dn **fsmo_role_dn,
4983 struct ldb_dn **role_owner_dn)
4987 case DREPL_NAMING_MASTER:
4988 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4989 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4990 if (ret != LDB_SUCCESS) {
4991 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4992 ldb_errstring(ldb)));
4993 talloc_free(tmp_ctx);
4994 return WERR_DS_DRA_INTERNAL_ERROR;
4997 case DREPL_INFRASTRUCTURE_MASTER:
4998 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4999 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5000 if (ret != LDB_SUCCESS) {
5001 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5002 ldb_errstring(ldb)));
5003 talloc_free(tmp_ctx);
5004 return WERR_DS_DRA_INTERNAL_ERROR;
5007 case DREPL_RID_MASTER:
5008 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
5009 if (ret != LDB_SUCCESS) {
5010 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
5011 talloc_free(tmp_ctx);
5012 return WERR_DS_DRA_INTERNAL_ERROR;
5015 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5016 if (ret != LDB_SUCCESS) {
5017 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
5018 ldb_errstring(ldb)));
5019 talloc_free(tmp_ctx);
5020 return WERR_DS_DRA_INTERNAL_ERROR;
5023 case DREPL_SCHEMA_MASTER:
5024 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
5025 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5026 if (ret != LDB_SUCCESS) {
5027 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5028 ldb_errstring(ldb)));
5029 talloc_free(tmp_ctx);
5030 return WERR_DS_DRA_INTERNAL_ERROR;
5033 case DREPL_PDC_MASTER:
5034 *fsmo_role_dn = ldb_get_default_basedn(ldb);
5035 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5036 if (ret != LDB_SUCCESS) {
5037 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
5038 ldb_errstring(ldb)));
5039 talloc_free(tmp_ctx);
5040 return WERR_DS_DRA_INTERNAL_ERROR;
5044 return WERR_DS_DRA_INTERNAL_ERROR;
5049 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
5050 TALLOC_CTX *mem_ctx,
5051 struct ldb_dn *server_dn)
5054 struct ldb_result *res = NULL;
5055 const char * const attrs[] = { "dNSHostName", NULL};
5057 ldb_ret = ldb_search(ldb, mem_ctx, &res,
5061 if (ldb_ret != LDB_SUCCESS) {
5062 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
5063 ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
5067 return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
5071 returns true if an attribute is in the filter,
5072 false otherwise, provided that attribute value is provided with the expression
5074 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
5078 switch (tree->operation) {
5081 for (i=0;i<tree->u.list.num_elements;i++) {
5082 if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
5088 return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
5089 case LDB_OP_EQUALITY:
5090 case LDB_OP_GREATER:
5093 if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
5097 case LDB_OP_SUBSTRING:
5098 if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
5102 case LDB_OP_PRESENT:
5103 /* (attrname=*) is not filtered out */
5105 case LDB_OP_EXTENDED:
5106 if (tree->u.extended.attr &&
5107 ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
5115 bool is_attr_in_list(const char * const * attrs, const char *attr)
5119 for (i = 0; attrs[i]; i++) {
5120 if (ldb_attr_cmp(attrs[i], attr) == 0)
5127 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
5128 const char *location, const char *func,
5131 if (reason == NULL) {
5132 reason = win_errstr(werr);
5134 ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
5135 W_ERROR_V(werr), reason, location, func);
5140 map an ldb error code to an approximate NTSTATUS code
5142 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
5146 return NT_STATUS_OK;
5148 case LDB_ERR_PROTOCOL_ERROR:
5149 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
5151 case LDB_ERR_TIME_LIMIT_EXCEEDED:
5152 return NT_STATUS_IO_TIMEOUT;
5154 case LDB_ERR_SIZE_LIMIT_EXCEEDED:
5155 return NT_STATUS_BUFFER_TOO_SMALL;
5157 case LDB_ERR_COMPARE_FALSE:
5158 case LDB_ERR_COMPARE_TRUE:
5159 return NT_STATUS_REVISION_MISMATCH;
5161 case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
5162 return NT_STATUS_NOT_SUPPORTED;
5164 case LDB_ERR_STRONG_AUTH_REQUIRED:
5165 case LDB_ERR_CONFIDENTIALITY_REQUIRED:
5166 case LDB_ERR_SASL_BIND_IN_PROGRESS:
5167 case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
5168 case LDB_ERR_INVALID_CREDENTIALS:
5169 case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
5170 case LDB_ERR_UNWILLING_TO_PERFORM:
5171 return NT_STATUS_ACCESS_DENIED;
5173 case LDB_ERR_NO_SUCH_OBJECT:
5174 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
5176 case LDB_ERR_REFERRAL:
5177 case LDB_ERR_NO_SUCH_ATTRIBUTE:
5178 return NT_STATUS_NOT_FOUND;
5180 case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
5181 return NT_STATUS_NOT_SUPPORTED;
5183 case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
5184 return NT_STATUS_BUFFER_TOO_SMALL;
5186 case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
5187 case LDB_ERR_INAPPROPRIATE_MATCHING:
5188 case LDB_ERR_CONSTRAINT_VIOLATION:
5189 case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
5190 case LDB_ERR_INVALID_DN_SYNTAX:
5191 case LDB_ERR_NAMING_VIOLATION:
5192 case LDB_ERR_OBJECT_CLASS_VIOLATION:
5193 case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
5194 case LDB_ERR_NOT_ALLOWED_ON_RDN:
5195 return NT_STATUS_INVALID_PARAMETER;
5197 case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
5198 case LDB_ERR_ENTRY_ALREADY_EXISTS:
5199 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
5202 return NT_STATUS_NETWORK_BUSY;
5204 case LDB_ERR_ALIAS_PROBLEM:
5205 case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
5206 case LDB_ERR_UNAVAILABLE:
5207 case LDB_ERR_LOOP_DETECT:
5208 case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
5209 case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
5211 case LDB_ERR_OPERATIONS_ERROR:
5214 return NT_STATUS_UNSUCCESSFUL;
5219 create a new naming context that will hold a partial replica
5221 int dsdb_create_partial_replica_NC(struct ldb_context *ldb, struct ldb_dn *dn)
5223 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5224 struct ldb_message *msg;
5227 msg = ldb_msg_new(tmp_ctx);
5229 talloc_free(tmp_ctx);
5230 return ldb_oom(ldb);
5234 ret = ldb_msg_add_string(msg, "objectClass", "top");
5235 if (ret != LDB_SUCCESS) {
5236 talloc_free(tmp_ctx);
5237 return ldb_oom(ldb);
5240 /* [MS-DRSR] implies that we should only add the 'top'
5241 * objectclass, but that would cause lots of problems with our
5242 * objectclass code as top is not structural, so we add
5243 * 'domainDNS' as well to keep things sane. We're expecting
5244 * this new NC to be of objectclass domainDNS after
5245 * replication anyway
5247 ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
5248 if (ret != LDB_SUCCESS) {
5249 talloc_free(tmp_ctx);
5250 return ldb_oom(ldb);
5253 ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
5254 INSTANCE_TYPE_IS_NC_HEAD|
5255 INSTANCE_TYPE_NC_ABOVE|
5256 INSTANCE_TYPE_UNINSTANT);
5257 if (ret != LDB_SUCCESS) {
5258 talloc_free(tmp_ctx);
5259 return ldb_oom(ldb);
5262 ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
5263 if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
5264 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
5265 ldb_dn_get_linearized(dn),
5266 ldb_errstring(ldb), ldb_strerror(ret)));
5267 talloc_free(tmp_ctx);
5271 DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
5273 talloc_free(tmp_ctx);
5278 build a GUID from a string
5280 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
5282 NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
5284 uint32_t time_mid, time_hi_and_version;
5285 uint32_t clock_seq[2];
5290 return NT_STATUS_INVALID_PARAMETER;
5293 status = parse_guid_string(s,
5296 &time_hi_and_version,
5300 if (!NT_STATUS_IS_OK(status)) {
5304 guid->time_low = time_low;
5305 guid->time_mid = time_mid;
5306 guid->time_hi_and_version = time_hi_and_version;
5307 guid->clock_seq[0] = clock_seq[0];
5308 guid->clock_seq[1] = clock_seq[1];
5310 guid->node[i] = node[i];
5313 return NT_STATUS_OK;
5316 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
5318 return talloc_asprintf(mem_ctx,
5319 "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5320 guid->time_low, guid->time_mid,
5321 guid->time_hi_and_version,
5324 guid->node[0], guid->node[1],
5325 guid->node[2], guid->node[3],
5326 guid->node[4], guid->node[5]);
5330 * Return the effective badPwdCount
5332 * This requires that the user_msg have (if present):
5336 * This also requires that the domain_msg have (if present):
5337 * - lockOutObservationWindow
5339 static int dsdb_effective_badPwdCount(const struct ldb_message *user_msg,
5340 int64_t lockOutObservationWindow,
5343 int64_t badPasswordTime;
5344 badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
5346 if (badPasswordTime - lockOutObservationWindow >= now) {
5347 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
5354 * Returns a user's PSO, or NULL if none was found
5356 static struct ldb_result *lookup_user_pso(struct ldb_context *sam_ldb,
5357 TALLOC_CTX *mem_ctx,
5358 const struct ldb_message *user_msg,
5359 const char * const *attrs)
5361 struct ldb_result *res = NULL;
5362 struct ldb_dn *pso_dn = NULL;
5365 /* if the user has a PSO that applies, then use the PSO's setting */
5366 pso_dn = ldb_msg_find_attr_as_dn(sam_ldb, mem_ctx, user_msg,
5367 "msDS-ResultantPSO");
5369 if (pso_dn != NULL) {
5371 ret = dsdb_search_dn(sam_ldb, mem_ctx, &res, pso_dn, attrs, 0);
5372 if (ret != LDB_SUCCESS) {
5375 * log the error. The caller should fallback to using
5376 * the default domain password settings
5378 DBG_ERR("Error retrieving msDS-ResultantPSO %s for %s",
5379 ldb_dn_get_linearized(pso_dn),
5380 ldb_dn_get_linearized(user_msg->dn));
5382 talloc_free(pso_dn);
5388 * Return the effective badPwdCount
5390 * This requires that the user_msg have (if present):
5393 * - msDS-ResultantPSO
5395 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
5396 TALLOC_CTX *mem_ctx,
5397 struct ldb_dn *domain_dn,
5398 const struct ldb_message *user_msg)
5400 struct timeval tv_now = timeval_current();
5401 NTTIME now = timeval_to_nttime(&tv_now);
5402 int64_t lockOutObservationWindow;
5403 struct ldb_result *res = NULL;
5404 const char *attrs[] = { "msDS-LockoutObservationWindow",
5407 res = lookup_user_pso(sam_ldb, mem_ctx, user_msg, attrs);
5410 lockOutObservationWindow =
5411 ldb_msg_find_attr_as_int64(res->msgs[0],
5412 "msDS-LockoutObservationWindow",
5413 DEFAULT_OBSERVATION_WINDOW);
5417 /* no PSO was found, lookup the default domain setting */
5418 lockOutObservationWindow =
5419 samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
5420 "lockOutObservationWindow", NULL);
5423 return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5427 * Returns the lockoutThreshold that applies. If a PSO is specified, then that
5428 * setting is used over the domain defaults
5430 static int64_t get_lockout_threshold(struct ldb_message *domain_msg,
5431 struct ldb_message *pso_msg)
5433 if (pso_msg != NULL) {
5434 return ldb_msg_find_attr_as_int(pso_msg,
5435 "msDS-LockoutThreshold", 0);
5437 return ldb_msg_find_attr_as_int(domain_msg,
5438 "lockoutThreshold", 0);
5443 * Returns the lockOutObservationWindow that applies. If a PSO is specified,
5444 * then that setting is used over the domain defaults
5446 static int64_t get_lockout_observation_window(struct ldb_message *domain_msg,
5447 struct ldb_message *pso_msg)
5449 if (pso_msg != NULL) {
5450 return ldb_msg_find_attr_as_int64(pso_msg,
5451 "msDS-LockoutObservationWindow",
5452 DEFAULT_OBSERVATION_WINDOW);
5454 return ldb_msg_find_attr_as_int64(domain_msg,
5455 "lockOutObservationWindow",
5456 DEFAULT_OBSERVATION_WINDOW);
5461 * Prepare an update to the badPwdCount and associated attributes.
5463 * This requires that the user_msg have (if present):
5468 * This also requires that the domain_msg have (if present):
5470 * - lockoutThreshold
5471 * - lockOutObservationWindow
5473 * This also requires that the pso_msg have (if present):
5474 * - msDS-LockoutThreshold
5475 * - msDS-LockoutObservationWindow
5477 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
5478 struct ldb_context *sam_ctx,
5479 struct ldb_message *user_msg,
5480 struct ldb_message *domain_msg,
5481 struct ldb_message *pso_msg,
5482 struct ldb_message **_mod_msg)
5484 int i, ret, badPwdCount;
5485 int64_t lockoutThreshold, lockOutObservationWindow;
5486 struct dom_sid *sid;
5487 struct timeval tv_now = timeval_current();
5488 NTTIME now = timeval_to_nttime(&tv_now);
5490 uint32_t pwdProperties, rid = 0;
5491 struct ldb_message *mod_msg;
5493 sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
5495 pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
5496 "pwdProperties", -1);
5497 if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
5498 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
5499 if (!NT_STATUS_IS_OK(status)) {
5501 * This can't happen anyway, but always try
5502 * and update the badPwdCount on failure
5510 * Work out if we are doing password lockout on the domain.
5511 * Also, the built in administrator account is exempt:
5512 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
5514 lockoutThreshold = get_lockout_threshold(domain_msg, pso_msg);
5515 if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
5516 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
5517 ldb_dn_get_linearized(user_msg->dn)));
5518 return NT_STATUS_OK;
5521 mod_msg = ldb_msg_new(mem_ctx);
5522 if (mod_msg == NULL) {
5523 return NT_STATUS_NO_MEMORY;
5525 mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
5526 if (mod_msg->dn == NULL) {
5527 TALLOC_FREE(mod_msg);
5528 return NT_STATUS_NO_MEMORY;
5531 lockOutObservationWindow = get_lockout_observation_window(domain_msg,
5534 badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5538 ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
5539 if (ret != LDB_SUCCESS) {
5540 TALLOC_FREE(mod_msg);
5541 return NT_STATUS_NO_MEMORY;
5543 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
5544 if (ret != LDB_SUCCESS) {
5545 TALLOC_FREE(mod_msg);
5546 return NT_STATUS_NO_MEMORY;
5549 if (badPwdCount >= lockoutThreshold) {
5550 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
5551 if (ret != LDB_SUCCESS) {
5552 TALLOC_FREE(mod_msg);
5553 return NT_STATUS_NO_MEMORY;
5555 DEBUGC( DBGC_AUTH, 1, ("Locked out user %s after %d wrong passwords\n",
5556 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5558 DEBUGC( DBGC_AUTH, 5, ("Updated badPwdCount on %s after %d wrong passwords\n",
5559 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5562 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5563 for (i=0; i< mod_msg->num_elements; i++) {
5564 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5567 *_mod_msg = mod_msg;
5568 return NT_STATUS_OK;
5572 * Sets defaults for a User object
5573 * List of default attributes set:
5574 * accountExpires, badPasswordTime, badPwdCount,
5575 * codePage, countryCode, lastLogoff, lastLogon
5576 * logonCount, pwdLastSet
5578 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
5579 struct ldb_message *usr_obj,
5580 struct ldb_request *req)
5583 const struct attribute_values {
5586 const char *add_value;
5587 const char *mod_value;
5588 const char *control;
5593 .name = "accountExpires",
5594 .add_value = "9223372036854775807",
5598 .name = "badPasswordTime",
5602 .name = "badPwdCount",
5610 .name = "countryCode",
5614 .name = "lastLogoff",
5618 .name = "lastLogon",
5622 .name = "logonCount",
5626 .name = "logonHours",
5627 .add_flags = DSDB_FLAG_INTERNAL_FORCE_META_DATA,
5630 .name = "pwdLastSet",
5632 .control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
5635 .name = "adminCount",
5639 .name = "operatorCount",
5644 for (i = 0; i < ARRAY_SIZE(map); i++) {
5646 const char *value = NULL;
5649 if (req != NULL && req->operation == LDB_ADD) {
5650 value = map[i].add_value;
5651 flags = map[i].add_flags;
5653 value = map[i].mod_value;
5654 flags = map[i].mod_flags;
5657 if (value == NULL) {
5658 value = map[i].value;
5661 if (value != NULL) {
5662 flags |= LDB_FLAG_MOD_ADD;
5669 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
5673 if (ret != LDB_SUCCESS) {
5677 if (req != NULL && added && map[i].control != NULL) {
5678 ret = ldb_request_add_control(req,
5681 if (ret != LDB_SUCCESS) {
5691 * Sets 'sAMAccountType on user object based on userAccountControl
5692 * @param ldb Current ldb_context
5693 * @param usr_obj ldb_message representing User object
5694 * @param user_account_control Value for userAccountControl flags
5695 * @param account_type_p Optional pointer to account_type to return
5696 * @return LDB_SUCCESS or LDB_ERR* code on failure
5698 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
5699 uint32_t user_account_control, uint32_t *account_type_p)
5702 uint32_t account_type;
5703 struct ldb_message_element *el;
5705 account_type = ds_uf2atype(user_account_control);
5706 if (account_type == 0) {
5707 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
5708 return LDB_ERR_UNWILLING_TO_PERFORM;
5710 ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5713 if (ret != LDB_SUCCESS) {
5716 el = ldb_msg_find_element(usr_obj, "sAMAccountType");
5717 el->flags = LDB_FLAG_MOD_REPLACE;
5719 if (account_type_p) {
5720 *account_type_p = account_type;
5727 * Determine and set primaryGroupID based on userAccountControl value
5728 * @param ldb Current ldb_context
5729 * @param usr_obj ldb_message representing User object
5730 * @param user_account_control Value for userAccountControl flags
5731 * @param group_rid_p Optional pointer to group RID to return
5732 * @return LDB_SUCCESS or LDB_ERR* code on failure
5734 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
5735 uint32_t user_account_control, uint32_t *group_rid_p)
5739 struct ldb_message_element *el;
5741 rid = ds_uf2prim_group_rid(user_account_control);
5743 ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5744 "primaryGroupID", rid);
5745 if (ret != LDB_SUCCESS) {
5748 el = ldb_msg_find_element(usr_obj, "primaryGroupID");
5749 el->flags = LDB_FLAG_MOD_REPLACE;
5759 * Returns True if the source and target DNs both have the same naming context,
5760 * i.e. they're both in the same partition.
5762 bool dsdb_objects_have_same_nc(struct ldb_context *ldb,
5763 TALLOC_CTX *mem_ctx,
5764 struct ldb_dn *source_dn,
5765 struct ldb_dn *target_dn)
5767 TALLOC_CTX *tmp_ctx;
5768 struct ldb_dn *source_nc;
5769 struct ldb_dn *target_nc;
5771 bool same_nc = true;
5773 tmp_ctx = talloc_new(mem_ctx);
5775 ret = dsdb_find_nc_root(ldb, tmp_ctx, source_dn, &source_nc);
5776 if (ret != LDB_SUCCESS) {
5777 DBG_ERR("Failed to find base DN for source %s\n",
5778 ldb_dn_get_linearized(source_dn));
5779 talloc_free(tmp_ctx);
5783 ret = dsdb_find_nc_root(ldb, tmp_ctx, target_dn, &target_nc);
5784 if (ret != LDB_SUCCESS) {
5785 DBG_ERR("Failed to find base DN for target %s\n",
5786 ldb_dn_get_linearized(target_dn));
5787 talloc_free(tmp_ctx);
5791 same_nc = (ldb_dn_compare(source_nc, target_nc) == 0);
5793 talloc_free(tmp_ctx);
5798 * Context for dsdb_count_domain_callback
5800 struct dsdb_count_domain_context {
5802 * Number of matching records
5806 * sid of the domain that the records must belong to.
5807 * if NULL records can belong to any domain.
5809 struct dom_sid *dom_sid;
5813 * @brief ldb aysnc callback for dsdb_domain_count.
5815 * count the number of records in the database matching an LDAP query,
5816 * optionally filtering for domain membership.
5818 * @param [in,out] req the ldb request being processed
5819 * req->context contains:
5820 * count The number of matching records
5821 * dom_sid The domain sid, if present records must belong
5822 * to the domain to be counted.
5823 *@param [in,out] ares The query result.
5825 * @return an LDB error code
5828 static int dsdb_count_domain_callback(
5829 struct ldb_request *req,
5830 struct ldb_reply *ares)
5834 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
5836 if (ares->error != LDB_SUCCESS) {
5837 int error = ares->error;
5839 return ldb_request_done(req, error);
5842 switch (ares->type) {
5843 case LDB_REPLY_ENTRY:
5845 struct dsdb_count_domain_context *context = NULL;
5848 const struct ldb_val *v;
5850 context = req->context;
5851 if (context->dom_sid == NULL) {
5856 v = ldb_msg_find_ldb_val(ares->message, "objectSid");
5861 ok = sid_parse(v->data, v->length, &sid);
5866 in_domain = dom_sid_in_domain(context->dom_sid, &sid);
5874 case LDB_REPLY_REFERRAL:
5877 case LDB_REPLY_DONE:
5879 return ldb_request_done(req, LDB_SUCCESS);
5888 * @brief Count the number of records matching a query.
5890 * Count the number of entries in the database matching the supplied query,
5891 * optionally filtering only those entries belonging to the supplied domain.
5893 * @param ldb [in] Current ldb context
5894 * @param count [out] Pointer to the count
5895 * @param base [in] The base dn for the quey
5896 * @param dom_sid [in] The domain sid, if non NULL records that are not a member
5897 * of the domain are ignored.
5898 * @param scope [in] Search scope.
5899 * @param exp_fmt [in] format string for the query.
5901 * @return LDB_STATUS code.
5903 int dsdb_domain_count(
5904 struct ldb_context *ldb,
5906 struct ldb_dn *base,
5907 struct dom_sid *dom_sid,
5908 enum ldb_scope scope,
5909 const char *exp_fmt, ...)
5911 TALLOC_CTX *tmp_ctx = NULL;
5912 struct ldb_request *req = NULL;
5913 struct dsdb_count_domain_context *context = NULL;
5914 char *expression = NULL;
5915 const char *object_sid[] = {"objectSid", NULL};
5916 const char *none[] = {NULL};
5921 tmp_ctx = talloc_new(ldb);
5923 context = talloc_zero(tmp_ctx, struct dsdb_count_domain_context);
5924 if (context == NULL) {
5925 return LDB_ERR_OPERATIONS_ERROR;
5927 context->dom_sid = dom_sid;
5930 va_start(ap, exp_fmt);
5931 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
5934 if (expression == NULL) {
5935 TALLOC_FREE(context);
5936 TALLOC_FREE(tmp_ctx);
5937 return LDB_ERR_OPERATIONS_ERROR;
5941 ret = ldb_build_search_req(
5948 (dom_sid == NULL) ? none : object_sid,
5951 dsdb_count_domain_callback,
5953 ldb_req_set_location(req, "dsdb_domain_count");
5955 if (ret != LDB_SUCCESS) goto done;
5957 ret = ldb_request(ldb, req);
5959 if (ret == LDB_SUCCESS) {
5960 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
5961 if (ret == LDB_SUCCESS) {
5962 *count = context->count;
5968 TALLOC_FREE(expression);
5970 TALLOC_FREE(context);
5971 TALLOC_FREE(tmp_ctx);