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, *subnets_dn, *sites_dn;
1877 struct ldb_result *res;
1878 const struct ldb_val *val;
1879 const char *site_name = NULL, *l_subnet_name = NULL;
1880 const char *allow_list[2] = { NULL, NULL };
1881 unsigned int i, count;
1885 * if we don't have a client ip e.g. ncalrpc
1886 * the server site is the client site
1888 if (ip_address == NULL) {
1889 return samdb_server_site_name(ldb, mem_ctx);
1892 sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1893 if (sites_container_dn == NULL) {
1897 subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1898 if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1899 talloc_free(sites_container_dn);
1900 talloc_free(subnets_dn);
1904 ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1906 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1908 } else if (ret != LDB_SUCCESS) {
1909 talloc_free(sites_container_dn);
1910 talloc_free(subnets_dn);
1916 for (i = 0; i < count; i++) {
1917 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1920 allow_list[0] = l_subnet_name;
1922 if (allow_access_nolog(NULL, allow_list, "", ip_address)) {
1923 sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1926 if (sites_dn == NULL) {
1927 /* No reference, maybe another subnet matches */
1931 /* "val" cannot be NULL here since "sites_dn" != NULL */
1932 val = ldb_dn_get_rdn_val(sites_dn);
1933 site_name = talloc_strdup(mem_ctx,
1934 (const char *) val->data);
1936 talloc_free(sites_dn);
1942 if (site_name == NULL && fallback) {
1943 /* This is the Windows Server fallback rule: when no subnet
1944 * exists and we have only one site available then use it (it
1945 * is for sure the same as our server site). If more sites do
1946 * exist then we don't know which one to use and set the site
1949 ret = dsdb_domain_count(
1955 "(objectClass=site)");
1956 if (ret != LDB_SUCCESS) {
1961 site_name = samdb_server_site_name(ldb, mem_ctx);
1963 site_name = talloc_strdup(mem_ctx, "");
1965 l_subnet_name = NULL;
1968 if (subnet_name != NULL) {
1969 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1973 talloc_free(sites_container_dn);
1974 talloc_free(subnets_dn);
1981 work out if we are the PDC for the domain of the current open ldb
1983 bool samdb_is_pdc(struct ldb_context *ldb)
1988 ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner",
1990 if (ret != LDB_SUCCESS) {
1991 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n",
1992 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
1993 ldb_errstring(ldb)));
2001 work out if we are a Global Catalog server for the domain of the current open ldb
2003 bool samdb_is_gc(struct ldb_context *ldb)
2006 if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
2009 return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
2012 /* Find a domain object in the parents of a particular DN. */
2013 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2014 struct ldb_dn **parent_dn, const char **errstring)
2016 TALLOC_CTX *local_ctx;
2017 struct ldb_dn *sdn = dn;
2018 struct ldb_result *res = NULL;
2019 int ret = LDB_SUCCESS;
2020 const char *attrs[] = { NULL };
2022 local_ctx = talloc_new(mem_ctx);
2023 if (local_ctx == NULL) return ldb_oom(ldb);
2025 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
2026 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
2027 "(|(objectClass=domain)(objectClass=builtinDomain))");
2028 if (ret == LDB_SUCCESS) {
2029 if (res->count == 1) {
2037 if (ret != LDB_SUCCESS) {
2038 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
2039 ldb_dn_get_linearized(dn),
2040 ldb_dn_get_linearized(sdn),
2041 ldb_errstring(ldb));
2042 talloc_free(local_ctx);
2045 if (res->count != 1) {
2046 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
2047 ldb_dn_get_linearized(dn));
2048 DEBUG(0,(__location__ ": %s\n", *errstring));
2049 talloc_free(local_ctx);
2050 return LDB_ERR_CONSTRAINT_VIOLATION;
2053 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2054 talloc_free(local_ctx);
2058 static void pwd_timeout_debug(struct tevent_context *unused1,
2059 struct tevent_timer *unused2,
2060 struct timeval unused3,
2063 DEBUG(0, ("WARNING: check_password_complexity: password script "
2064 "took more than 1 second to run\n"));
2069 * Performs checks on a user password (plaintext UNIX format - attribute
2070 * "password"). The remaining parameters have to be extracted from the domain
2073 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
2075 enum samr_ValidationStatus samdb_check_password(TALLOC_CTX *mem_ctx,
2076 struct loadparm_context *lp_ctx,
2077 const char *account_name,
2078 const char *user_principal_name,
2079 const char *full_name,
2080 const DATA_BLOB *utf8_blob,
2081 const uint32_t pwdProperties,
2082 const uint32_t minPwdLength)
2084 const char *utf8_pw = (const char *)utf8_blob->data;
2085 size_t utf8_len = strlen_m(utf8_pw);
2086 char *password_script = NULL;
2088 /* checks if the "minPwdLength" property is satisfied */
2089 if (minPwdLength > utf8_len) {
2090 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2093 /* checks the password complexity */
2094 if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
2095 return SAMR_VALIDATION_STATUS_SUCCESS;
2098 if (utf8_len == 0) {
2099 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2102 password_script = lpcfg_check_password_script(lp_ctx, mem_ctx);
2103 if (password_script != NULL && *password_script != '\0') {
2106 struct tevent_context *event_ctx = NULL;
2107 struct tevent_req *req = NULL;
2109 const char * const cmd[4] = {
2115 event_ctx = tevent_context_init(mem_ctx);
2116 if (event_ctx == NULL) {
2117 TALLOC_FREE(password_script);
2118 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2121 /* Gives a warning after 1 second, terminates after 10 */
2122 tevent_add_timer(event_ctx, event_ctx,
2123 tevent_timeval_current_ofs(1, 0),
2124 pwd_timeout_debug, NULL);
2126 check_ret = setenv("SAMBA_CPS_ACCOUNT_NAME", account_name, 1);
2127 if (check_ret != 0) {
2128 TALLOC_FREE(password_script);
2129 TALLOC_FREE(event_ctx);
2130 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2132 if (user_principal_name != NULL) {
2133 check_ret = setenv("SAMBA_CPS_USER_PRINCIPAL_NAME",
2134 user_principal_name, 1);
2136 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2138 if (check_ret != 0) {
2139 TALLOC_FREE(password_script);
2140 TALLOC_FREE(event_ctx);
2141 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2143 if (full_name != NULL) {
2144 check_ret = setenv("SAMBA_CPS_FULL_NAME", full_name, 1);
2146 unsetenv("SAMBA_CPS_FULL_NAME");
2148 if (check_ret != 0) {
2149 TALLOC_FREE(password_script);
2150 TALLOC_FREE(event_ctx);
2151 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2154 req = samba_runcmd_send(event_ctx, event_ctx,
2155 tevent_timeval_current_ofs(10, 0),
2156 100, 100, cmd, NULL);
2157 unsetenv("SAMBA_CPS_ACCOUNT_NAME");
2158 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2159 unsetenv("SAMBA_CPS_FULL_NAME");
2161 TALLOC_FREE(password_script);
2162 TALLOC_FREE(event_ctx);
2163 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2166 cps_stdin = samba_runcmd_export_stdin(req);
2168 if (write(cps_stdin, utf8_pw, utf8_len) != utf8_len) {
2171 TALLOC_FREE(password_script);
2172 TALLOC_FREE(event_ctx);
2173 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2179 if (!tevent_req_poll(req, event_ctx)) {
2180 TALLOC_FREE(password_script);
2181 TALLOC_FREE(event_ctx);
2182 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2185 check_ret = samba_runcmd_recv(req, &error);
2186 TALLOC_FREE(event_ctx);
2188 if (error == ETIMEDOUT) {
2189 DEBUG(0, ("check_password_complexity: check password script took too long!\n"));
2190 TALLOC_FREE(password_script);
2191 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2193 DEBUG(5,("check_password_complexity: check password script (%s) "
2194 "returned [%d]\n", password_script, check_ret));
2196 if (check_ret != 0) {
2197 DEBUG(1,("check_password_complexity: "
2198 "check password script said new password is not good "
2200 TALLOC_FREE(password_script);
2201 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2204 TALLOC_FREE(password_script);
2205 return SAMR_VALIDATION_STATUS_SUCCESS;
2208 TALLOC_FREE(password_script);
2211 * Here are the standard AD password quality rules, which we
2212 * run after the script.
2215 if (!check_password_quality(utf8_pw)) {
2216 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2219 return SAMR_VALIDATION_STATUS_SUCCESS;
2223 * Callback for "samdb_set_password" password change
2225 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2230 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2233 if (ares->error != LDB_SUCCESS) {
2235 req->context = talloc_steal(req,
2236 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2238 return ldb_request_done(req, ret);
2241 if (ares->type != LDB_REPLY_DONE) {
2243 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2246 req->context = talloc_steal(req,
2247 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2249 return ldb_request_done(req, LDB_SUCCESS);
2253 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2254 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2255 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2256 * user change or not. The "rejectReason" gives some more information if the
2259 * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2260 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2262 static NTSTATUS samdb_set_password_internal(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2263 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2264 const DATA_BLOB *new_password,
2265 const struct samr_Password *lmNewHash,
2266 const struct samr_Password *ntNewHash,
2267 const struct samr_Password *lmOldHash,
2268 const struct samr_Password *ntOldHash,
2269 enum samPwdChangeReason *reject_reason,
2270 struct samr_DomInfo1 **_dominfo,
2271 bool permit_interdomain_trust)
2273 struct ldb_message *msg;
2274 struct ldb_message_element *el;
2275 struct ldb_request *req;
2276 struct dsdb_control_password_change_status *pwd_stat = NULL;
2278 bool hash_values = false;
2279 NTSTATUS status = NT_STATUS_OK;
2281 #define CHECK_RET(x) \
2282 if (x != LDB_SUCCESS) { \
2284 return NT_STATUS_NO_MEMORY; \
2287 msg = ldb_msg_new(mem_ctx);
2289 return NT_STATUS_NO_MEMORY;
2292 if ((new_password != NULL)
2293 && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2294 /* we have the password as plaintext UTF16 */
2295 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2296 new_password, NULL));
2297 el = ldb_msg_find_element(msg, "clearTextPassword");
2298 el->flags = LDB_FLAG_MOD_REPLACE;
2299 } else if ((new_password == NULL)
2300 && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2301 /* we have a password as LM and/or NT hash */
2302 if (lmNewHash != NULL) {
2303 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2304 "dBCSPwd", lmNewHash));
2305 el = ldb_msg_find_element(msg, "dBCSPwd");
2306 el->flags = LDB_FLAG_MOD_REPLACE;
2308 if (ntNewHash != NULL) {
2309 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2310 "unicodePwd", ntNewHash));
2311 el = ldb_msg_find_element(msg, "unicodePwd");
2312 el->flags = LDB_FLAG_MOD_REPLACE;
2316 /* the password wasn't specified correctly */
2318 return NT_STATUS_INVALID_PARAMETER;
2321 /* build modify request */
2322 ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2323 samdb_set_password_callback, NULL);
2324 if (ret != LDB_SUCCESS) {
2326 return NT_STATUS_NO_MEMORY;
2329 /* A password change operation */
2330 if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2331 struct dsdb_control_password_change *change;
2333 change = talloc(req, struct dsdb_control_password_change);
2334 if (change == NULL) {
2337 return NT_STATUS_NO_MEMORY;
2340 change->old_nt_pwd_hash = ntOldHash;
2341 change->old_lm_pwd_hash = lmOldHash;
2343 ret = ldb_request_add_control(req,
2344 DSDB_CONTROL_PASSWORD_CHANGE_OID,
2346 if (ret != LDB_SUCCESS) {
2349 return NT_STATUS_NO_MEMORY;
2353 ret = ldb_request_add_control(req,
2354 DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2356 if (ret != LDB_SUCCESS) {
2359 return NT_STATUS_NO_MEMORY;
2362 if (permit_interdomain_trust) {
2363 ret = ldb_request_add_control(req,
2364 DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
2366 if (ret != LDB_SUCCESS) {
2369 return NT_STATUS_NO_MEMORY;
2372 ret = ldb_request_add_control(req,
2373 DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2375 if (ret != LDB_SUCCESS) {
2378 return NT_STATUS_NO_MEMORY;
2381 ret = dsdb_autotransaction_request(ldb, req);
2383 if (req->context != NULL) {
2384 struct ldb_control *control = talloc_get_type_abort(req->context,
2385 struct ldb_control);
2386 pwd_stat = talloc_get_type_abort(control->data,
2387 struct dsdb_control_password_change_status);
2388 talloc_steal(mem_ctx, pwd_stat);
2394 /* Sets the domain info (if requested) */
2395 if (_dominfo != NULL) {
2396 struct samr_DomInfo1 *dominfo;
2398 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2399 if (dominfo == NULL) {
2400 return NT_STATUS_NO_MEMORY;
2403 if (pwd_stat != NULL) {
2404 dominfo->min_password_length = pwd_stat->domain_data.minPwdLength;
2405 dominfo->password_properties = pwd_stat->domain_data.pwdProperties;
2406 dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2407 dominfo->max_password_age = pwd_stat->domain_data.maxPwdAge;
2408 dominfo->min_password_age = pwd_stat->domain_data.minPwdAge;
2411 *_dominfo = dominfo;
2414 if (reject_reason != NULL) {
2415 if (pwd_stat != NULL) {
2416 *reject_reason = pwd_stat->reject_reason;
2418 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2422 if (pwd_stat != NULL) {
2423 talloc_free(pwd_stat);
2426 if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2427 const char *errmsg = ldb_errstring(ldb);
2428 char *endptr = NULL;
2429 WERROR werr = WERR_GEN_FAILURE;
2430 status = NT_STATUS_UNSUCCESSFUL;
2431 if (errmsg != NULL) {
2432 werr = W_ERROR(strtol(errmsg, &endptr, 16));
2433 DBG_WARNING("%s\n", errmsg);
2435 if (endptr != errmsg) {
2436 if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2437 status = NT_STATUS_WRONG_PASSWORD;
2439 if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2440 status = NT_STATUS_PASSWORD_RESTRICTION;
2443 } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2444 /* don't let the caller know if an account doesn't exist */
2445 status = NT_STATUS_WRONG_PASSWORD;
2446 } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2447 status = NT_STATUS_ACCESS_DENIED;
2448 } else if (ret != LDB_SUCCESS) {
2449 DEBUG(1, ("Failed to set password on %s: %s\n",
2450 ldb_dn_get_linearized(user_dn),
2451 ldb_errstring(ldb)));
2452 status = NT_STATUS_UNSUCCESSFUL;
2458 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2459 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2460 const DATA_BLOB *new_password,
2461 const struct samr_Password *lmNewHash,
2462 const struct samr_Password *ntNewHash,
2463 const struct samr_Password *lmOldHash,
2464 const struct samr_Password *ntOldHash,
2465 enum samPwdChangeReason *reject_reason,
2466 struct samr_DomInfo1 **_dominfo)
2468 return samdb_set_password_internal(ldb, mem_ctx,
2471 lmNewHash, ntNewHash,
2472 lmOldHash, ntOldHash,
2473 reject_reason, _dominfo,
2474 false); /* reject trusts */
2478 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2479 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2480 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2481 * user change or not. The "rejectReason" gives some more information if the
2484 * This wrapper function for "samdb_set_password" takes a SID as input rather
2487 * This call encapsulates a new LDB transaction for changing the password;
2488 * therefore the user hasn't to start a new one.
2490 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2491 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2492 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2493 * NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2495 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2496 const struct dom_sid *user_sid,
2497 const uint32_t *new_version, /* optional for trusts */
2498 const DATA_BLOB *new_password,
2499 const struct samr_Password *lmNewHash,
2500 const struct samr_Password *ntNewHash,
2501 const struct samr_Password *lmOldHash,
2502 const struct samr_Password *ntOldHash,
2503 enum samPwdChangeReason *reject_reason,
2504 struct samr_DomInfo1 **_dominfo)
2506 TALLOC_CTX *frame = talloc_stackframe();
2508 const char * const user_attrs[] = {
2509 "userAccountControl",
2513 struct ldb_message *user_msg = NULL;
2517 ret = ldb_transaction_start(ldb);
2518 if (ret != LDB_SUCCESS) {
2519 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2521 return NT_STATUS_TRANSACTION_ABORTED;
2524 ret = dsdb_search_one(ldb, frame, &user_msg, ldb_get_default_basedn(ldb),
2525 LDB_SCOPE_SUBTREE, user_attrs, 0,
2526 "(&(objectSid=%s)(objectClass=user))",
2527 ldap_encode_ndr_dom_sid(frame, user_sid));
2528 if (ret != LDB_SUCCESS) {
2529 ldb_transaction_cancel(ldb);
2530 DEBUG(3, ("samdb_set_password_sid: SID[%s] not found in samdb %s - %s, "
2531 "returning NO_SUCH_USER\n",
2532 dom_sid_string(frame, user_sid),
2533 ldb_strerror(ret), ldb_errstring(ldb)));
2535 return NT_STATUS_NO_SUCH_USER;
2538 uac = ldb_msg_find_attr_as_uint(user_msg, "userAccountControl", 0);
2539 if (!(uac & UF_ACCOUNT_TYPE_MASK)) {
2540 ldb_transaction_cancel(ldb);
2541 DEBUG(1, ("samdb_set_password_sid: invalid "
2542 "userAccountControl[0x%08X] for SID[%s] DN[%s], "
2543 "returning NO_SUCH_USER\n",
2544 (unsigned)uac, dom_sid_string(frame, user_sid),
2545 ldb_dn_get_linearized(user_msg->dn)));
2547 return NT_STATUS_NO_SUCH_USER;
2550 if (uac & UF_INTERDOMAIN_TRUST_ACCOUNT) {
2551 const char * const tdo_attrs[] = {
2552 "trustAuthIncoming",
2556 struct ldb_message *tdo_msg = NULL;
2557 const char *account_name = NULL;
2558 uint32_t trust_direction;
2560 const struct ldb_val *old_val = NULL;
2561 struct trustAuthInOutBlob old_blob = {
2564 uint32_t old_version = 0;
2565 struct AuthenticationInformation *old_version_a = NULL;
2566 uint32_t _new_version = 0;
2567 struct trustAuthInOutBlob new_blob = {
2570 struct ldb_val new_val = {
2573 struct timeval tv = timeval_current();
2574 NTTIME now = timeval_to_nttime(&tv);
2575 enum ndr_err_code ndr_err;
2577 if (new_password == NULL && ntNewHash == NULL) {
2578 ldb_transaction_cancel(ldb);
2579 DEBUG(1, ("samdb_set_password_sid: "
2580 "no new password provided "
2581 "sAMAccountName for SID[%s] DN[%s], "
2582 "returning INVALID_PARAMETER\n",
2583 dom_sid_string(frame, user_sid),
2584 ldb_dn_get_linearized(user_msg->dn)));
2586 return NT_STATUS_INVALID_PARAMETER;
2589 if (new_password != NULL && ntNewHash != NULL) {
2590 ldb_transaction_cancel(ldb);
2591 DEBUG(1, ("samdb_set_password_sid: "
2592 "two new passwords provided "
2593 "sAMAccountName for SID[%s] DN[%s], "
2594 "returning INVALID_PARAMETER\n",
2595 dom_sid_string(frame, user_sid),
2596 ldb_dn_get_linearized(user_msg->dn)));
2598 return NT_STATUS_INVALID_PARAMETER;
2601 if (new_password != NULL && (new_password->length % 2)) {
2602 ldb_transaction_cancel(ldb);
2603 DEBUG(2, ("samdb_set_password_sid: "
2604 "invalid utf16 length (%zu) "
2605 "sAMAccountName for SID[%s] DN[%s], "
2606 "returning WRONG_PASSWORD\n",
2607 new_password->length,
2608 dom_sid_string(frame, user_sid),
2609 ldb_dn_get_linearized(user_msg->dn)));
2611 return NT_STATUS_WRONG_PASSWORD;
2614 if (new_password != NULL && new_password->length >= 500) {
2615 ldb_transaction_cancel(ldb);
2616 DEBUG(2, ("samdb_set_password_sid: "
2617 "utf16 password too long (%zu) "
2618 "sAMAccountName for SID[%s] DN[%s], "
2619 "returning WRONG_PASSWORD\n",
2620 new_password->length,
2621 dom_sid_string(frame, user_sid),
2622 ldb_dn_get_linearized(user_msg->dn)));
2624 return NT_STATUS_WRONG_PASSWORD;
2627 account_name = ldb_msg_find_attr_as_string(user_msg,
2628 "sAMAccountName", NULL);
2629 if (account_name == NULL) {
2630 ldb_transaction_cancel(ldb);
2631 DEBUG(1, ("samdb_set_password_sid: missing "
2632 "sAMAccountName for SID[%s] DN[%s], "
2633 "returning NO_SUCH_USER\n",
2634 dom_sid_string(frame, user_sid),
2635 ldb_dn_get_linearized(user_msg->dn)));
2637 return NT_STATUS_NO_SUCH_USER;
2640 nt_status = dsdb_trust_search_tdo_by_type(ldb,
2645 if (!NT_STATUS_IS_OK(nt_status)) {
2646 ldb_transaction_cancel(ldb);
2647 DEBUG(1, ("samdb_set_password_sid: dsdb_trust_search_tdo "
2648 "failed(%s) for sAMAccountName[%s] SID[%s] DN[%s], "
2649 "returning INTERNAL_DB_CORRUPTION\n",
2650 nt_errstr(nt_status), account_name,
2651 dom_sid_string(frame, user_sid),
2652 ldb_dn_get_linearized(user_msg->dn)));
2654 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2657 trust_direction = ldb_msg_find_attr_as_int(tdo_msg,
2658 "trustDirection", 0);
2659 if (!(trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {
2660 ldb_transaction_cancel(ldb);
2661 DEBUG(1, ("samdb_set_password_sid: direction[0x%08X] is "
2662 "not inbound for sAMAccountName[%s] "
2664 "returning INTERNAL_DB_CORRUPTION\n",
2665 (unsigned)trust_direction,
2667 ldb_dn_get_linearized(user_msg->dn),
2668 ldb_dn_get_linearized(tdo_msg->dn)));
2670 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2673 old_val = ldb_msg_find_ldb_val(tdo_msg, "trustAuthIncoming");
2674 if (old_val != NULL) {
2675 ndr_err = ndr_pull_struct_blob(old_val, frame, &old_blob,
2676 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2677 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2678 ldb_transaction_cancel(ldb);
2679 DEBUG(1, ("samdb_set_password_sid: "
2680 "failed(%s) to parse "
2681 "trustAuthOutgoing sAMAccountName[%s] "
2683 "returning INTERNAL_DB_CORRUPTION\n",
2684 ndr_map_error2string(ndr_err),
2686 ldb_dn_get_linearized(user_msg->dn),
2687 ldb_dn_get_linearized(tdo_msg->dn)));
2690 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2694 for (i = old_blob.current.count; i > 0; i--) {
2695 struct AuthenticationInformation *a =
2696 &old_blob.current.array[i - 1];
2698 switch (a->AuthType) {
2699 case TRUST_AUTH_TYPE_NONE:
2700 if (i == old_blob.current.count) {
2702 * remove TRUST_AUTH_TYPE_NONE at the
2705 old_blob.current.count--;
2709 case TRUST_AUTH_TYPE_VERSION:
2711 old_version = a->AuthInfo.version.version;
2714 case TRUST_AUTH_TYPE_CLEAR:
2717 case TRUST_AUTH_TYPE_NT4OWF:
2722 if (new_version == NULL) {
2724 new_version = &_new_version;
2727 if (old_version_a != NULL && *new_version != (old_version + 1)) {
2728 old_version_a->LastUpdateTime = now;
2729 old_version_a->AuthType = TRUST_AUTH_TYPE_NONE;
2732 new_blob.count = MAX(old_blob.current.count, 2);
2733 new_blob.current.array = talloc_zero_array(frame,
2734 struct AuthenticationInformation,
2736 if (new_blob.current.array == NULL) {
2737 ldb_transaction_cancel(ldb);
2739 return NT_STATUS_NO_MEMORY;
2741 new_blob.previous.array = talloc_zero_array(frame,
2742 struct AuthenticationInformation,
2744 if (new_blob.current.array == NULL) {
2745 ldb_transaction_cancel(ldb);
2747 return NT_STATUS_NO_MEMORY;
2750 for (i = 0; i < old_blob.current.count; i++) {
2751 struct AuthenticationInformation *o =
2752 &old_blob.current.array[i];
2753 struct AuthenticationInformation *p =
2754 &new_blob.previous.array[i];
2757 new_blob.previous.count++;
2759 for (; i < new_blob.count; i++) {
2760 struct AuthenticationInformation *pi =
2761 &new_blob.previous.array[i];
2765 * new_blob.previous is still empty so
2766 * we'll do new_blob.previous = new_blob.current
2772 pi->LastUpdateTime = now;
2773 pi->AuthType = TRUST_AUTH_TYPE_NONE;
2774 new_blob.previous.count++;
2777 for (i = 0; i < new_blob.count; i++) {
2778 struct AuthenticationInformation *ci =
2779 &new_blob.current.array[i];
2781 ci->LastUpdateTime = now;
2784 if (ntNewHash != NULL) {
2785 ci->AuthType = TRUST_AUTH_TYPE_NT4OWF;
2786 ci->AuthInfo.nt4owf.password = *ntNewHash;
2790 ci->AuthType = TRUST_AUTH_TYPE_CLEAR;
2791 ci->AuthInfo.clear.size = new_password->length;
2792 ci->AuthInfo.clear.password = new_password->data;
2795 ci->AuthType = TRUST_AUTH_TYPE_VERSION;
2796 ci->AuthInfo.version.version = *new_version;
2799 ci->AuthType = TRUST_AUTH_TYPE_NONE;
2803 new_blob.current.count++;
2806 if (new_blob.previous.count == 0) {
2807 TALLOC_FREE(new_blob.previous.array);
2808 new_blob.previous = new_blob.current;
2811 ndr_err = ndr_push_struct_blob(&new_val, frame, &new_blob,
2812 (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2813 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2814 ldb_transaction_cancel(ldb);
2815 DEBUG(1, ("samdb_set_password_sid: "
2816 "failed(%s) to generate "
2817 "trustAuthOutgoing sAMAccountName[%s] "
2819 "returning UNSUCCESSFUL\n",
2820 ndr_map_error2string(ndr_err),
2822 ldb_dn_get_linearized(user_msg->dn),
2823 ldb_dn_get_linearized(tdo_msg->dn)));
2825 return NT_STATUS_UNSUCCESSFUL;
2828 tdo_msg->num_elements = 0;
2829 TALLOC_FREE(tdo_msg->elements);
2831 ret = ldb_msg_add_empty(tdo_msg, "trustAuthIncoming",
2832 LDB_FLAG_MOD_REPLACE, NULL);
2833 if (ret != LDB_SUCCESS) {
2834 ldb_transaction_cancel(ldb);
2836 return NT_STATUS_NO_MEMORY;
2838 ret = ldb_msg_add_value(tdo_msg, "trustAuthIncoming",
2840 if (ret != LDB_SUCCESS) {
2841 ldb_transaction_cancel(ldb);
2843 return NT_STATUS_NO_MEMORY;
2846 ret = ldb_modify(ldb, tdo_msg);
2847 if (ret != LDB_SUCCESS) {
2848 nt_status = dsdb_ldb_err_to_ntstatus(ret);
2849 ldb_transaction_cancel(ldb);
2850 DEBUG(1, ("samdb_set_password_sid: "
2851 "failed to replace "
2852 "trustAuthOutgoing sAMAccountName[%s] "
2856 ldb_dn_get_linearized(user_msg->dn),
2857 ldb_dn_get_linearized(tdo_msg->dn),
2858 nt_errstr(nt_status), ldb_errstring(ldb)));
2864 nt_status = samdb_set_password_internal(ldb, mem_ctx,
2867 lmNewHash, ntNewHash,
2868 lmOldHash, ntOldHash,
2869 reject_reason, _dominfo,
2870 true); /* permit trusts */
2871 if (!NT_STATUS_IS_OK(nt_status)) {
2872 ldb_transaction_cancel(ldb);
2877 ret = ldb_transaction_commit(ldb);
2878 if (ret != LDB_SUCCESS) {
2879 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2880 ldb_dn_get_linearized(user_msg->dn),
2881 ldb_errstring(ldb)));
2883 return NT_STATUS_TRANSACTION_ABORTED;
2887 return NT_STATUS_OK;
2891 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
2892 struct dom_sid *sid, struct ldb_dn **ret_dn)
2894 struct ldb_message *msg;
2895 struct ldb_dn *basedn;
2899 sidstr = dom_sid_string(mem_ctx, sid);
2900 NT_STATUS_HAVE_NO_MEMORY(sidstr);
2902 /* We might have to create a ForeignSecurityPrincipal, even if this user
2903 * is in our own domain */
2905 msg = ldb_msg_new(sidstr);
2907 talloc_free(sidstr);
2908 return NT_STATUS_NO_MEMORY;
2911 ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2912 ldb_get_default_basedn(sam_ctx),
2913 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2915 if (ret != LDB_SUCCESS) {
2916 DEBUG(0, ("Failed to find DN for "
2917 "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2918 talloc_free(sidstr);
2919 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2922 /* add core elements to the ldb_message for the alias */
2924 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2925 talloc_free(sidstr);
2926 return NT_STATUS_NO_MEMORY;
2929 ret = ldb_msg_add_string(msg, "objectClass",
2930 "foreignSecurityPrincipal");
2931 if (ret != LDB_SUCCESS) {
2932 talloc_free(sidstr);
2933 return NT_STATUS_NO_MEMORY;
2936 /* create the alias */
2937 ret = ldb_add(sam_ctx, msg);
2938 if (ret != LDB_SUCCESS) {
2939 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2941 ldb_dn_get_linearized(msg->dn),
2942 ldb_errstring(sam_ctx)));
2943 talloc_free(sidstr);
2944 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2947 *ret_dn = talloc_steal(mem_ctx, msg->dn);
2948 talloc_free(sidstr);
2950 return NT_STATUS_OK;
2955 Find the DN of a domain, assuming it to be a dotted.dns name
2958 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
2961 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2962 const char *binary_encoded;
2963 const char * const *split_realm;
2970 split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
2972 talloc_free(tmp_ctx);
2975 dn = ldb_dn_new(mem_ctx, ldb, NULL);
2976 for (i=0; split_realm[i]; i++) {
2977 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2978 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2979 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2980 binary_encoded, ldb_dn_get_linearized(dn)));
2981 talloc_free(tmp_ctx);
2985 if (!ldb_dn_validate(dn)) {
2986 DEBUG(2, ("Failed to validated DN %s\n",
2987 ldb_dn_get_linearized(dn)));
2988 talloc_free(tmp_ctx);
2991 talloc_free(tmp_ctx);
2997 Find the DNS equivalent of a DN, in dotted DNS form
2999 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
3001 int i, num_components = ldb_dn_get_comp_num(dn);
3002 char *dns_name = talloc_strdup(mem_ctx, "");
3003 if (dns_name == NULL) {
3007 for (i=0; i<num_components; i++) {
3008 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
3011 talloc_free(dns_name);
3014 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
3015 (int)v->length, (int)v->length, (char *)v->data);
3017 talloc_free(dns_name);
3023 /* remove the last '.' */
3024 if (dns_name[0] != 0) {
3025 dns_name[strlen(dns_name)-1] = 0;
3032 Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
3033 name is based on the forest DNS name
3035 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
3036 TALLOC_CTX *mem_ctx,
3037 const struct GUID *ntds_guid)
3039 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3040 const char *guid_str;
3041 struct ldb_dn *forest_dn;
3042 const char *dnsforest;
3045 guid_str = GUID_string(tmp_ctx, ntds_guid);
3046 if (guid_str == NULL) {
3047 talloc_free(tmp_ctx);
3050 forest_dn = ldb_get_root_basedn(samdb);
3051 if (forest_dn == NULL) {
3052 talloc_free(tmp_ctx);
3055 dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
3056 if (dnsforest == NULL) {
3057 talloc_free(tmp_ctx);
3060 ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
3061 talloc_free(tmp_ctx);
3067 Find the DN of a domain, be it the netbios or DNS name
3069 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
3070 const char *domain_name)
3072 const char * const domain_ref_attrs[] = {
3075 const char * const domain_ref2_attrs[] = {
3078 struct ldb_result *res_domain_ref;
3079 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
3080 /* find the domain's DN */
3081 int ret_domain = ldb_search(ldb, mem_ctx,
3083 samdb_partitions_dn(ldb, mem_ctx),
3086 "(&(nETBIOSName=%s)(objectclass=crossRef))",
3088 if (ret_domain != LDB_SUCCESS) {
3092 if (res_domain_ref->count == 0) {
3093 ret_domain = ldb_search(ldb, mem_ctx,
3095 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
3098 "(objectclass=domain)");
3099 if (ret_domain != LDB_SUCCESS) {
3103 if (res_domain_ref->count == 1) {
3104 return res_domain_ref->msgs[0]->dn;
3109 if (res_domain_ref->count > 1) {
3110 DEBUG(0,("Found %d records matching domain [%s]\n",
3111 ret_domain, domain_name));
3115 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
3121 use a GUID to find a DN
3123 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
3124 TALLOC_CTX *mem_ctx,
3125 const struct GUID *guid,
3126 uint32_t dsdb_flags,
3130 struct ldb_result *res;
3131 const char *attrs[] = { NULL };
3132 char *guid_str = GUID_string(mem_ctx, guid);
3135 return ldb_operr(ldb);
3138 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3139 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3140 DSDB_SEARCH_SHOW_EXTENDED_DN |
3141 DSDB_SEARCH_ONE_ONLY | dsdb_flags,
3142 "objectGUID=%s", guid_str);
3143 talloc_free(guid_str);
3144 if (ret != LDB_SUCCESS) {
3148 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3155 use a DN to find a GUID with a given attribute name
3157 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
3158 struct ldb_dn *dn, const char *attribute,
3162 struct ldb_result *res;
3163 const char *attrs[2];
3164 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3166 attrs[0] = attribute;
3169 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3170 DSDB_SEARCH_SHOW_DELETED |
3171 DSDB_SEARCH_SHOW_RECYCLED);
3172 if (ret != LDB_SUCCESS) {
3173 talloc_free(tmp_ctx);
3176 if (res->count < 1) {
3177 talloc_free(tmp_ctx);
3178 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3180 *guid = samdb_result_guid(res->msgs[0], attribute);
3181 talloc_free(tmp_ctx);
3186 use a DN to find a GUID
3188 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
3189 struct ldb_dn *dn, struct GUID *guid)
3191 return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
3197 adds the given GUID to the given ldb_message. This value is added
3198 for the given attr_name (may be either "objectGUID" or "parentGUID").
3200 int dsdb_msg_add_guid(struct ldb_message *msg,
3202 const char *attr_name)
3207 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
3209 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
3210 if (!NT_STATUS_IS_OK(status)) {
3211 ret = LDB_ERR_OPERATIONS_ERROR;
3215 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
3216 if (ret != LDB_SUCCESS) {
3217 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
3225 talloc_free(tmp_ctx);
3232 use a DN to find a SID
3234 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
3235 struct ldb_dn *dn, struct dom_sid *sid)
3238 struct ldb_result *res;
3239 const char *attrs[] = { "objectSid", NULL };
3240 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3245 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3246 DSDB_SEARCH_SHOW_DELETED |
3247 DSDB_SEARCH_SHOW_RECYCLED);
3248 if (ret != LDB_SUCCESS) {
3249 talloc_free(tmp_ctx);
3252 if (res->count < 1) {
3253 talloc_free(tmp_ctx);
3254 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3256 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
3258 talloc_free(tmp_ctx);
3259 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3262 talloc_free(tmp_ctx);
3267 use a SID to find a DN
3269 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
3270 TALLOC_CTX *mem_ctx,
3271 struct dom_sid *sid, struct ldb_dn **dn)
3274 struct ldb_result *res;
3275 const char *attrs[] = { NULL };
3276 char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
3279 return ldb_operr(ldb);
3282 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3283 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3284 DSDB_SEARCH_SHOW_EXTENDED_DN |
3285 DSDB_SEARCH_ONE_ONLY,
3286 "objectSid=%s", sid_str);
3287 talloc_free(sid_str);
3288 if (ret != LDB_SUCCESS) {
3292 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3299 load a repsFromTo blob list for a given partition GUID
3300 attr must be "repsFrom" or "repsTo"
3302 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3303 const char *attr, struct repsFromToBlob **r, uint32_t *count)
3305 const char *attrs[] = { attr, NULL };
3306 struct ldb_result *res = NULL;
3307 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3309 struct ldb_message_element *el;
3315 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
3316 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3317 /* partition hasn't been replicated yet */
3320 if (ret != LDB_SUCCESS) {
3321 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
3322 talloc_free(tmp_ctx);
3323 return WERR_DS_DRA_INTERNAL_ERROR;
3326 el = ldb_msg_find_element(res->msgs[0], attr);
3328 /* it's OK to be empty */
3329 talloc_free(tmp_ctx);
3333 *count = el->num_values;
3334 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
3336 talloc_free(tmp_ctx);
3337 return WERR_DS_DRA_INTERNAL_ERROR;
3340 for (i=0; i<(*count); i++) {
3341 enum ndr_err_code ndr_err;
3342 ndr_err = ndr_pull_struct_blob(&el->values[i],
3345 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3346 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3347 talloc_free(tmp_ctx);
3348 return WERR_DS_DRA_INTERNAL_ERROR;
3352 talloc_free(tmp_ctx);
3358 save the repsFromTo blob list for a given partition GUID
3359 attr must be "repsFrom" or "repsTo"
3361 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3362 const char *attr, struct repsFromToBlob *r, uint32_t count)
3364 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3365 struct ldb_message *msg;
3366 struct ldb_message_element *el;
3369 msg = ldb_msg_new(tmp_ctx);
3371 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
3375 el->values = talloc_array(msg, struct ldb_val, count);
3380 for (i=0; i<count; i++) {
3382 enum ndr_err_code ndr_err;
3384 ndr_err = ndr_push_struct_blob(&v, tmp_ctx,
3386 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3387 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3395 if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
3396 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
3400 talloc_free(tmp_ctx);
3405 talloc_free(tmp_ctx);
3406 return WERR_DS_DRA_INTERNAL_ERROR;
3411 load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
3412 object for a partition
3414 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
3415 uint64_t *uSN, uint64_t *urgent_uSN)
3417 struct ldb_request *req;
3419 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3420 struct dsdb_control_current_partition *p_ctrl;
3421 struct ldb_result *res;
3423 res = talloc_zero(tmp_ctx, struct ldb_result);
3425 talloc_free(tmp_ctx);
3426 return ldb_oom(ldb);
3429 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3430 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
3434 res, ldb_search_default_callback,
3436 if (ret != LDB_SUCCESS) {
3437 talloc_free(tmp_ctx);
3441 p_ctrl = talloc(req, struct dsdb_control_current_partition);
3442 if (p_ctrl == NULL) {
3443 talloc_free(tmp_ctx);
3444 return ldb_oom(ldb);
3446 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
3449 ret = ldb_request_add_control(req,
3450 DSDB_CONTROL_CURRENT_PARTITION_OID,
3452 if (ret != LDB_SUCCESS) {
3453 talloc_free(tmp_ctx);
3457 /* Run the new request */
3458 ret = ldb_request(ldb, req);
3460 if (ret == LDB_SUCCESS) {
3461 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3464 if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
3465 /* it hasn't been created yet, which means
3466 an implicit value of zero */
3468 talloc_free(tmp_ctx);
3472 if (ret != LDB_SUCCESS) {
3473 talloc_free(tmp_ctx);
3477 if (res->count < 1) {
3483 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
3485 *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
3489 talloc_free(tmp_ctx);
3494 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
3495 const struct drsuapi_DsReplicaCursor2 *c2)
3497 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3500 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
3501 const struct drsuapi_DsReplicaCursor *c2)
3503 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3508 see if a computer identified by its invocationId is a RODC
3510 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
3512 /* 1) find the DN for this servers NTDSDSA object
3513 2) search for the msDS-isRODC attribute
3514 3) if not present then not a RODC
3515 4) if present and TRUE then is a RODC
3517 struct ldb_dn *config_dn;
3518 const char *attrs[] = { "msDS-isRODC", NULL };
3520 struct ldb_result *res;
3521 TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
3523 config_dn = ldb_get_config_basedn(sam_ctx);
3525 talloc_free(tmp_ctx);
3526 return ldb_operr(sam_ctx);
3529 ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
3530 DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
3532 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3534 talloc_free(tmp_ctx);
3538 if (ret != LDB_SUCCESS) {
3539 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
3540 GUID_string(tmp_ctx, objectGUID)));
3542 talloc_free(tmp_ctx);
3546 ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
3547 *is_rodc = (ret == 1);
3549 talloc_free(tmp_ctx);
3555 see if we are a RODC
3557 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
3559 const struct GUID *objectGUID;
3563 /* see if we have a cached copy */
3564 cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
3570 objectGUID = samdb_ntds_objectGUID(sam_ctx);
3572 return ldb_operr(sam_ctx);
3575 ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
3576 if (ret != LDB_SUCCESS) {
3580 cached = talloc(sam_ctx, bool);
3581 if (cached == NULL) {
3582 return ldb_oom(sam_ctx);
3586 ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
3587 if (ret != LDB_SUCCESS) {
3588 talloc_free(cached);
3589 return ldb_operr(sam_ctx);
3595 int samdb_dns_host_name(struct ldb_context *sam_ctx, const char **host_name)
3597 const char *_host_name = NULL;
3598 const char *attrs[] = { "dnsHostName", NULL };
3599 TALLOC_CTX *tmp_ctx = NULL;
3601 struct ldb_result *res = NULL;
3603 _host_name = (const char *)ldb_get_opaque(sam_ctx, "cache.dns_host_name");
3604 if (_host_name != NULL) {
3605 *host_name = _host_name;
3609 tmp_ctx = talloc_new(sam_ctx);
3611 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, NULL, attrs, 0);
3613 if (res->count != 1 || ret != LDB_SUCCESS) {
3614 DEBUG(0, ("Failed to get rootDSE for dnsHostName: %s",
3615 ldb_errstring(sam_ctx)));
3616 TALLOC_FREE(tmp_ctx);
3621 _host_name = ldb_msg_find_attr_as_string(res->msgs[0],
3624 if (_host_name == NULL) {
3625 DEBUG(0, ("Failed to get dnsHostName from rootDSE"));
3626 TALLOC_FREE(tmp_ctx);
3627 return LDB_ERR_OPERATIONS_ERROR;
3629 ret = ldb_set_opaque(sam_ctx, "cache.dns_host_name",
3630 discard_const_p(char *, _host_name));
3631 if (ret != LDB_SUCCESS) {
3632 TALLOC_FREE(tmp_ctx);
3633 return ldb_operr(sam_ctx);
3636 *host_name = talloc_steal(sam_ctx, _host_name);
3638 TALLOC_FREE(tmp_ctx);
3642 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3644 TALLOC_CTX *tmp_ctx;
3647 tmp_ctx = talloc_new(ldb);
3648 if (tmp_ctx == NULL) {
3652 cached = talloc(tmp_ctx, bool);
3658 if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3662 talloc_steal(ldb, cached);
3663 talloc_free(tmp_ctx);
3667 DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3668 talloc_free(tmp_ctx);
3674 * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3675 * flags are DS_NTDSSETTINGS_OPT_*
3677 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3681 TALLOC_CTX *tmp_ctx;
3682 struct ldb_result *res;
3683 struct ldb_dn *site_dn;
3684 const char *attrs[] = { "options", NULL };
3686 tmp_ctx = talloc_new(ldb_ctx);
3687 if (tmp_ctx == NULL)
3690 /* Retrieve the site dn for the ldb that we
3691 * have open. This is our local site.
3693 site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3694 if (site_dn == NULL)
3697 /* Perform a one level (child) search from the local
3698 * site distinguided name. We're looking for the
3699 * "options" attribute within the nTDSSiteSettings
3702 rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3703 LDB_SCOPE_ONELEVEL, attrs,
3704 "objectClass=nTDSSiteSettings");
3706 if (rc != LDB_SUCCESS || res->count != 1)
3709 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3711 talloc_free(tmp_ctx);
3716 DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3717 talloc_free(tmp_ctx);
3718 return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
3722 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
3724 flags are DS_NTDS_OPTION_*
3726 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3728 TALLOC_CTX *tmp_ctx;
3729 const char *attrs[] = { "options", NULL };
3731 struct ldb_result *res;
3733 tmp_ctx = talloc_new(ldb);
3734 if (tmp_ctx == NULL) {
3738 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3739 if (ret != LDB_SUCCESS) {
3743 if (res->count != 1) {
3747 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3749 talloc_free(tmp_ctx);
3754 DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3755 talloc_free(tmp_ctx);
3756 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3759 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3761 const char *attrs[] = { "objectCategory", NULL };
3763 struct ldb_result *res;
3765 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3766 if (ret != LDB_SUCCESS) {
3770 if (res->count != 1) {
3774 return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3777 DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3782 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3783 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3785 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3787 char **tokens, *ret;
3790 tokens = str_list_make(mem_ctx, cn, " -_");
3791 if (tokens == NULL || tokens[0] == NULL) {
3795 /* "tolower()" and "toupper()" should also work properly on 0x00 */
3796 tokens[0][0] = tolower(tokens[0][0]);
3797 for (i = 1; tokens[i] != NULL; i++)
3798 tokens[i][0] = toupper(tokens[i][0]);
3800 ret = talloc_strdup(mem_ctx, tokens[0]);
3801 for (i = 1; tokens[i] != NULL; i++)
3802 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3804 talloc_free(tokens);
3810 * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3812 int dsdb_functional_level(struct ldb_context *ldb)
3814 int *domainFunctionality =
3815 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3816 if (!domainFunctionality) {
3817 /* this is expected during initial provision */
3818 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3819 return DS_DOMAIN_FUNCTION_2000;
3821 return *domainFunctionality;
3825 * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3827 int dsdb_forest_functional_level(struct ldb_context *ldb)
3829 int *forestFunctionality =
3830 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3831 if (!forestFunctionality) {
3832 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3833 return DS_DOMAIN_FUNCTION_2000;
3835 return *forestFunctionality;
3839 set a GUID in an extended DN structure
3841 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3847 status = GUID_to_ndr_blob(guid, dn, &v);
3848 if (!NT_STATUS_IS_OK(status)) {
3849 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3852 ret = ldb_dn_set_extended_component(dn, component_name, &v);
3858 return a GUID from a extended DN structure
3860 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3862 const struct ldb_val *v;
3864 v = ldb_dn_get_extended_component(dn, component_name);
3866 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3869 return GUID_from_ndr_blob(v, guid);
3873 return a uint64_t from a extended DN structure
3875 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3877 const struct ldb_val *v;
3879 v = ldb_dn_get_extended_component(dn, component_name);
3881 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3884 /* Just check we don't allow the caller to fill our stack */
3885 if (v->length >= 64) {
3886 return NT_STATUS_INVALID_PARAMETER;
3888 char s[v->length+1];
3889 memcpy(s, v->data, v->length);
3892 *val = strtoull(s, NULL, 0);
3894 return NT_STATUS_OK;
3898 return a NTTIME from a extended DN structure
3900 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3902 return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3906 return a uint32_t from a extended DN structure
3908 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3910 const struct ldb_val *v;
3912 v = ldb_dn_get_extended_component(dn, component_name);
3914 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3917 /* Just check we don't allow the caller to fill our stack */
3918 if (v->length >= 32) {
3919 return NT_STATUS_INVALID_PARAMETER;
3921 char s[v->length + 1];
3922 memcpy(s, v->data, v->length);
3924 *val = strtoul(s, NULL, 0);
3927 return NT_STATUS_OK;
3931 return a dom_sid from a extended DN structure
3933 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3935 const struct ldb_val *sid_blob;
3936 enum ndr_err_code ndr_err;
3938 sid_blob = ldb_dn_get_extended_component(dn, component_name);
3940 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3943 ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
3944 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3945 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3946 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3950 return NT_STATUS_OK;
3955 return RMD_FLAGS directly from a ldb_dn
3956 returns 0 if not found
3958 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3960 uint32_t rmd_flags = 0;
3961 NTSTATUS status = dsdb_get_extended_dn_uint32(dn, &rmd_flags,
3963 if (NT_STATUS_IS_OK(status)) {
3970 return RMD_FLAGS directly from a ldb_val for a DN
3971 returns 0 if RMD_FLAGS is not found
3973 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3979 if (val->length < 13) {
3982 p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3986 flags = strtoul(p+11, &end, 10);
3987 if (!end || *end != '>') {
3988 /* it must end in a > */
3995 return true if a ldb_val containing a DN in storage form is deleted
3997 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3999 return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
4003 return true if a ldb_val containing a DN in storage form is
4004 in the upgraded w2k3 linked attribute format
4006 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
4008 return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
4012 return a DN for a wellknown GUID
4014 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
4015 struct ldb_dn *nc_root, const char *wk_guid,
4016 struct ldb_dn **wkguid_dn)
4018 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4019 const char *attrs[] = { NULL };
4022 struct ldb_result *res;
4024 /* construct the magic WKGUID DN */
4025 dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
4026 wk_guid, ldb_dn_get_linearized(nc_root));
4028 talloc_free(tmp_ctx);
4029 return ldb_operr(samdb);
4032 ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
4033 DSDB_SEARCH_SHOW_DELETED |
4034 DSDB_SEARCH_SHOW_RECYCLED);
4035 if (ret != LDB_SUCCESS) {
4036 talloc_free(tmp_ctx);
4040 (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
4041 talloc_free(tmp_ctx);
4046 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
4048 return ldb_dn_compare(*dn1, *dn2);
4052 find a NC root given a DN within the NC
4054 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
4055 struct ldb_dn **nc_root)
4057 const char *root_attrs[] = { "namingContexts", NULL };
4058 TALLOC_CTX *tmp_ctx;
4060 struct ldb_message_element *el;
4061 struct ldb_result *root_res;
4063 struct ldb_dn **nc_dns;
4065 tmp_ctx = talloc_new(samdb);
4066 if (tmp_ctx == NULL) {
4067 return ldb_oom(samdb);
4070 ret = ldb_search(samdb, tmp_ctx, &root_res,
4071 ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
4072 if (ret != LDB_SUCCESS || root_res->count == 0) {
4073 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
4074 talloc_free(tmp_ctx);
4078 el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
4079 if ((el == NULL) || (el->num_values < 3)) {
4080 struct ldb_message *tmp_msg;
4082 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list.\n"));
4084 /* This generates a temporary list of NCs in order to let the
4085 * provisioning work. */
4086 tmp_msg = ldb_msg_new(tmp_ctx);
4087 if (tmp_msg == NULL) {
4088 talloc_free(tmp_ctx);
4089 return ldb_oom(samdb);
4091 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4092 ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
4093 if (ret != LDB_SUCCESS) {
4094 talloc_free(tmp_ctx);
4097 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4098 ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
4099 if (ret != LDB_SUCCESS) {
4100 talloc_free(tmp_ctx);
4103 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4104 ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
4105 if (ret != LDB_SUCCESS) {
4106 talloc_free(tmp_ctx);
4109 el = &tmp_msg->elements[0];
4112 nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
4114 talloc_free(tmp_ctx);
4115 return ldb_oom(samdb);
4118 for (i=0; i<el->num_values; i++) {
4119 nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
4120 if (nc_dns[i] == NULL) {
4121 talloc_free(tmp_ctx);
4122 return ldb_operr(samdb);
4126 TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
4128 for (i=0; i<el->num_values; i++) {
4129 if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
4130 (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
4131 talloc_free(tmp_ctx);
4136 talloc_free(tmp_ctx);
4137 return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4142 find the deleted objects DN for any object, by looking for the NC
4143 root, then looking up the wellknown GUID
4145 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
4146 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
4147 struct ldb_dn **do_dn)
4149 struct ldb_dn *nc_root;
4152 ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
4153 if (ret != LDB_SUCCESS) {
4157 ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
4158 talloc_free(nc_root);
4163 return the tombstoneLifetime, in days
4165 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
4168 dn = ldb_get_config_basedn(ldb);
4170 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4172 dn = ldb_dn_copy(ldb, dn);
4174 return ldb_operr(ldb);
4176 /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
4177 be a wellknown GUID for this */
4178 if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
4180 return ldb_operr(ldb);
4183 *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
4189 compare a ldb_val to a string case insensitively
4191 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
4193 size_t len = strlen(s);
4195 if (len > v->length) return 1;
4196 ret = strncasecmp(s, (const char *)v->data, v->length);
4197 if (ret != 0) return ret;
4198 if (v->length > len && v->data[len] != 0) {
4206 load the UDV for a partition in v2 format
4207 The list is returned sorted, and with our local cursor added
4209 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4210 struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
4212 static const char *attrs[] = { "replUpToDateVector", NULL };
4213 struct ldb_result *r;
4214 const struct ldb_val *ouv_value;
4217 uint64_t highest_usn = 0;
4218 const struct GUID *our_invocation_id;
4219 static const struct timeval tv1970;
4220 NTTIME nt1970 = timeval_to_nttime(&tv1970);
4222 ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
4223 if (ret != LDB_SUCCESS) {
4227 ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
4229 enum ndr_err_code ndr_err;
4230 struct replUpToDateVectorBlob ouv;
4232 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
4233 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
4234 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4236 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4238 if (ouv.version != 2) {
4239 /* we always store as version 2, and
4240 * replUpToDateVector is not replicated
4242 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4245 *count = ouv.ctr.ctr2.count;
4246 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
4254 our_invocation_id = samdb_ntds_invocation_id(samdb);
4255 if (!our_invocation_id) {
4256 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
4257 talloc_free(*cursors);
4258 return ldb_operr(samdb);
4261 ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
4262 if (ret != LDB_SUCCESS) {
4263 /* nothing to add - this can happen after a vampire */
4264 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4268 for (i=0; i<*count; i++) {
4269 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
4270 (*cursors)[i].highest_usn = highest_usn;
4271 (*cursors)[i].last_sync_success = nt1970;
4272 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4277 (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
4279 return ldb_oom(samdb);
4282 (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
4283 (*cursors)[*count].highest_usn = highest_usn;
4284 (*cursors)[*count].last_sync_success = nt1970;
4287 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4293 load the UDV for a partition in version 1 format
4294 The list is returned sorted, and with our local cursor added
4296 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4297 struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
4299 struct drsuapi_DsReplicaCursor2 *v2;
4303 ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
4304 if (ret != LDB_SUCCESS) {
4314 *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
4315 if (*cursors == NULL) {
4317 return ldb_oom(samdb);
4320 for (i=0; i<*count; i++) {
4321 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
4322 (*cursors)[i].highest_usn = v2[i].highest_usn;
4329 add a set of controls to a ldb_request structure based on a set of
4330 flags. See util.h for a list of available flags
4332 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
4335 if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
4336 struct ldb_search_options_control *options;
4337 /* Using the phantom root control allows us to search all partitions */
4338 options = talloc(req, struct ldb_search_options_control);
4339 if (options == NULL) {
4340 return LDB_ERR_OPERATIONS_ERROR;
4342 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
4344 ret = ldb_request_add_control(req,
4345 LDB_CONTROL_SEARCH_OPTIONS_OID,
4347 if (ret != LDB_SUCCESS) {
4352 if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
4353 ret = ldb_request_add_control(req,
4354 DSDB_CONTROL_NO_GLOBAL_CATALOG,
4356 if (ret != LDB_SUCCESS) {
4361 if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
4362 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
4363 if (ret != LDB_SUCCESS) {
4368 if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
4369 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
4370 if (ret != LDB_SUCCESS) {
4375 if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
4376 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
4377 if (ret != LDB_SUCCESS) {
4382 if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
4383 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
4384 if (!extended_ctrl) {
4385 return LDB_ERR_OPERATIONS_ERROR;
4387 extended_ctrl->type = 1;
4389 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
4390 if (ret != LDB_SUCCESS) {
4395 if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
4396 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
4397 if (ret != LDB_SUCCESS) {
4402 if (dsdb_flags & DSDB_MODIFY_RELAX) {
4403 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
4404 if (ret != LDB_SUCCESS) {
4409 if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
4410 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
4411 if (ret != LDB_SUCCESS) {
4416 if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
4417 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
4418 if (ret != LDB_SUCCESS) {
4423 if (dsdb_flags & DSDB_TREE_DELETE) {
4424 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
4425 if (ret != LDB_SUCCESS) {
4430 if (dsdb_flags & DSDB_PROVISION) {
4431 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
4432 if (ret != LDB_SUCCESS) {
4437 /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
4438 if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
4439 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
4440 if (ret != LDB_SUCCESS) {
4445 if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
4447 * This must not be critical, as it will only be
4448 * handled (and need to be handled) if the other
4449 * attributes in the request bring password_hash into
4452 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
4453 if (ret != LDB_SUCCESS) {
4458 if (dsdb_flags & DSDB_REPLMD_VANISH_LINKS) {
4459 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLMD_VANISH_LINKS, true, NULL);
4460 if (ret != LDB_SUCCESS) {
4465 if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
4466 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
4467 if (ret != LDB_SUCCESS) {
4472 if (dsdb_flags & DSDB_FLAG_REPLICATED_UPDATE) {
4473 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
4474 if (ret != LDB_SUCCESS) {
4483 returns true if a control with the specified "oid" exists
4485 bool dsdb_request_has_control(struct ldb_request *req, const char *oid)
4487 return (ldb_request_get_control(req, oid) != NULL);
4491 an add with a set of controls
4493 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
4494 uint32_t dsdb_flags)
4496 struct ldb_request *req;
4499 ret = ldb_build_add_req(&req, ldb, ldb,
4503 ldb_op_default_callback,
4506 if (ret != LDB_SUCCESS) return ret;
4508 ret = dsdb_request_add_controls(req, dsdb_flags);
4509 if (ret != LDB_SUCCESS) {
4514 ret = dsdb_autotransaction_request(ldb, req);
4521 a modify with a set of controls
4523 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
4524 uint32_t dsdb_flags)
4526 struct ldb_request *req;
4529 ret = ldb_build_mod_req(&req, ldb, ldb,
4533 ldb_op_default_callback,
4536 if (ret != LDB_SUCCESS) return ret;
4538 ret = dsdb_request_add_controls(req, dsdb_flags);
4539 if (ret != LDB_SUCCESS) {
4544 ret = dsdb_autotransaction_request(ldb, req);
4551 a delete with a set of flags
4553 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
4554 uint32_t dsdb_flags)
4556 struct ldb_request *req;
4559 ret = ldb_build_del_req(&req, ldb, ldb,
4563 ldb_op_default_callback,
4566 if (ret != LDB_SUCCESS) return ret;
4568 ret = dsdb_request_add_controls(req, dsdb_flags);
4569 if (ret != LDB_SUCCESS) {
4574 ret = dsdb_autotransaction_request(ldb, req);
4581 like dsdb_modify() but set all the element flags to
4582 LDB_FLAG_MOD_REPLACE
4584 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
4588 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
4589 for (i=0;i<msg->num_elements;i++) {
4590 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
4593 return dsdb_modify(ldb, msg, dsdb_flags);
4598 search for attrs on one DN, allowing for dsdb_flags controls
4600 int dsdb_search_dn(struct ldb_context *ldb,
4601 TALLOC_CTX *mem_ctx,
4602 struct ldb_result **_result,
4603 struct ldb_dn *basedn,
4604 const char * const *attrs,
4605 uint32_t dsdb_flags)
4608 struct ldb_request *req;
4609 struct ldb_result *res;
4611 res = talloc_zero(mem_ctx, struct ldb_result);
4613 return ldb_oom(ldb);
4616 ret = ldb_build_search_req(&req, ldb, res,
4623 ldb_search_default_callback,
4625 if (ret != LDB_SUCCESS) {
4630 ret = dsdb_request_add_controls(req, dsdb_flags);
4631 if (ret != LDB_SUCCESS) {
4636 ret = ldb_request(ldb, req);
4637 if (ret == LDB_SUCCESS) {
4638 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4642 if (ret != LDB_SUCCESS) {
4652 search for attrs on one DN, by the GUID of the DN, allowing for
4655 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
4656 TALLOC_CTX *mem_ctx,
4657 struct ldb_result **_result,
4658 const struct GUID *guid,
4659 const char * const *attrs,
4660 uint32_t dsdb_flags)
4662 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4666 dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
4668 talloc_free(tmp_ctx);
4669 return ldb_oom(ldb);
4672 ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
4673 talloc_free(tmp_ctx);
4678 general search with dsdb_flags for controls
4680 int dsdb_search(struct ldb_context *ldb,
4681 TALLOC_CTX *mem_ctx,
4682 struct ldb_result **_result,
4683 struct ldb_dn *basedn,
4684 enum ldb_scope scope,
4685 const char * const *attrs,
4686 uint32_t dsdb_flags,
4687 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4690 struct ldb_request *req;
4691 struct ldb_result *res;
4693 char *expression = NULL;
4694 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4696 /* cross-partitions searches with a basedn break multi-domain support */
4697 SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
4699 res = talloc_zero(tmp_ctx, struct ldb_result);
4701 talloc_free(tmp_ctx);
4702 return ldb_oom(ldb);
4706 va_start(ap, exp_fmt);
4707 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4711 talloc_free(tmp_ctx);
4712 return ldb_oom(ldb);
4716 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
4723 ldb_search_default_callback,
4725 if (ret != LDB_SUCCESS) {
4726 talloc_free(tmp_ctx);
4730 ret = dsdb_request_add_controls(req, dsdb_flags);
4731 if (ret != LDB_SUCCESS) {
4732 talloc_free(tmp_ctx);
4733 ldb_reset_err_string(ldb);
4737 ret = ldb_request(ldb, req);
4738 if (ret == LDB_SUCCESS) {
4739 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4742 if (ret != LDB_SUCCESS) {
4743 talloc_free(tmp_ctx);
4747 if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
4748 if (res->count == 0) {
4749 talloc_free(tmp_ctx);
4750 ldb_reset_err_string(ldb);
4751 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4753 if (res->count != 1) {
4754 talloc_free(tmp_ctx);
4755 ldb_reset_err_string(ldb);
4756 return LDB_ERR_CONSTRAINT_VIOLATION;
4760 *_result = talloc_steal(mem_ctx, res);
4761 talloc_free(tmp_ctx);
4768 general search with dsdb_flags for controls
4769 returns exactly 1 record or an error
4771 int dsdb_search_one(struct ldb_context *ldb,
4772 TALLOC_CTX *mem_ctx,
4773 struct ldb_message **msg,
4774 struct ldb_dn *basedn,
4775 enum ldb_scope scope,
4776 const char * const *attrs,
4777 uint32_t dsdb_flags,
4778 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4781 struct ldb_result *res;
4783 char *expression = NULL;
4784 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4786 dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4788 res = talloc_zero(tmp_ctx, struct ldb_result);
4790 talloc_free(tmp_ctx);
4791 return ldb_oom(ldb);
4795 va_start(ap, exp_fmt);
4796 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4800 talloc_free(tmp_ctx);
4801 return ldb_oom(ldb);
4803 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4804 dsdb_flags, "%s", expression);
4806 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4810 if (ret != LDB_SUCCESS) {
4811 talloc_free(tmp_ctx);
4815 *msg = talloc_steal(mem_ctx, res->msgs[0]);
4816 talloc_free(tmp_ctx);
4821 /* returns back the forest DNS name */
4822 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4824 const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4825 ldb_get_root_basedn(ldb));
4828 if (forest_name == NULL) {
4832 p = strchr(forest_name, '/');
4840 /* returns back the default domain DNS name */
4841 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4843 const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4844 ldb_get_default_basedn(ldb));
4847 if (domain_name == NULL) {
4851 p = strchr(domain_name, '/');
4860 validate that an DSA GUID belongs to the specified user sid.
4861 The user SID must be a domain controller account (either RODC or
4864 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4865 const struct GUID *dsa_guid,
4866 const struct dom_sid *sid)
4869 - find DN of record with the DSA GUID in the
4870 configuration partition (objectGUID)
4871 - remove "NTDS Settings" component from DN
4872 - do a base search on that DN for serverReference with
4874 - extract objectSid from resulting serverReference
4876 - check this sid matches the sid argument
4878 struct ldb_dn *config_dn;
4879 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4880 struct ldb_message *msg;
4881 const char *attrs1[] = { NULL };
4882 const char *attrs2[] = { "serverReference", NULL };
4884 struct ldb_dn *dn, *account_dn;
4885 struct dom_sid sid2;
4888 config_dn = ldb_get_config_basedn(ldb);
4890 ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4891 attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4892 if (ret != LDB_SUCCESS) {
4893 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4894 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4895 talloc_free(tmp_ctx);
4896 return ldb_operr(ldb);
4900 if (!ldb_dn_remove_child_components(dn, 1)) {
4901 talloc_free(tmp_ctx);
4902 return ldb_operr(ldb);
4905 ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4906 attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4907 "(objectClass=server)");
4908 if (ret != LDB_SUCCESS) {
4909 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4910 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4911 talloc_free(tmp_ctx);
4912 return ldb_operr(ldb);
4915 account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4916 if (account_dn == NULL) {
4917 DEBUG(1,(__location__ ": Failed to find account dn "
4918 "(serverReference) for %s, parent of DSA with "
4919 "objectGUID %s, sid %s\n",
4920 ldb_dn_get_linearized(msg->dn),
4921 GUID_string(tmp_ctx, dsa_guid),
4922 dom_sid_string(tmp_ctx, sid)));
4923 talloc_free(tmp_ctx);
4924 return ldb_operr(ldb);
4927 status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4928 if (!NT_STATUS_IS_OK(status)) {
4929 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4930 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4931 talloc_free(tmp_ctx);
4932 return ldb_operr(ldb);
4935 if (!dom_sid_equal(sid, &sid2)) {
4936 /* someone is trying to spoof another account */
4937 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4938 GUID_string(tmp_ctx, dsa_guid),
4939 dom_sid_string(tmp_ctx, sid),
4940 dom_sid_string(tmp_ctx, &sid2)));
4941 talloc_free(tmp_ctx);
4942 return ldb_operr(ldb);
4945 talloc_free(tmp_ctx);
4949 static const char * const secret_attributes[] = {
4950 DSDB_SECRET_ATTRIBUTES,
4955 check if the attribute belongs to the RODC filtered attribute set
4956 Note that attributes that are in the filtered attribute set are the
4957 ones that _are_ always sent to a RODC
4959 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4961 /* they never get secret attributes */
4962 if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4966 /* they do get non-secret critical attributes */
4967 if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4971 /* they do get non-secret attributes marked as being in the FAS */
4972 if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4976 /* other attributes are denied */
4980 /* return fsmo role dn and role owner dn for a particular role*/
4981 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4982 struct ldb_context *ldb,
4984 struct ldb_dn **fsmo_role_dn,
4985 struct ldb_dn **role_owner_dn)
4989 case DREPL_NAMING_MASTER:
4990 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4991 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4992 if (ret != LDB_SUCCESS) {
4993 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4994 ldb_errstring(ldb)));
4995 talloc_free(tmp_ctx);
4996 return WERR_DS_DRA_INTERNAL_ERROR;
4999 case DREPL_INFRASTRUCTURE_MASTER:
5000 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
5001 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5002 if (ret != LDB_SUCCESS) {
5003 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5004 ldb_errstring(ldb)));
5005 talloc_free(tmp_ctx);
5006 return WERR_DS_DRA_INTERNAL_ERROR;
5009 case DREPL_RID_MASTER:
5010 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
5011 if (ret != LDB_SUCCESS) {
5012 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
5013 talloc_free(tmp_ctx);
5014 return WERR_DS_DRA_INTERNAL_ERROR;
5017 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5018 if (ret != LDB_SUCCESS) {
5019 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
5020 ldb_errstring(ldb)));
5021 talloc_free(tmp_ctx);
5022 return WERR_DS_DRA_INTERNAL_ERROR;
5025 case DREPL_SCHEMA_MASTER:
5026 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
5027 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5028 if (ret != LDB_SUCCESS) {
5029 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5030 ldb_errstring(ldb)));
5031 talloc_free(tmp_ctx);
5032 return WERR_DS_DRA_INTERNAL_ERROR;
5035 case DREPL_PDC_MASTER:
5036 *fsmo_role_dn = ldb_get_default_basedn(ldb);
5037 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5038 if (ret != LDB_SUCCESS) {
5039 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
5040 ldb_errstring(ldb)));
5041 talloc_free(tmp_ctx);
5042 return WERR_DS_DRA_INTERNAL_ERROR;
5046 return WERR_DS_DRA_INTERNAL_ERROR;
5051 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
5052 TALLOC_CTX *mem_ctx,
5053 struct ldb_dn *server_dn)
5056 struct ldb_result *res = NULL;
5057 const char * const attrs[] = { "dNSHostName", NULL};
5059 ldb_ret = ldb_search(ldb, mem_ctx, &res,
5063 if (ldb_ret != LDB_SUCCESS) {
5064 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
5065 ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
5069 return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
5073 returns true if an attribute is in the filter,
5074 false otherwise, provided that attribute value is provided with the expression
5076 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
5080 switch (tree->operation) {
5083 for (i=0;i<tree->u.list.num_elements;i++) {
5084 if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
5090 return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
5091 case LDB_OP_EQUALITY:
5092 case LDB_OP_GREATER:
5095 if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
5099 case LDB_OP_SUBSTRING:
5100 if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
5104 case LDB_OP_PRESENT:
5105 /* (attrname=*) is not filtered out */
5107 case LDB_OP_EXTENDED:
5108 if (tree->u.extended.attr &&
5109 ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
5117 bool is_attr_in_list(const char * const * attrs, const char *attr)
5121 for (i = 0; attrs[i]; i++) {
5122 if (ldb_attr_cmp(attrs[i], attr) == 0)
5129 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
5130 const char *location, const char *func,
5133 if (reason == NULL) {
5134 reason = win_errstr(werr);
5136 ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
5137 W_ERROR_V(werr), reason, location, func);
5142 map an ldb error code to an approximate NTSTATUS code
5144 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
5148 return NT_STATUS_OK;
5150 case LDB_ERR_PROTOCOL_ERROR:
5151 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
5153 case LDB_ERR_TIME_LIMIT_EXCEEDED:
5154 return NT_STATUS_IO_TIMEOUT;
5156 case LDB_ERR_SIZE_LIMIT_EXCEEDED:
5157 return NT_STATUS_BUFFER_TOO_SMALL;
5159 case LDB_ERR_COMPARE_FALSE:
5160 case LDB_ERR_COMPARE_TRUE:
5161 return NT_STATUS_REVISION_MISMATCH;
5163 case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
5164 return NT_STATUS_NOT_SUPPORTED;
5166 case LDB_ERR_STRONG_AUTH_REQUIRED:
5167 case LDB_ERR_CONFIDENTIALITY_REQUIRED:
5168 case LDB_ERR_SASL_BIND_IN_PROGRESS:
5169 case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
5170 case LDB_ERR_INVALID_CREDENTIALS:
5171 case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
5172 case LDB_ERR_UNWILLING_TO_PERFORM:
5173 return NT_STATUS_ACCESS_DENIED;
5175 case LDB_ERR_NO_SUCH_OBJECT:
5176 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
5178 case LDB_ERR_REFERRAL:
5179 case LDB_ERR_NO_SUCH_ATTRIBUTE:
5180 return NT_STATUS_NOT_FOUND;
5182 case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
5183 return NT_STATUS_NOT_SUPPORTED;
5185 case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
5186 return NT_STATUS_BUFFER_TOO_SMALL;
5188 case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
5189 case LDB_ERR_INAPPROPRIATE_MATCHING:
5190 case LDB_ERR_CONSTRAINT_VIOLATION:
5191 case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
5192 case LDB_ERR_INVALID_DN_SYNTAX:
5193 case LDB_ERR_NAMING_VIOLATION:
5194 case LDB_ERR_OBJECT_CLASS_VIOLATION:
5195 case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
5196 case LDB_ERR_NOT_ALLOWED_ON_RDN:
5197 return NT_STATUS_INVALID_PARAMETER;
5199 case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
5200 case LDB_ERR_ENTRY_ALREADY_EXISTS:
5201 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
5204 return NT_STATUS_NETWORK_BUSY;
5206 case LDB_ERR_ALIAS_PROBLEM:
5207 case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
5208 case LDB_ERR_UNAVAILABLE:
5209 case LDB_ERR_LOOP_DETECT:
5210 case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
5211 case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
5213 case LDB_ERR_OPERATIONS_ERROR:
5216 return NT_STATUS_UNSUCCESSFUL;
5221 create a new naming context that will hold a partial replica
5223 int dsdb_create_partial_replica_NC(struct ldb_context *ldb, struct ldb_dn *dn)
5225 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5226 struct ldb_message *msg;
5229 msg = ldb_msg_new(tmp_ctx);
5231 talloc_free(tmp_ctx);
5232 return ldb_oom(ldb);
5236 ret = ldb_msg_add_string(msg, "objectClass", "top");
5237 if (ret != LDB_SUCCESS) {
5238 talloc_free(tmp_ctx);
5239 return ldb_oom(ldb);
5242 /* [MS-DRSR] implies that we should only add the 'top'
5243 * objectclass, but that would cause lots of problems with our
5244 * objectclass code as top is not structural, so we add
5245 * 'domainDNS' as well to keep things sane. We're expecting
5246 * this new NC to be of objectclass domainDNS after
5247 * replication anyway
5249 ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
5250 if (ret != LDB_SUCCESS) {
5251 talloc_free(tmp_ctx);
5252 return ldb_oom(ldb);
5255 ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
5256 INSTANCE_TYPE_IS_NC_HEAD|
5257 INSTANCE_TYPE_NC_ABOVE|
5258 INSTANCE_TYPE_UNINSTANT);
5259 if (ret != LDB_SUCCESS) {
5260 talloc_free(tmp_ctx);
5261 return ldb_oom(ldb);
5264 ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
5265 if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
5266 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
5267 ldb_dn_get_linearized(dn),
5268 ldb_errstring(ldb), ldb_strerror(ret)));
5269 talloc_free(tmp_ctx);
5273 DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
5275 talloc_free(tmp_ctx);
5280 build a GUID from a string
5282 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
5284 NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
5286 uint32_t time_mid, time_hi_and_version;
5287 uint32_t clock_seq[2];
5292 return NT_STATUS_INVALID_PARAMETER;
5295 status = parse_guid_string(s,
5298 &time_hi_and_version,
5302 if (!NT_STATUS_IS_OK(status)) {
5306 guid->time_low = time_low;
5307 guid->time_mid = time_mid;
5308 guid->time_hi_and_version = time_hi_and_version;
5309 guid->clock_seq[0] = clock_seq[0];
5310 guid->clock_seq[1] = clock_seq[1];
5312 guid->node[i] = node[i];
5315 return NT_STATUS_OK;
5318 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
5320 return talloc_asprintf(mem_ctx,
5321 "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5322 guid->time_low, guid->time_mid,
5323 guid->time_hi_and_version,
5326 guid->node[0], guid->node[1],
5327 guid->node[2], guid->node[3],
5328 guid->node[4], guid->node[5]);
5332 * Return the effective badPwdCount
5334 * This requires that the user_msg have (if present):
5338 * This also requires that the domain_msg have (if present):
5339 * - lockOutObservationWindow
5341 static int dsdb_effective_badPwdCount(const struct ldb_message *user_msg,
5342 int64_t lockOutObservationWindow,
5345 int64_t badPasswordTime;
5346 badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
5348 if (badPasswordTime - lockOutObservationWindow >= now) {
5349 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
5356 * Returns a user's PSO, or NULL if none was found
5358 static struct ldb_result *lookup_user_pso(struct ldb_context *sam_ldb,
5359 TALLOC_CTX *mem_ctx,
5360 const struct ldb_message *user_msg,
5361 const char * const *attrs)
5363 struct ldb_result *res = NULL;
5364 struct ldb_dn *pso_dn = NULL;
5367 /* if the user has a PSO that applies, then use the PSO's setting */
5368 pso_dn = ldb_msg_find_attr_as_dn(sam_ldb, mem_ctx, user_msg,
5369 "msDS-ResultantPSO");
5371 if (pso_dn != NULL) {
5373 ret = dsdb_search_dn(sam_ldb, mem_ctx, &res, pso_dn, attrs, 0);
5374 if (ret != LDB_SUCCESS) {
5377 * log the error. The caller should fallback to using
5378 * the default domain password settings
5380 DBG_ERR("Error retrieving msDS-ResultantPSO %s for %s",
5381 ldb_dn_get_linearized(pso_dn),
5382 ldb_dn_get_linearized(user_msg->dn));
5384 talloc_free(pso_dn);
5390 * Return the effective badPwdCount
5392 * This requires that the user_msg have (if present):
5395 * - msDS-ResultantPSO
5397 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
5398 TALLOC_CTX *mem_ctx,
5399 struct ldb_dn *domain_dn,
5400 const struct ldb_message *user_msg)
5402 struct timeval tv_now = timeval_current();
5403 NTTIME now = timeval_to_nttime(&tv_now);
5404 int64_t lockOutObservationWindow;
5405 struct ldb_result *res = NULL;
5406 const char *attrs[] = { "msDS-LockoutObservationWindow",
5409 res = lookup_user_pso(sam_ldb, mem_ctx, user_msg, attrs);
5412 lockOutObservationWindow =
5413 ldb_msg_find_attr_as_int64(res->msgs[0],
5414 "msDS-LockoutObservationWindow",
5415 DEFAULT_OBSERVATION_WINDOW);
5419 /* no PSO was found, lookup the default domain setting */
5420 lockOutObservationWindow =
5421 samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
5422 "lockOutObservationWindow", NULL);
5425 return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5429 * Returns the lockoutThreshold that applies. If a PSO is specified, then that
5430 * setting is used over the domain defaults
5432 static int64_t get_lockout_threshold(struct ldb_message *domain_msg,
5433 struct ldb_message *pso_msg)
5435 if (pso_msg != NULL) {
5436 return ldb_msg_find_attr_as_int(pso_msg,
5437 "msDS-LockoutThreshold", 0);
5439 return ldb_msg_find_attr_as_int(domain_msg,
5440 "lockoutThreshold", 0);
5445 * Returns the lockOutObservationWindow that applies. If a PSO is specified,
5446 * then that setting is used over the domain defaults
5448 static int64_t get_lockout_observation_window(struct ldb_message *domain_msg,
5449 struct ldb_message *pso_msg)
5451 if (pso_msg != NULL) {
5452 return ldb_msg_find_attr_as_int64(pso_msg,
5453 "msDS-LockoutObservationWindow",
5454 DEFAULT_OBSERVATION_WINDOW);
5456 return ldb_msg_find_attr_as_int64(domain_msg,
5457 "lockOutObservationWindow",
5458 DEFAULT_OBSERVATION_WINDOW);
5463 * Prepare an update to the badPwdCount and associated attributes.
5465 * This requires that the user_msg have (if present):
5470 * This also requires that the domain_msg have (if present):
5472 * - lockoutThreshold
5473 * - lockOutObservationWindow
5475 * This also requires that the pso_msg have (if present):
5476 * - msDS-LockoutThreshold
5477 * - msDS-LockoutObservationWindow
5479 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
5480 struct ldb_context *sam_ctx,
5481 struct ldb_message *user_msg,
5482 struct ldb_message *domain_msg,
5483 struct ldb_message *pso_msg,
5484 struct ldb_message **_mod_msg)
5486 int i, ret, badPwdCount;
5487 int64_t lockoutThreshold, lockOutObservationWindow;
5488 struct dom_sid *sid;
5489 struct timeval tv_now = timeval_current();
5490 NTTIME now = timeval_to_nttime(&tv_now);
5492 uint32_t pwdProperties, rid = 0;
5493 struct ldb_message *mod_msg;
5495 sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
5497 pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
5498 "pwdProperties", -1);
5499 if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
5500 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
5501 if (!NT_STATUS_IS_OK(status)) {
5503 * This can't happen anyway, but always try
5504 * and update the badPwdCount on failure
5512 * Work out if we are doing password lockout on the domain.
5513 * Also, the built in administrator account is exempt:
5514 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
5516 lockoutThreshold = get_lockout_threshold(domain_msg, pso_msg);
5517 if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
5518 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
5519 ldb_dn_get_linearized(user_msg->dn)));
5520 return NT_STATUS_OK;
5523 mod_msg = ldb_msg_new(mem_ctx);
5524 if (mod_msg == NULL) {
5525 return NT_STATUS_NO_MEMORY;
5527 mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
5528 if (mod_msg->dn == NULL) {
5529 TALLOC_FREE(mod_msg);
5530 return NT_STATUS_NO_MEMORY;
5533 lockOutObservationWindow = get_lockout_observation_window(domain_msg,
5536 badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5540 ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
5541 if (ret != LDB_SUCCESS) {
5542 TALLOC_FREE(mod_msg);
5543 return NT_STATUS_NO_MEMORY;
5545 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
5546 if (ret != LDB_SUCCESS) {
5547 TALLOC_FREE(mod_msg);
5548 return NT_STATUS_NO_MEMORY;
5551 if (badPwdCount >= lockoutThreshold) {
5552 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
5553 if (ret != LDB_SUCCESS) {
5554 TALLOC_FREE(mod_msg);
5555 return NT_STATUS_NO_MEMORY;
5557 DEBUGC( DBGC_AUTH, 1, ("Locked out user %s after %d wrong passwords\n",
5558 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5560 DEBUGC( DBGC_AUTH, 5, ("Updated badPwdCount on %s after %d wrong passwords\n",
5561 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5564 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5565 for (i=0; i< mod_msg->num_elements; i++) {
5566 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5569 *_mod_msg = mod_msg;
5570 return NT_STATUS_OK;
5574 * Sets defaults for a User object
5575 * List of default attributes set:
5576 * accountExpires, badPasswordTime, badPwdCount,
5577 * codePage, countryCode, lastLogoff, lastLogon
5578 * logonCount, pwdLastSet
5580 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
5581 struct ldb_message *usr_obj,
5582 struct ldb_request *req)
5585 const struct attribute_values {
5588 const char *add_value;
5589 const char *mod_value;
5590 const char *control;
5595 .name = "accountExpires",
5596 .add_value = "9223372036854775807",
5600 .name = "badPasswordTime",
5604 .name = "badPwdCount",
5612 .name = "countryCode",
5616 .name = "lastLogoff",
5620 .name = "lastLogon",
5624 .name = "logonCount",
5628 .name = "logonHours",
5629 .add_flags = DSDB_FLAG_INTERNAL_FORCE_META_DATA,
5632 .name = "pwdLastSet",
5634 .control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
5637 .name = "adminCount",
5641 .name = "operatorCount",
5646 for (i = 0; i < ARRAY_SIZE(map); i++) {
5648 const char *value = NULL;
5651 if (req != NULL && req->operation == LDB_ADD) {
5652 value = map[i].add_value;
5653 flags = map[i].add_flags;
5655 value = map[i].mod_value;
5656 flags = map[i].mod_flags;
5659 if (value == NULL) {
5660 value = map[i].value;
5663 if (value != NULL) {
5664 flags |= LDB_FLAG_MOD_ADD;
5671 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
5675 if (ret != LDB_SUCCESS) {
5679 if (req != NULL && added && map[i].control != NULL) {
5680 ret = ldb_request_add_control(req,
5683 if (ret != LDB_SUCCESS) {
5693 * Sets 'sAMAccountType on user object based on userAccountControl
5694 * @param ldb Current ldb_context
5695 * @param usr_obj ldb_message representing User object
5696 * @param user_account_control Value for userAccountControl flags
5697 * @param account_type_p Optional pointer to account_type to return
5698 * @return LDB_SUCCESS or LDB_ERR* code on failure
5700 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
5701 uint32_t user_account_control, uint32_t *account_type_p)
5704 uint32_t account_type;
5705 struct ldb_message_element *el;
5707 account_type = ds_uf2atype(user_account_control);
5708 if (account_type == 0) {
5709 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
5710 return LDB_ERR_UNWILLING_TO_PERFORM;
5712 ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5715 if (ret != LDB_SUCCESS) {
5718 el = ldb_msg_find_element(usr_obj, "sAMAccountType");
5719 el->flags = LDB_FLAG_MOD_REPLACE;
5721 if (account_type_p) {
5722 *account_type_p = account_type;
5729 * Determine and set primaryGroupID based on userAccountControl value
5730 * @param ldb Current ldb_context
5731 * @param usr_obj ldb_message representing User object
5732 * @param user_account_control Value for userAccountControl flags
5733 * @param group_rid_p Optional pointer to group RID to return
5734 * @return LDB_SUCCESS or LDB_ERR* code on failure
5736 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
5737 uint32_t user_account_control, uint32_t *group_rid_p)
5741 struct ldb_message_element *el;
5743 rid = ds_uf2prim_group_rid(user_account_control);
5745 ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5746 "primaryGroupID", rid);
5747 if (ret != LDB_SUCCESS) {
5750 el = ldb_msg_find_element(usr_obj, "primaryGroupID");
5751 el->flags = LDB_FLAG_MOD_REPLACE;
5761 * Returns True if the source and target DNs both have the same naming context,
5762 * i.e. they're both in the same partition.
5764 bool dsdb_objects_have_same_nc(struct ldb_context *ldb,
5765 TALLOC_CTX *mem_ctx,
5766 struct ldb_dn *source_dn,
5767 struct ldb_dn *target_dn)
5769 TALLOC_CTX *tmp_ctx;
5770 struct ldb_dn *source_nc;
5771 struct ldb_dn *target_nc;
5773 bool same_nc = true;
5775 tmp_ctx = talloc_new(mem_ctx);
5777 ret = dsdb_find_nc_root(ldb, tmp_ctx, source_dn, &source_nc);
5778 if (ret != LDB_SUCCESS) {
5779 DBG_ERR("Failed to find base DN for source %s\n",
5780 ldb_dn_get_linearized(source_dn));
5781 talloc_free(tmp_ctx);
5785 ret = dsdb_find_nc_root(ldb, tmp_ctx, target_dn, &target_nc);
5786 if (ret != LDB_SUCCESS) {
5787 DBG_ERR("Failed to find base DN for target %s\n",
5788 ldb_dn_get_linearized(target_dn));
5789 talloc_free(tmp_ctx);
5793 same_nc = (ldb_dn_compare(source_nc, target_nc) == 0);
5795 talloc_free(tmp_ctx);
5800 * Context for dsdb_count_domain_callback
5802 struct dsdb_count_domain_context {
5804 * Number of matching records
5808 * sid of the domain that the records must belong to.
5809 * if NULL records can belong to any domain.
5811 struct dom_sid *dom_sid;
5815 * @brief ldb aysnc callback for dsdb_domain_count.
5817 * count the number of records in the database matching an LDAP query,
5818 * optionally filtering for domain membership.
5820 * @param [in,out] req the ldb request being processed
5821 * req->context contains:
5822 * count The number of matching records
5823 * dom_sid The domain sid, if present records must belong
5824 * to the domain to be counted.
5825 *@param [in,out] ares The query result.
5827 * @return an LDB error code
5830 static int dsdb_count_domain_callback(
5831 struct ldb_request *req,
5832 struct ldb_reply *ares)
5836 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
5838 if (ares->error != LDB_SUCCESS) {
5839 int error = ares->error;
5841 return ldb_request_done(req, error);
5844 switch (ares->type) {
5845 case LDB_REPLY_ENTRY:
5847 struct dsdb_count_domain_context *context = NULL;
5850 const struct ldb_val *v;
5852 context = req->context;
5853 if (context->dom_sid == NULL) {
5858 v = ldb_msg_find_ldb_val(ares->message, "objectSid");
5863 ok = sid_parse(v->data, v->length, &sid);
5868 in_domain = dom_sid_in_domain(context->dom_sid, &sid);
5876 case LDB_REPLY_REFERRAL:
5879 case LDB_REPLY_DONE:
5881 return ldb_request_done(req, LDB_SUCCESS);
5890 * @brief Count the number of records matching a query.
5892 * Count the number of entries in the database matching the supplied query,
5893 * optionally filtering only those entries belonging to the supplied domain.
5895 * @param ldb [in] Current ldb context
5896 * @param count [out] Pointer to the count
5897 * @param base [in] The base dn for the quey
5898 * @param dom_sid [in] The domain sid, if non NULL records that are not a member
5899 * of the domain are ignored.
5900 * @param scope [in] Search scope.
5901 * @param exp_fmt [in] format string for the query.
5903 * @return LDB_STATUS code.
5905 int dsdb_domain_count(
5906 struct ldb_context *ldb,
5908 struct ldb_dn *base,
5909 struct dom_sid *dom_sid,
5910 enum ldb_scope scope,
5911 const char *exp_fmt, ...)
5913 TALLOC_CTX *tmp_ctx = NULL;
5914 struct ldb_request *req = NULL;
5915 struct dsdb_count_domain_context *context = NULL;
5916 char *expression = NULL;
5917 const char *object_sid[] = {"objectSid", NULL};
5918 const char *none[] = {NULL};
5923 tmp_ctx = talloc_new(ldb);
5925 context = talloc_zero(tmp_ctx, struct dsdb_count_domain_context);
5926 if (context == NULL) {
5927 return LDB_ERR_OPERATIONS_ERROR;
5929 context->dom_sid = dom_sid;
5932 va_start(ap, exp_fmt);
5933 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
5936 if (expression == NULL) {
5937 TALLOC_FREE(context);
5938 TALLOC_FREE(tmp_ctx);
5939 return LDB_ERR_OPERATIONS_ERROR;
5943 ret = ldb_build_search_req(
5950 (dom_sid == NULL) ? none : object_sid,
5953 dsdb_count_domain_callback,
5955 ldb_req_set_location(req, "dsdb_domain_count");
5957 if (ret != LDB_SUCCESS) goto done;
5959 ret = ldb_request(ldb, req);
5961 if (ret == LDB_SUCCESS) {
5962 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
5963 if (ret == LDB_SUCCESS) {
5964 *count = context->count;
5970 TALLOC_FREE(expression);
5972 TALLOC_FREE(context);
5973 TALLOC_FREE(tmp_ctx);