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/sys_rw_data.h"
50 #include "libcli/util/ntstatus.h"
51 #include "lib/util/smb_strtox.h"
52 #include "auth/auth.h"
58 * This included to allow us to handle DSDB_FLAG_REPLICATED_UPDATE in
59 * dsdb_request_add_controls()
61 #include "dsdb/samdb/ldb_modules/util.h"
63 /* default is 30 minutes: -1e7 * 30 * 60 */
64 #define DEFAULT_OBSERVATION_WINDOW -18000000000
67 search the sam for the specified attributes in a specific domain, filter on
68 objectSid being in domain_sid.
70 int samdb_search_domain(struct ldb_context *sam_ldb,
72 struct ldb_dn *basedn,
73 struct ldb_message ***res,
74 const char * const *attrs,
75 const struct dom_sid *domain_sid,
76 const char *format, ...) _PRINTF_ATTRIBUTE(7,8)
82 count = gendb_search_v(sam_ldb, mem_ctx, basedn,
83 res, attrs, format, ap);
89 struct dom_sid *entry_sid;
91 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
93 if ((entry_sid == NULL) ||
94 (!dom_sid_in_domain(domain_sid, entry_sid))) {
95 /* Delete that entry from the result set */
96 (*res)[i] = (*res)[count-1];
98 talloc_free(entry_sid);
101 talloc_free(entry_sid);
109 search the sam for a single string attribute in exactly 1 record
111 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
113 struct ldb_dn *basedn,
114 const char *attr_name,
115 const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
118 const char *attrs[2] = { NULL, NULL };
119 struct ldb_message **res = NULL;
121 attrs[0] = attr_name;
123 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
125 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
126 attr_name, format, count));
133 return ldb_msg_find_attr_as_string(res[0], attr_name, NULL);
137 search the sam for a single string attribute in exactly 1 record
139 const char *samdb_search_string(struct ldb_context *sam_ldb,
141 struct ldb_dn *basedn,
142 const char *attr_name,
143 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
148 va_start(ap, format);
149 str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
155 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
157 struct ldb_dn *basedn,
158 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
162 struct ldb_message **res = NULL;
165 va_start(ap, format);
166 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
169 if (count != 1) return NULL;
171 ret = talloc_steal(mem_ctx, res[0]->dn);
178 search the sam for a dom_sid attribute in exactly 1 record
180 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
182 struct ldb_dn *basedn,
183 const char *attr_name,
184 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
188 struct ldb_message **res;
189 const char *attrs[2] = { NULL, NULL };
192 attrs[0] = attr_name;
194 va_start(ap, format);
195 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
198 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
199 attr_name, format, count));
205 sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
211 search the sam for a single integer attribute in exactly 1 record
213 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
215 unsigned int default_value,
216 struct ldb_dn *basedn,
217 const char *attr_name,
218 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
222 struct ldb_message **res;
223 const char *attrs[2] = { NULL, NULL };
225 attrs[0] = attr_name;
227 va_start(ap, format);
228 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
232 return default_value;
235 return ldb_msg_find_attr_as_uint(res[0], attr_name, default_value);
239 search the sam for a single signed 64 bit integer attribute in exactly 1 record
241 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
243 int64_t default_value,
244 struct ldb_dn *basedn,
245 const char *attr_name,
246 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
250 struct ldb_message **res;
251 const char *attrs[2] = { NULL, NULL };
253 attrs[0] = attr_name;
255 va_start(ap, format);
256 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
260 return default_value;
263 return ldb_msg_find_attr_as_int64(res[0], attr_name, default_value);
267 search the sam for multipe records each giving a single string attribute
268 return the number of matches, or -1 on error
270 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
272 struct ldb_dn *basedn,
274 const char *attr_name,
275 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
279 const char *attrs[2] = { NULL, NULL };
280 struct ldb_message **res = NULL;
282 attrs[0] = attr_name;
284 va_start(ap, format);
285 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
292 /* make sure its single valued */
293 for (i=0;i<count;i++) {
294 if (res[i]->num_elements != 1) {
295 DEBUG(1,("samdb: search for %s %s not single valued\n",
302 *strs = talloc_array(mem_ctx, const char *, count+1);
308 for (i=0;i<count;i++) {
309 (*strs)[i] = ldb_msg_find_attr_as_string(res[i], attr_name, NULL);
311 (*strs)[count] = NULL;
316 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
317 const char *attr, struct ldb_dn *default_value)
319 struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
321 return default_value;
327 pull a rid from a objectSid in a result set.
329 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
330 const char *attr, uint32_t default_value)
335 sid = samdb_result_dom_sid(mem_ctx, msg, attr);
337 return default_value;
339 rid = sid->sub_auths[sid->num_auths-1];
345 pull a dom_sid structure from a objectSid in a result set.
347 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
351 const struct ldb_val *v;
353 v = ldb_msg_find_ldb_val(msg, attr);
357 sid = talloc(mem_ctx, struct dom_sid);
361 ret = sid_parse(v->data, v->length, sid);
371 * Makes an auth_SidAttr structure from a objectSid in a result set and a
372 * supplied attribute value.
374 * @param [in] mem_ctx Talloc memory context on which to allocate the auth_SidAttr.
375 * @param [in] msg The message from which to take the objectSid.
376 * @param [in] attr The attribute name, usually "objectSid".
377 * @param [in] attrs SE_GROUP_* flags to go with the SID.
378 * @returns A pointer to the auth_SidAttr structure, or NULL on failure.
380 struct auth_SidAttr *samdb_result_dom_sid_attrs(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
381 const char *attr, uint32_t attrs)
384 const struct ldb_val *v;
385 struct auth_SidAttr *sid;
386 v = ldb_msg_find_ldb_val(msg, attr);
390 sid = talloc(mem_ctx, struct auth_SidAttr);
394 ret = sid_parse(v->data, v->length, &sid->sid);
404 pull a dom_sid structure from a objectSid in a result set.
406 int samdb_result_dom_sid_buf(const struct ldb_message *msg,
411 const struct ldb_val *v = NULL;
412 v = ldb_msg_find_ldb_val(msg, attr);
414 return LDB_ERR_NO_SUCH_ATTRIBUTE;
416 ret = sid_parse(v->data, v->length, sid);
418 return LDB_ERR_OPERATIONS_ERROR;
424 pull a guid structure from a objectGUID in a result set.
426 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
428 const struct ldb_val *v;
432 v = ldb_msg_find_ldb_val(msg, attr);
433 if (!v) return GUID_zero();
435 status = GUID_from_ndr_blob(v, &guid);
436 if (!NT_STATUS_IS_OK(status)) {
444 pull a sid prefix from a objectSid in a result set.
445 this is used to find the domain sid for a user
447 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
450 struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
451 if (!sid || sid->num_auths < 1) return NULL;
457 pull a NTTIME in a result set.
459 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
460 NTTIME default_value)
462 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
466 * Windows stores 0 for lastLogoff.
467 * But when a MS DC return the lastLogoff (as Logoff Time)
468 * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
469 * cause windows 2008 and newer version to fail for SMB requests
471 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
473 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
476 ret = 0x7FFFFFFFFFFFFFFFULL;
482 * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
483 * indicate an account doesn't expire.
485 * When Windows initially creates an account, it sets
486 * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF). However,
487 * when changing from an account having a specific expiration date to
488 * that account never expiring, it sets accountExpires = 0.
490 * Consolidate that logic here to allow clearer logic for account expiry in
491 * the rest of the code.
493 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
495 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
499 ret = 0x7FFFFFFFFFFFFFFFULL;
505 construct the allow_password_change field from the PwdLastSet attribute and the
506 domain password settings
508 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb,
510 struct ldb_dn *domain_dn,
511 const struct ldb_message *msg,
514 uint64_t attr_time = ldb_msg_find_attr_as_uint64(msg, attr, 0);
517 if (attr_time == 0) {
521 minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
523 /* yes, this is a -= not a += as minPwdAge is stored as the negative
524 of the number of 100-nano-seconds */
525 attr_time -= minPwdAge;
531 pull a samr_Password structutre from a result set.
533 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
535 struct samr_Password *hash = NULL;
536 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
537 if (val && (val->length >= sizeof(hash->hash))) {
538 hash = talloc(mem_ctx, struct samr_Password);
539 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
545 pull an array of samr_Password structures from a result set.
547 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
548 const char *attr, struct samr_Password **hashes)
550 unsigned int count, i;
551 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
557 count = val->length / 16;
562 *hashes = talloc_array(mem_ctx, struct samr_Password, count);
566 talloc_keep_secret(*hashes);
568 for (i=0;i<count;i++) {
569 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
575 NTSTATUS samdb_result_passwords_from_history(TALLOC_CTX *mem_ctx,
576 struct loadparm_context *lp_ctx,
577 const struct ldb_message *msg,
579 const struct samr_Password **lm_pwd,
580 const struct samr_Password **nt_pwd)
582 struct samr_Password *lmPwdHash, *ntPwdHash;
586 num_nt = samdb_result_hashes(mem_ctx, msg, "ntPwdHistory", &ntPwdHash);
590 *nt_pwd = &ntPwdHash[idx];
594 /* Ensure that if we have turned off LM
595 * authentication, that we never use the LM hash, even
597 if (lpcfg_lanman_auth(lp_ctx)) {
599 num_lm = samdb_result_hashes(mem_ctx, msg, "lmPwdHistory", &lmPwdHash);
603 *lm_pwd = &lmPwdHash[idx];
612 NTSTATUS samdb_result_passwords_no_lockout(TALLOC_CTX *mem_ctx,
613 struct loadparm_context *lp_ctx,
614 const struct ldb_message *msg,
615 struct samr_Password **nt_pwd)
617 struct samr_Password *ntPwdHash;
621 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
624 } else if (num_nt > 1) {
625 return NT_STATUS_INTERNAL_DB_CORRUPTION;
627 *nt_pwd = &ntPwdHash[0];
633 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx,
634 struct loadparm_context *lp_ctx,
635 const struct ldb_message *msg,
636 struct samr_Password **nt_pwd)
640 acct_flags = samdb_result_acct_flags(msg,
641 "msDS-User-Account-Control-Computed");
642 /* Quit if the account was locked out. */
643 if (acct_flags & ACB_AUTOLOCK) {
644 DEBUG(3,("samdb_result_passwords: Account for user %s was locked out.\n",
645 ldb_dn_get_linearized(msg->dn)));
646 return NT_STATUS_ACCOUNT_LOCKED_OUT;
649 return samdb_result_passwords_no_lockout(mem_ctx, lp_ctx, msg,
654 pull a samr_LogonHours structutre from a result set.
656 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
658 struct samr_LogonHours hours;
659 size_t units_per_week = 168;
660 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
665 units_per_week = val->length * 8;
668 hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
672 hours.units_per_week = units_per_week;
673 memset(hours.bits, 0xFF, units_per_week/8);
675 memcpy(hours.bits, val->data, val->length);
682 pull a set of account_flags from a result set.
684 Naturally, this requires that userAccountControl and
685 (if not null) the attributes 'attr' be already
688 uint32_t samdb_result_acct_flags(const struct ldb_message *msg, const char *attr)
690 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
691 uint32_t attr_flags = 0;
692 uint32_t acct_flags = ds_uf2acb(userAccountControl);
694 attr_flags = ldb_msg_find_attr_as_uint(msg, attr, UF_ACCOUNTDISABLE);
695 if (attr_flags == UF_ACCOUNTDISABLE) {
696 DEBUG(0, ("Attribute %s not found, disabling account %s!\n", attr,
697 ldb_dn_get_linearized(msg->dn)));
699 acct_flags |= ds_uf2acb(attr_flags);
705 NTSTATUS samdb_result_parameters(TALLOC_CTX *mem_ctx,
706 struct ldb_message *msg,
708 struct lsa_BinaryString *s)
711 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
719 if ((val->length % 2) != 0) {
721 * If the on-disk data is not even in length, we know
722 * it is corrupt, and can not be safely pushed. We
723 * would either truncate, send either a un-initilaised
724 * byte or send a forced zero byte
726 return NT_STATUS_INTERNAL_DB_CORRUPTION;
729 s->array = talloc_array(mem_ctx, uint16_t, val->length/2);
731 return NT_STATUS_NO_MEMORY;
733 s->length = s->size = val->length;
735 /* The on-disk format is the 'network' format, being UTF16LE (sort of) */
736 for (i = 0; i < s->length / 2; i++) {
737 s->array[i] = SVAL(val->data, i * 2);
743 /* Find an attribute, with a particular value */
745 /* The current callers of this function expect a very specific
746 * behaviour: In particular, objectClass subclass equivalence is not
747 * wanted. This means that we should not lookup the schema for the
748 * comparison function */
749 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
750 const struct ldb_message *msg,
751 const char *name, const char *value)
754 struct ldb_message_element *el = ldb_msg_find_element(msg, name);
760 for (i=0;i<el->num_values;i++) {
761 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
769 static int samdb_find_or_add_attribute_ex(struct ldb_context *ldb,
770 struct ldb_message *msg,
772 const char *set_value,
777 struct ldb_message_element *el;
779 SMB_ASSERT(attr_flags != 0);
781 el = ldb_msg_find_element(msg, name);
790 ret = ldb_msg_add_empty(msg, name,
793 if (ret != LDB_SUCCESS) {
797 if (set_value != NULL) {
798 ret = ldb_msg_add_string(msg, name, set_value);
799 if (ret != LDB_SUCCESS) {
810 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
812 return samdb_find_or_add_attribute_ex(ldb, msg, name, set_value, LDB_FLAG_MOD_ADD, NULL);
816 add a dom_sid element to a message
818 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
819 const char *attr_name, const struct dom_sid *sid)
822 enum ndr_err_code ndr_err;
824 ndr_err = ndr_push_struct_blob(&v, mem_ctx,
826 (ndr_push_flags_fn_t)ndr_push_dom_sid);
827 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
828 return ldb_operr(sam_ldb);
830 return ldb_msg_add_value(msg, attr_name, &v, NULL);
835 add a delete element operation to a message
837 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
838 const char *attr_name)
840 /* we use an empty replace rather than a delete, as it allows for
841 dsdb_replace() to be used everywhere */
842 return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
846 add an add attribute value to a message or enhance an existing attribute
847 which has the same name and the add flag set.
849 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
850 struct ldb_message *msg, const char *attr_name,
853 struct ldb_message_element *el;
860 v = talloc_strdup(mem_ctx, value);
862 return ldb_oom(sam_ldb);
865 val.data = (uint8_t *) v;
866 val.length = strlen(v);
868 if (val.length == 0) {
869 /* allow empty strings as non-existent attributes */
873 for (i = 0; i < msg->num_elements; i++) {
874 el = &msg->elements[i];
875 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
876 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
882 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
884 if (ret != LDB_SUCCESS) {
889 ret = ldb_msg_element_add_value(msg->elements, el, &val);
890 if (ret != LDB_SUCCESS) {
891 return ldb_oom(sam_ldb);
898 add a delete attribute value to a message or enhance an existing attribute
899 which has the same name and the delete flag set.
901 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
902 struct ldb_message *msg, const char *attr_name,
905 struct ldb_message_element *el;
912 v = talloc_strdup(mem_ctx, value);
914 return ldb_oom(sam_ldb);
917 val.data = (uint8_t *) v;
918 val.length = strlen(v);
920 if (val.length == 0) {
921 /* allow empty strings as non-existent attributes */
925 for (i = 0; i < msg->num_elements; i++) {
926 el = &msg->elements[i];
927 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
928 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
934 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
936 if (ret != LDB_SUCCESS) {
941 ret = ldb_msg_element_add_value(msg->elements, el, &val);
942 if (ret != LDB_SUCCESS) {
943 return ldb_oom(sam_ldb);
950 add a int element to a message
952 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
953 const char *attr_name, int v)
955 const char *s = talloc_asprintf(mem_ctx, "%d", v);
957 return ldb_oom(sam_ldb);
959 return ldb_msg_add_string(msg, attr_name, s);
962 int samdb_msg_add_int_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
963 const char *attr_name, int v, int flags)
965 const char *s = talloc_asprintf(mem_ctx, "%d", v);
967 return ldb_oom(sam_ldb);
969 return ldb_msg_add_string_flags(msg, attr_name, s, flags);
973 * Add an unsigned int element to a message
975 * The issue here is that we have not yet first cast to int32_t explicitly,
976 * before we cast to an signed int to printf() into the %d or cast to a
977 * int64_t before we then cast to a long long to printf into a %lld.
979 * There are *no* unsigned integers in Active Directory LDAP, even the RID
980 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
981 * (See the schema, and the syntax definitions in schema_syntax.c).
984 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
985 const char *attr_name, unsigned int v)
987 return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
990 int samdb_msg_add_uint_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
991 const char *attr_name, unsigned int v, int flags)
993 return samdb_msg_add_int_flags(sam_ldb, mem_ctx, msg, attr_name, (int)v, flags);
997 add a (signed) int64_t element to a message
999 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1000 const char *attr_name, int64_t v)
1002 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
1004 return ldb_oom(sam_ldb);
1006 return ldb_msg_add_string(msg, attr_name, s);
1010 * Add an unsigned int64_t (uint64_t) element to a message
1012 * The issue here is that we have not yet first cast to int32_t explicitly,
1013 * before we cast to an signed int to printf() into the %d or cast to a
1014 * int64_t before we then cast to a long long to printf into a %lld.
1016 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1017 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1018 * (See the schema, and the syntax definitions in schema_syntax.c).
1021 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1022 const char *attr_name, uint64_t v)
1024 return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
1028 append a int element to a message
1030 int samdb_msg_append_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1031 const char *attr_name, int v, int flags)
1033 const char *s = talloc_asprintf(mem_ctx, "%d", v);
1035 return ldb_oom(sam_ldb);
1037 return ldb_msg_append_string(msg, attr_name, s, flags);
1041 * Append an unsigned int element to a message
1043 * The issue here is that we have not yet first cast to int32_t explicitly,
1044 * before we cast to an signed int to printf() into the %d or cast to a
1045 * int64_t before we then cast to a long long to printf into a %lld.
1047 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1048 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1049 * (See the schema, and the syntax definitions in schema_syntax.c).
1052 int samdb_msg_append_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1053 const char *attr_name, unsigned int v, int flags)
1055 return samdb_msg_append_int(sam_ldb, mem_ctx, msg, attr_name, (int)v, flags);
1059 append a (signed) int64_t element to a message
1061 int samdb_msg_append_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1062 const char *attr_name, int64_t v, int flags)
1064 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
1066 return ldb_oom(sam_ldb);
1068 return ldb_msg_append_string(msg, attr_name, s, flags);
1072 * Append an unsigned int64_t (uint64_t) element to a message
1074 * The issue here is that we have not yet first cast to int32_t explicitly,
1075 * before we cast to an signed int to printf() into the %d or cast to a
1076 * int64_t before we then cast to a long long to printf into a %lld.
1078 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1079 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1080 * (See the schema, and the syntax definitions in schema_syntax.c).
1083 int samdb_msg_append_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1084 const char *attr_name, uint64_t v, int flags)
1086 return samdb_msg_append_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v, flags);
1090 add a samr_Password element to a message
1092 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1093 const char *attr_name, const struct samr_Password *hash)
1096 val.data = talloc_memdup(mem_ctx, hash->hash, 16);
1098 return ldb_oom(sam_ldb);
1101 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1105 add a samr_Password array to a message
1107 int samdb_msg_add_hashes(struct ldb_context *ldb,
1108 TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1109 const char *attr_name, struct samr_Password *hashes,
1114 val.data = talloc_array_size(mem_ctx, 16, count);
1115 val.length = count*16;
1117 return ldb_oom(ldb);
1119 for (i=0;i<count;i++) {
1120 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
1122 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1126 add a acct_flags element to a message
1128 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1129 const char *attr_name, uint32_t v)
1131 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1135 add a logon_hours element to a message
1137 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1138 const char *attr_name, struct samr_LogonHours *hours)
1141 val.length = hours->units_per_week / 8;
1142 val.data = hours->bits;
1143 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1147 add a parameters element to a message
1149 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1150 const char *attr_name, struct lsa_BinaryString *parameters)
1154 if ((parameters->length % 2) != 0) {
1155 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
1158 val.data = talloc_array(mem_ctx, uint8_t, parameters->length);
1159 if (val.data == NULL) {
1160 return LDB_ERR_OPERATIONS_ERROR;
1162 val.length = parameters->length;
1163 for (i = 0; i < parameters->length / 2; i++) {
1165 * The on-disk format needs to be in the 'network'
1166 * format, parmeters->array is a uint16_t array of
1167 * length parameters->length / 2
1169 SSVAL(val.data, i * 2, parameters->array[i]);
1171 return ldb_msg_add_steal_value(msg, attr_name, &val);
1175 * Sets an unsigned int element in a message
1177 * The issue here is that we have not yet first cast to int32_t explicitly,
1178 * before we cast to an signed int to printf() into the %d or cast to a
1179 * int64_t before we then cast to a long long to printf into a %lld.
1181 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1182 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1183 * (See the schema, and the syntax definitions in schema_syntax.c).
1186 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1187 struct ldb_message *msg, const char *attr_name,
1190 struct ldb_message_element *el;
1192 el = ldb_msg_find_element(msg, attr_name);
1196 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1200 * Handle ldb_request in transaction
1202 int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1203 struct ldb_request *req)
1207 ret = ldb_transaction_start(sam_ldb);
1208 if (ret != LDB_SUCCESS) {
1212 ret = ldb_request(sam_ldb, req);
1213 if (ret == LDB_SUCCESS) {
1214 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1217 if (ret == LDB_SUCCESS) {
1218 return ldb_transaction_commit(sam_ldb);
1220 ldb_transaction_cancel(sam_ldb);
1226 return a default security descriptor
1228 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1230 struct security_descriptor *sd;
1232 sd = security_descriptor_initialise(mem_ctx);
1237 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1239 struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1240 struct ldb_dn *aggregate_dn;
1245 aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1246 if (!aggregate_dn) {
1249 if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1252 return aggregate_dn;
1255 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1257 struct ldb_dn *new_dn;
1259 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1260 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1261 talloc_free(new_dn);
1267 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1269 struct ldb_dn *new_dn;
1271 new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1272 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1273 talloc_free(new_dn);
1279 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1281 struct ldb_dn *new_dn;
1283 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1284 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1285 talloc_free(new_dn);
1291 struct ldb_dn *samdb_extended_rights_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1293 struct ldb_dn *new_dn;
1295 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1296 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Extended-Rights")) {
1297 talloc_free(new_dn);
1303 work out the domain sid for the current open ldb
1305 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1307 TALLOC_CTX *tmp_ctx;
1308 const struct dom_sid *domain_sid;
1309 const char *attrs[] = {
1313 struct ldb_result *res;
1316 /* see if we have a cached copy */
1317 domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1322 tmp_ctx = talloc_new(ldb);
1323 if (tmp_ctx == NULL) {
1327 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1329 if (ret != LDB_SUCCESS) {
1333 if (res->count != 1) {
1337 domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1338 if (domain_sid == NULL) {
1342 /* cache the domain_sid in the ldb */
1343 if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1347 talloc_steal(ldb, domain_sid);
1348 talloc_free(tmp_ctx);
1353 talloc_free(tmp_ctx);
1358 get domain sid from cache
1360 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1362 return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1365 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1367 TALLOC_CTX *tmp_ctx;
1368 struct dom_sid *dom_sid_new;
1369 struct dom_sid *dom_sid_old;
1371 /* see if we have a cached copy */
1372 dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1373 "cache.domain_sid"), struct dom_sid);
1375 tmp_ctx = talloc_new(ldb);
1376 if (tmp_ctx == NULL) {
1380 dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1385 /* cache the domain_sid in the ldb */
1386 if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1390 talloc_steal(ldb, dom_sid_new);
1391 talloc_free(tmp_ctx);
1392 talloc_free(dom_sid_old);
1397 DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1398 talloc_free(tmp_ctx);
1403 work out the domain guid for the current open ldb
1405 const struct GUID *samdb_domain_guid(struct ldb_context *ldb)
1407 TALLOC_CTX *tmp_ctx = NULL;
1408 struct GUID *domain_guid = NULL;
1409 const char *attrs[] = {
1413 struct ldb_result *res = NULL;
1416 /* see if we have a cached copy */
1417 domain_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.domain_guid");
1422 tmp_ctx = talloc_new(ldb);
1423 if (tmp_ctx == NULL) {
1427 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectGUID=*");
1428 if (ret != LDB_SUCCESS) {
1432 if (res->count != 1) {
1436 domain_guid = talloc(tmp_ctx, struct GUID);
1437 if (domain_guid == NULL) {
1440 *domain_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1442 /* cache the domain_sid in the ldb */
1443 if (ldb_set_opaque(ldb, "cache.domain_guid", domain_guid) != LDB_SUCCESS) {
1447 talloc_steal(ldb, domain_guid);
1448 talloc_free(tmp_ctx);
1453 talloc_free(tmp_ctx);
1457 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1459 TALLOC_CTX *tmp_ctx;
1460 struct ldb_dn *ntds_settings_dn_new;
1461 struct ldb_dn *ntds_settings_dn_old;
1463 /* see if we have a forced copy from provision */
1464 ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb,
1465 "forced.ntds_settings_dn"), struct ldb_dn);
1467 tmp_ctx = talloc_new(ldb);
1468 if (tmp_ctx == NULL) {
1472 ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1473 if (!ntds_settings_dn_new) {
1477 /* set the DN in the ldb to avoid lookups during provision */
1478 if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1482 talloc_steal(ldb, ntds_settings_dn_new);
1483 talloc_free(tmp_ctx);
1484 talloc_free(ntds_settings_dn_old);
1489 DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1490 talloc_free(tmp_ctx);
1495 work out the ntds settings dn for the current open ldb
1497 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1499 TALLOC_CTX *tmp_ctx;
1500 const char *root_attrs[] = { "dsServiceName", NULL };
1502 struct ldb_result *root_res;
1503 struct ldb_dn *settings_dn;
1505 /* see if we have a cached copy */
1506 settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1508 return ldb_dn_copy(mem_ctx, settings_dn);
1511 tmp_ctx = talloc_new(mem_ctx);
1512 if (tmp_ctx == NULL) {
1516 ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1517 if (ret != LDB_SUCCESS) {
1518 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1519 ldb_errstring(ldb)));
1523 if (root_res->count != 1) {
1527 settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1529 /* note that we do not cache the DN here, as that would mean
1530 * we could not handle server renames at runtime. Only
1531 * provision sets up forced.ntds_settings_dn */
1533 talloc_steal(mem_ctx, settings_dn);
1534 talloc_free(tmp_ctx);
1539 DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1540 talloc_free(tmp_ctx);
1545 work out the ntds settings invocationID/objectGUID for the current open ldb
1547 static const struct GUID *samdb_ntds_GUID(struct ldb_context *ldb,
1548 const char *attribute,
1549 const char *cache_name)
1551 TALLOC_CTX *tmp_ctx;
1552 const char *attrs[] = { attribute, NULL };
1554 struct ldb_result *res;
1555 struct GUID *ntds_guid;
1556 struct ldb_dn *ntds_settings_dn = NULL;
1557 const char *errstr = NULL;
1559 /* see if we have a cached copy */
1560 ntds_guid = (struct GUID *)ldb_get_opaque(ldb, cache_name);
1561 if (ntds_guid != NULL) {
1565 tmp_ctx = talloc_new(ldb);
1566 if (tmp_ctx == NULL) {
1570 ntds_settings_dn = samdb_ntds_settings_dn(ldb, tmp_ctx);
1571 if (ntds_settings_dn == NULL) {
1572 errstr = "samdb_ntds_settings_dn() returned NULL";
1576 ret = ldb_search(ldb, tmp_ctx, &res, ntds_settings_dn,
1577 LDB_SCOPE_BASE, attrs, NULL);
1579 errstr = ldb_errstring(ldb);
1583 if (res->count != 1) {
1584 errstr = "incorrect number of results from base search";
1588 ntds_guid = talloc(tmp_ctx, struct GUID);
1589 if (ntds_guid == NULL) {
1593 *ntds_guid = samdb_result_guid(res->msgs[0], attribute);
1595 if (GUID_all_zero(ntds_guid)) {
1596 if (ldb_msg_find_ldb_val(res->msgs[0], attribute)) {
1597 errstr = "failed to find the GUID attribute";
1599 errstr = "failed to parse the GUID";
1604 /* cache the domain_sid in the ldb */
1605 if (ldb_set_opaque(ldb, cache_name, ntds_guid) != LDB_SUCCESS) {
1606 errstr = "ldb_set_opaque() failed";
1610 talloc_steal(ldb, ntds_guid);
1611 talloc_free(tmp_ctx);
1616 DBG_WARNING("Failed to find our own NTDS Settings %s in the ldb: %s!\n",
1618 talloc_free(tmp_ctx);
1623 work out the ntds settings objectGUID for the current open ldb
1625 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1627 return samdb_ntds_GUID(ldb, "objectGUID", "cache.ntds_guid");
1631 work out the ntds settings invocationId for the current open ldb
1633 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1635 return samdb_ntds_GUID(ldb, "invocationId", "cache.invocation_id");
1638 static bool samdb_set_ntds_GUID(struct ldb_context *ldb,
1639 const struct GUID *ntds_guid_in,
1640 const char *attribute,
1641 const char *cache_name)
1643 TALLOC_CTX *tmp_ctx;
1644 struct GUID *ntds_guid_new;
1645 struct GUID *ntds_guid_old;
1647 /* see if we have a cached copy */
1648 ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, cache_name);
1650 tmp_ctx = talloc_new(ldb);
1651 if (tmp_ctx == NULL) {
1655 ntds_guid_new = talloc(tmp_ctx, struct GUID);
1656 if (!ntds_guid_new) {
1660 *ntds_guid_new = *ntds_guid_in;
1662 /* cache the domain_sid in the ldb */
1663 if (ldb_set_opaque(ldb, cache_name, ntds_guid_new) != LDB_SUCCESS) {
1667 talloc_steal(ldb, ntds_guid_new);
1668 talloc_free(tmp_ctx);
1669 talloc_free(ntds_guid_old);
1674 DBG_WARNING("Failed to set our own cached %s in the ldb!\n",
1676 talloc_free(tmp_ctx);
1680 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1682 return samdb_set_ntds_GUID(ldb,
1688 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1690 return samdb_set_ntds_GUID(ldb,
1693 "cache.invocation_id");
1697 work out the server dn for the current open ldb
1699 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1701 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1706 dn = ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb, tmp_ctx));
1707 talloc_free(tmp_ctx);
1713 work out the server dn for the current open ldb
1715 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1717 struct ldb_dn *server_dn;
1718 struct ldb_dn *servers_dn;
1719 struct ldb_dn *server_site_dn;
1721 /* TODO: there must be a saner way to do this!! */
1722 server_dn = samdb_server_dn(ldb, mem_ctx);
1723 if (!server_dn) return NULL;
1725 servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1726 talloc_free(server_dn);
1727 if (!servers_dn) return NULL;
1729 server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1730 talloc_free(servers_dn);
1732 return server_site_dn;
1736 find the site name from a computers DN record
1738 int samdb_find_site_for_computer(struct ldb_context *ldb,
1739 TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1740 const char **site_name)
1744 const struct ldb_val *rdn_val;
1748 ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1749 if (ret != LDB_SUCCESS) {
1753 if (!ldb_dn_remove_child_components(dn, 2)) {
1755 return LDB_ERR_INVALID_DN_SYNTAX;
1758 rdn_val = ldb_dn_get_rdn_val(dn);
1759 if (rdn_val == NULL) {
1760 return LDB_ERR_OPERATIONS_ERROR;
1763 (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1766 return LDB_ERR_OPERATIONS_ERROR;
1772 find the NTDS GUID from a computers DN record
1774 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1775 struct GUID *ntds_guid)
1780 *ntds_guid = GUID_zero();
1782 ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1783 if (ret != LDB_SUCCESS) {
1787 if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1789 return LDB_ERR_OPERATIONS_ERROR;
1792 ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1798 find a 'reference' DN that points at another object
1799 (eg. serverReference, rIDManagerReference etc)
1801 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1802 const char *attribute, struct ldb_dn **dn)
1804 const char *attrs[2];
1805 struct ldb_result *res;
1808 attrs[0] = attribute;
1811 ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY|DSDB_SEARCH_SHOW_EXTENDED_DN, NULL);
1812 if (ret != LDB_SUCCESS) {
1813 ldb_asprintf_errstring(ldb, "Cannot find DN %s to get attribute %s for reference dn: %s",
1814 ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb));
1818 *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1820 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1821 ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1822 ldb_dn_get_linearized(base));
1824 ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1825 ldb_dn_get_linearized(base));
1828 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1836 find if a DN (must have GUID component!) is our ntdsDsa
1838 int samdb_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *dn, bool *is_ntdsa)
1841 struct GUID dn_guid;
1842 const struct GUID *our_ntds_guid;
1843 status = dsdb_get_extended_dn_guid(dn, &dn_guid, "GUID");
1844 if (!NT_STATUS_IS_OK(status)) {
1845 return LDB_ERR_OPERATIONS_ERROR;
1848 our_ntds_guid = samdb_ntds_objectGUID(ldb);
1849 if (!our_ntds_guid) {
1850 DEBUG(0, ("Failed to find our NTDS Settings GUID for comparison with %s - %s\n", ldb_dn_get_linearized(dn), ldb_errstring(ldb)));
1851 return LDB_ERR_OPERATIONS_ERROR;
1854 *is_ntdsa = GUID_equal(&dn_guid, our_ntds_guid);
1859 find a 'reference' DN that points at another object and indicate if it is our ntdsDsa
1861 int samdb_reference_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *base,
1862 const char *attribute, bool *is_ntdsa)
1865 struct ldb_dn *referenced_dn;
1866 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1867 if (tmp_ctx == NULL) {
1868 return LDB_ERR_OPERATIONS_ERROR;
1870 ret = samdb_reference_dn(ldb, tmp_ctx, base, attribute, &referenced_dn);
1871 if (ret != LDB_SUCCESS) {
1872 DEBUG(0, ("Failed to find object %s for attribute %s - %s\n", ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb)));
1876 ret = samdb_dn_is_our_ntdsa(ldb, referenced_dn, is_ntdsa);
1878 talloc_free(tmp_ctx);
1883 find our machine account via the serverReference attribute in the
1886 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1888 struct ldb_dn *server_dn;
1891 server_dn = samdb_server_dn(ldb, mem_ctx);
1892 if (server_dn == NULL) {
1893 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
1896 ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1897 talloc_free(server_dn);
1903 find the RID Manager$ DN via the rIDManagerReference attribute in the
1906 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1908 return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1909 "rIDManagerReference", dn);
1913 find the RID Set DN via the rIDSetReferences attribute in our
1916 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1918 struct ldb_dn *server_ref_dn = NULL;
1921 ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1922 if (ret != LDB_SUCCESS) {
1925 ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1926 talloc_free(server_ref_dn);
1930 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1932 const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1939 return (const char *) val->data;
1943 * Finds the client site by using the client's IP address.
1944 * The "subnet_name" returns the name of the subnet if parameter != NULL
1946 * Has a Windows-based fallback to provide the only site available, or an empty
1947 * string if there are multiple sites.
1949 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1950 const char *ip_address, char **subnet_name,
1953 const char *attrs[] = { "cn", "siteObject", NULL };
1954 struct ldb_dn *sites_container_dn = NULL;
1955 struct ldb_dn *subnets_dn = NULL;
1956 struct ldb_dn *sites_dn = NULL;
1957 struct ldb_result *res = NULL;
1958 const struct ldb_val *val = NULL;
1959 const char *site_name = NULL;
1960 const char *l_subnet_name = NULL;
1961 const char *allow_list[2] = { NULL, NULL };
1962 unsigned int i, count;
1966 * if we don't have a client ip e.g. ncalrpc
1967 * the server site is the client site
1969 if (ip_address == NULL) {
1970 return samdb_server_site_name(ldb, mem_ctx);
1973 sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1974 if (sites_container_dn == NULL) {
1978 subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1979 if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1983 ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1985 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1987 } else if (ret != LDB_SUCCESS) {
1993 for (i = 0; i < count; i++) {
1994 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1997 allow_list[0] = l_subnet_name;
1999 if (allow_access_nolog(NULL, allow_list, "", ip_address)) {
2000 sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
2003 if (sites_dn == NULL) {
2004 /* No reference, maybe another subnet matches */
2008 /* "val" cannot be NULL here since "sites_dn" != NULL */
2009 val = ldb_dn_get_rdn_val(sites_dn);
2010 site_name = talloc_strdup(mem_ctx,
2011 (const char *) val->data);
2013 TALLOC_FREE(sites_dn);
2019 if (site_name == NULL && fallback) {
2020 /* This is the Windows Server fallback rule: when no subnet
2021 * exists and we have only one site available then use it (it
2022 * is for sure the same as our server site). If more sites do
2023 * exist then we don't know which one to use and set the site
2026 ret = dsdb_domain_count(
2032 "(objectClass=site)");
2033 if (ret != LDB_SUCCESS) {
2037 site_name = samdb_server_site_name(ldb, mem_ctx);
2039 site_name = talloc_strdup(mem_ctx, "");
2041 l_subnet_name = NULL;
2044 if (subnet_name != NULL) {
2045 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
2049 TALLOC_FREE(sites_container_dn);
2050 TALLOC_FREE(subnets_dn);
2057 work out if we are the PDC for the domain of the current open ldb
2059 bool samdb_is_pdc(struct ldb_context *ldb)
2064 ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner",
2066 if (ret != LDB_SUCCESS) {
2067 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n",
2068 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
2069 ldb_errstring(ldb)));
2077 work out if we are a Global Catalog server for the domain of the current open ldb
2079 bool samdb_is_gc(struct ldb_context *ldb)
2081 uint32_t options = 0;
2082 if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
2085 return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
2088 /* Find a domain object in the parents of a particular DN. */
2089 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2090 struct ldb_dn **parent_dn, const char **errstring)
2092 TALLOC_CTX *local_ctx;
2093 struct ldb_dn *sdn = dn;
2094 struct ldb_result *res = NULL;
2095 int ret = LDB_SUCCESS;
2096 const char *attrs[] = { NULL };
2098 local_ctx = talloc_new(mem_ctx);
2099 if (local_ctx == NULL) return ldb_oom(ldb);
2101 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
2102 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
2103 "(|(objectClass=domain)(objectClass=builtinDomain))");
2104 if (ret == LDB_SUCCESS) {
2105 if (res->count == 1) {
2113 if (ret != LDB_SUCCESS) {
2114 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
2115 ldb_dn_get_linearized(dn),
2116 ldb_dn_get_linearized(sdn),
2117 ldb_errstring(ldb));
2118 talloc_free(local_ctx);
2121 /* should never be true with 'ret=LDB_SUCCESS', here to satisfy clang */
2123 talloc_free(local_ctx);
2124 return LDB_ERR_OTHER;
2126 if (res->count != 1) {
2127 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
2128 ldb_dn_get_linearized(dn));
2129 DEBUG(0,(__location__ ": %s\n", *errstring));
2130 talloc_free(local_ctx);
2131 return LDB_ERR_CONSTRAINT_VIOLATION;
2134 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2135 talloc_free(local_ctx);
2139 static void pwd_timeout_debug(struct tevent_context *unused1,
2140 struct tevent_timer *unused2,
2141 struct timeval unused3,
2144 DEBUG(0, ("WARNING: check_password_complexity: password script "
2145 "took more than 1 second to run\n"));
2150 * Performs checks on a user password (plaintext UNIX format - attribute
2151 * "password"). The remaining parameters have to be extracted from the domain
2154 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
2156 enum samr_ValidationStatus samdb_check_password(TALLOC_CTX *mem_ctx,
2157 struct loadparm_context *lp_ctx,
2158 const char *account_name,
2159 const char *user_principal_name,
2160 const char *full_name,
2161 const DATA_BLOB *utf8_blob,
2162 const uint32_t pwdProperties,
2163 const uint32_t minPwdLength)
2165 const struct loadparm_substitution *lp_sub =
2166 lpcfg_noop_substitution();
2167 char *password_script = NULL;
2168 const char *utf8_pw = (const char *)utf8_blob->data;
2171 * This looks strange because it is.
2173 * The check for the number of characters in the password
2174 * should clearly not be against the byte length, or else a
2175 * single UTF8 character would count for more than one.
2177 * We have chosen to use the number of 16-bit units that the
2178 * password encodes to as the measure of length. This is not
2179 * the same as the number of codepoints, if a password
2180 * contains a character beyond the Basic Multilingual Plane
2181 * (above 65535) it will count for more than one "character".
2184 size_t password_characters_roughly = strlen_m(utf8_pw);
2186 /* checks if the "minPwdLength" property is satisfied */
2187 if (minPwdLength > password_characters_roughly) {
2188 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2191 /* We might not be asked to check the password complexity */
2192 if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
2193 return SAMR_VALIDATION_STATUS_SUCCESS;
2196 if (password_characters_roughly == 0) {
2197 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2200 password_script = lpcfg_check_password_script(lp_ctx, lp_sub, mem_ctx);
2201 if (password_script != NULL && *password_script != '\0') {
2204 ssize_t nwritten = 0;
2205 struct tevent_context *event_ctx = NULL;
2206 struct tevent_req *req = NULL;
2208 const char * const cmd[4] = {
2214 event_ctx = tevent_context_init(mem_ctx);
2215 if (event_ctx == NULL) {
2216 TALLOC_FREE(password_script);
2217 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2220 /* Gives a warning after 1 second, terminates after 10 */
2221 tevent_add_timer(event_ctx, event_ctx,
2222 tevent_timeval_current_ofs(1, 0),
2223 pwd_timeout_debug, NULL);
2225 check_ret = setenv("SAMBA_CPS_ACCOUNT_NAME", account_name, 1);
2226 if (check_ret != 0) {
2227 TALLOC_FREE(password_script);
2228 TALLOC_FREE(event_ctx);
2229 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2231 if (user_principal_name != NULL) {
2232 check_ret = setenv("SAMBA_CPS_USER_PRINCIPAL_NAME",
2233 user_principal_name, 1);
2235 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2237 if (check_ret != 0) {
2238 TALLOC_FREE(password_script);
2239 TALLOC_FREE(event_ctx);
2240 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2242 if (full_name != NULL) {
2243 check_ret = setenv("SAMBA_CPS_FULL_NAME", full_name, 1);
2245 unsetenv("SAMBA_CPS_FULL_NAME");
2247 if (check_ret != 0) {
2248 TALLOC_FREE(password_script);
2249 TALLOC_FREE(event_ctx);
2250 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2253 req = samba_runcmd_send(event_ctx, event_ctx,
2254 tevent_timeval_current_ofs(10, 0),
2255 100, 100, cmd, NULL);
2256 unsetenv("SAMBA_CPS_ACCOUNT_NAME");
2257 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2258 unsetenv("SAMBA_CPS_FULL_NAME");
2260 TALLOC_FREE(password_script);
2261 TALLOC_FREE(event_ctx);
2262 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2265 cps_stdin = samba_runcmd_export_stdin(req);
2267 nwritten = write_data(
2268 cps_stdin, utf8_blob->data, utf8_blob->length);
2269 if (nwritten == -1) {
2271 TALLOC_FREE(password_script);
2272 TALLOC_FREE(event_ctx);
2273 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2278 if (!tevent_req_poll(req, event_ctx)) {
2279 TALLOC_FREE(password_script);
2280 TALLOC_FREE(event_ctx);
2281 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2284 check_ret = samba_runcmd_recv(req, &error);
2285 TALLOC_FREE(event_ctx);
2287 if (error == ETIMEDOUT) {
2288 DEBUG(0, ("check_password_complexity: check password script took too long!\n"));
2289 TALLOC_FREE(password_script);
2290 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2292 DEBUG(5,("check_password_complexity: check password script (%s) "
2293 "returned [%d]\n", password_script, check_ret));
2295 if (check_ret != 0) {
2296 DEBUG(1,("check_password_complexity: "
2297 "check password script said new password is not good "
2299 TALLOC_FREE(password_script);
2300 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2303 TALLOC_FREE(password_script);
2304 return SAMR_VALIDATION_STATUS_SUCCESS;
2307 TALLOC_FREE(password_script);
2310 * Here are the standard AD password quality rules, which we
2311 * run after the script.
2314 if (!check_password_quality(utf8_pw)) {
2315 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2318 return SAMR_VALIDATION_STATUS_SUCCESS;
2322 * Callback for "samdb_set_password" password change
2324 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2329 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2332 if (ares->error != LDB_SUCCESS) {
2334 req->context = talloc_steal(req,
2335 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2337 return ldb_request_done(req, ret);
2340 if (ares->type != LDB_REPLY_DONE) {
2342 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2345 req->context = talloc_steal(req,
2346 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2348 return ldb_request_done(req, LDB_SUCCESS);
2352 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2353 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2354 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2355 * user change or not. The "rejectReason" gives some more information if the
2358 * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2359 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2360 * NT_STATUS_ACCESS_DENIED, NT_STATUS_ACCOUNT_LOCKED_OUT, NT_STATUS_NO_MEMORY
2362 static NTSTATUS samdb_set_password_internal(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2363 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2364 const DATA_BLOB *new_password,
2365 const struct samr_Password *ntNewHash,
2366 enum dsdb_password_checked old_password_checked,
2367 enum samPwdChangeReason *reject_reason,
2368 struct samr_DomInfo1 **_dominfo,
2369 bool permit_interdomain_trust)
2371 struct ldb_message *msg;
2372 struct ldb_message_element *el;
2373 struct ldb_request *req;
2374 struct dsdb_control_password_change_status *pwd_stat = NULL;
2376 bool hash_values = false;
2377 NTSTATUS status = NT_STATUS_OK;
2379 #define CHECK_RET(x) \
2380 if (x != LDB_SUCCESS) { \
2382 return NT_STATUS_NO_MEMORY; \
2385 msg = ldb_msg_new(mem_ctx);
2387 return NT_STATUS_NO_MEMORY;
2390 if ((new_password != NULL)
2391 && ((ntNewHash == NULL))) {
2392 /* we have the password as plaintext UTF16 */
2393 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2394 new_password, NULL));
2395 el = ldb_msg_find_element(msg, "clearTextPassword");
2396 el->flags = LDB_FLAG_MOD_REPLACE;
2397 } else if ((new_password == NULL)
2398 && ((ntNewHash != NULL))) {
2399 /* we have a password as NT hash */
2400 if (ntNewHash != NULL) {
2401 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2402 "unicodePwd", ntNewHash));
2403 el = ldb_msg_find_element(msg, "unicodePwd");
2404 el->flags = LDB_FLAG_MOD_REPLACE;
2408 /* the password wasn't specified correctly */
2410 return NT_STATUS_INVALID_PARAMETER;
2413 /* build modify request */
2414 ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2415 samdb_set_password_callback, NULL);
2416 if (ret != LDB_SUCCESS) {
2418 return NT_STATUS_NO_MEMORY;
2421 /* A password change operation */
2422 if (old_password_checked == DSDB_PASSWORD_CHECKED_AND_CORRECT) {
2423 struct dsdb_control_password_change *change;
2425 change = talloc(req, struct dsdb_control_password_change);
2426 if (change == NULL) {
2429 return NT_STATUS_NO_MEMORY;
2432 change->old_password_checked = old_password_checked;
2434 ret = ldb_request_add_control(req,
2435 DSDB_CONTROL_PASSWORD_CHANGE_OLD_PW_CHECKED_OID,
2437 if (ret != LDB_SUCCESS) {
2440 return NT_STATUS_NO_MEMORY;
2444 ret = ldb_request_add_control(req,
2445 DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2447 if (ret != LDB_SUCCESS) {
2450 return NT_STATUS_NO_MEMORY;
2453 if (permit_interdomain_trust) {
2454 ret = ldb_request_add_control(req,
2455 DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
2457 if (ret != LDB_SUCCESS) {
2460 return NT_STATUS_NO_MEMORY;
2463 ret = ldb_request_add_control(req,
2464 DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2466 if (ret != LDB_SUCCESS) {
2469 return NT_STATUS_NO_MEMORY;
2472 ret = ldb_request(ldb, req);
2473 if (ret == LDB_SUCCESS) {
2474 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2477 if (req->context != NULL) {
2478 struct ldb_control *control = talloc_get_type_abort(req->context,
2479 struct ldb_control);
2480 pwd_stat = talloc_get_type_abort(control->data,
2481 struct dsdb_control_password_change_status);
2482 talloc_steal(mem_ctx, pwd_stat);
2488 /* Sets the domain info (if requested) */
2489 if (_dominfo != NULL) {
2490 struct samr_DomInfo1 *dominfo;
2492 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2493 if (dominfo == NULL) {
2494 return NT_STATUS_NO_MEMORY;
2497 if (pwd_stat != NULL) {
2498 dominfo->min_password_length = pwd_stat->domain_data.minPwdLength;
2499 dominfo->password_properties = pwd_stat->domain_data.pwdProperties;
2500 dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2501 dominfo->max_password_age = pwd_stat->domain_data.maxPwdAge;
2502 dominfo->min_password_age = pwd_stat->domain_data.minPwdAge;
2505 *_dominfo = dominfo;
2508 if (reject_reason != NULL) {
2509 if (pwd_stat != NULL) {
2510 *reject_reason = pwd_stat->reject_reason;
2512 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2516 if (pwd_stat != NULL) {
2517 talloc_free(pwd_stat);
2520 if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2521 const char *errmsg = ldb_errstring(ldb);
2522 char *endptr = NULL;
2523 WERROR werr = WERR_GEN_FAILURE;
2524 status = NT_STATUS_UNSUCCESSFUL;
2525 if (errmsg != NULL) {
2526 werr = W_ERROR(strtol(errmsg, &endptr, 16));
2527 DBG_WARNING("%s\n", errmsg);
2529 if (endptr != errmsg) {
2530 if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2531 status = NT_STATUS_WRONG_PASSWORD;
2533 if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2534 status = NT_STATUS_PASSWORD_RESTRICTION;
2536 if (W_ERROR_EQUAL(werr, WERR_ACCOUNT_LOCKED_OUT)) {
2537 status = NT_STATUS_ACCOUNT_LOCKED_OUT;
2540 } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2541 /* don't let the caller know if an account doesn't exist */
2542 status = NT_STATUS_WRONG_PASSWORD;
2543 } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2544 status = NT_STATUS_ACCESS_DENIED;
2545 } else if (ret != LDB_SUCCESS) {
2546 DEBUG(1, ("Failed to set password on %s: %s\n",
2547 ldb_dn_get_linearized(user_dn),
2548 ldb_errstring(ldb)));
2549 status = NT_STATUS_UNSUCCESSFUL;
2555 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2556 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2557 const DATA_BLOB *new_password,
2558 const struct samr_Password *ntNewHash,
2559 enum dsdb_password_checked old_password_checked,
2560 enum samPwdChangeReason *reject_reason,
2561 struct samr_DomInfo1 **_dominfo)
2563 return samdb_set_password_internal(ldb, mem_ctx,
2567 old_password_checked,
2568 reject_reason, _dominfo,
2569 false); /* reject trusts */
2573 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2574 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2575 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2576 * user change or not. The "rejectReason" gives some more information if the
2579 * This wrapper function for "samdb_set_password" takes a SID as input rather
2582 * This call encapsulates a new LDB transaction for changing the password;
2583 * therefore the user hasn't to start a new one.
2585 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2586 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2587 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2588 * NT_STATUS_ACCESS_DENIED, NT_STATUS_ACCOUNT_LOCKED_OUT, NT_STATUS_NO_MEMORY
2589 * NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2591 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2592 const struct dom_sid *user_sid,
2593 const uint32_t *new_version, /* optional for trusts */
2594 const DATA_BLOB *new_password,
2595 const struct samr_Password *ntNewHash,
2596 enum dsdb_password_checked old_password_checked,
2597 enum samPwdChangeReason *reject_reason,
2598 struct samr_DomInfo1 **_dominfo)
2600 TALLOC_CTX *frame = talloc_stackframe();
2602 static const char * const attrs[] = {
2603 "userAccountControl",
2607 struct ldb_message *user_msg = NULL;
2611 ret = ldb_transaction_start(ldb);
2612 if (ret != LDB_SUCCESS) {
2613 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2615 return NT_STATUS_TRANSACTION_ABORTED;
2618 ret = dsdb_search_one(ldb, frame, &user_msg, ldb_get_default_basedn(ldb),
2619 LDB_SCOPE_SUBTREE, attrs, 0,
2620 "(&(objectSid=%s)(objectClass=user))",
2621 ldap_encode_ndr_dom_sid(frame, user_sid));
2622 if (ret != LDB_SUCCESS) {
2623 ldb_transaction_cancel(ldb);
2624 DEBUG(3, ("samdb_set_password_sid: SID[%s] not found in samdb %s - %s, "
2625 "returning NO_SUCH_USER\n",
2626 dom_sid_string(frame, user_sid),
2627 ldb_strerror(ret), ldb_errstring(ldb)));
2629 return NT_STATUS_NO_SUCH_USER;
2632 uac = ldb_msg_find_attr_as_uint(user_msg, "userAccountControl", 0);
2633 if (!(uac & UF_ACCOUNT_TYPE_MASK)) {
2634 ldb_transaction_cancel(ldb);
2635 DEBUG(1, ("samdb_set_password_sid: invalid "
2636 "userAccountControl[0x%08X] for SID[%s] DN[%s], "
2637 "returning NO_SUCH_USER\n",
2638 (unsigned)uac, dom_sid_string(frame, user_sid),
2639 ldb_dn_get_linearized(user_msg->dn)));
2641 return NT_STATUS_NO_SUCH_USER;
2644 if (uac & UF_INTERDOMAIN_TRUST_ACCOUNT) {
2645 static const char * const tdo_attrs[] = {
2646 "trustAuthIncoming",
2650 struct ldb_message *tdo_msg = NULL;
2651 const char *account_name = NULL;
2652 uint32_t trust_direction;
2654 const struct ldb_val *old_val = NULL;
2655 struct trustAuthInOutBlob old_blob = {
2658 uint32_t old_version = 0;
2659 struct AuthenticationInformation *old_version_a = NULL;
2660 uint32_t _new_version = 0;
2661 struct trustAuthInOutBlob new_blob = {
2664 struct ldb_val new_val = {
2667 struct timeval tv = timeval_current();
2668 NTTIME now = timeval_to_nttime(&tv);
2669 enum ndr_err_code ndr_err;
2671 if (new_password == NULL && ntNewHash == NULL) {
2672 ldb_transaction_cancel(ldb);
2673 DEBUG(1, ("samdb_set_password_sid: "
2674 "no new password provided "
2675 "sAMAccountName for SID[%s] DN[%s], "
2676 "returning INVALID_PARAMETER\n",
2677 dom_sid_string(frame, user_sid),
2678 ldb_dn_get_linearized(user_msg->dn)));
2680 return NT_STATUS_INVALID_PARAMETER;
2683 if (new_password != NULL && ntNewHash != NULL) {
2684 ldb_transaction_cancel(ldb);
2685 DEBUG(1, ("samdb_set_password_sid: "
2686 "two new passwords provided "
2687 "sAMAccountName for SID[%s] DN[%s], "
2688 "returning INVALID_PARAMETER\n",
2689 dom_sid_string(frame, user_sid),
2690 ldb_dn_get_linearized(user_msg->dn)));
2692 return NT_STATUS_INVALID_PARAMETER;
2695 if (new_password != NULL && (new_password->length % 2)) {
2696 ldb_transaction_cancel(ldb);
2697 DEBUG(2, ("samdb_set_password_sid: "
2698 "invalid utf16 length (%zu) "
2699 "sAMAccountName for SID[%s] DN[%s], "
2700 "returning WRONG_PASSWORD\n",
2701 new_password->length,
2702 dom_sid_string(frame, user_sid),
2703 ldb_dn_get_linearized(user_msg->dn)));
2705 return NT_STATUS_WRONG_PASSWORD;
2708 if (new_password != NULL && new_password->length >= 500) {
2709 ldb_transaction_cancel(ldb);
2710 DEBUG(2, ("samdb_set_password_sid: "
2711 "utf16 password too long (%zu) "
2712 "sAMAccountName for SID[%s] DN[%s], "
2713 "returning WRONG_PASSWORD\n",
2714 new_password->length,
2715 dom_sid_string(frame, user_sid),
2716 ldb_dn_get_linearized(user_msg->dn)));
2718 return NT_STATUS_WRONG_PASSWORD;
2721 account_name = ldb_msg_find_attr_as_string(user_msg,
2722 "sAMAccountName", NULL);
2723 if (account_name == NULL) {
2724 ldb_transaction_cancel(ldb);
2725 DEBUG(1, ("samdb_set_password_sid: missing "
2726 "sAMAccountName for SID[%s] DN[%s], "
2727 "returning NO_SUCH_USER\n",
2728 dom_sid_string(frame, user_sid),
2729 ldb_dn_get_linearized(user_msg->dn)));
2731 return NT_STATUS_NO_SUCH_USER;
2734 nt_status = dsdb_trust_search_tdo_by_type(ldb,
2739 if (!NT_STATUS_IS_OK(nt_status)) {
2740 ldb_transaction_cancel(ldb);
2741 DEBUG(1, ("samdb_set_password_sid: dsdb_trust_search_tdo "
2742 "failed(%s) for sAMAccountName[%s] SID[%s] DN[%s], "
2743 "returning INTERNAL_DB_CORRUPTION\n",
2744 nt_errstr(nt_status), account_name,
2745 dom_sid_string(frame, user_sid),
2746 ldb_dn_get_linearized(user_msg->dn)));
2748 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2751 trust_direction = ldb_msg_find_attr_as_int(tdo_msg,
2752 "trustDirection", 0);
2753 if (!(trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {
2754 ldb_transaction_cancel(ldb);
2755 DEBUG(1, ("samdb_set_password_sid: direction[0x%08X] is "
2756 "not inbound for sAMAccountName[%s] "
2758 "returning INTERNAL_DB_CORRUPTION\n",
2759 (unsigned)trust_direction,
2761 ldb_dn_get_linearized(user_msg->dn),
2762 ldb_dn_get_linearized(tdo_msg->dn)));
2764 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2767 old_val = ldb_msg_find_ldb_val(tdo_msg, "trustAuthIncoming");
2768 if (old_val != NULL) {
2769 ndr_err = ndr_pull_struct_blob(old_val, frame, &old_blob,
2770 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2771 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2772 ldb_transaction_cancel(ldb);
2773 DEBUG(1, ("samdb_set_password_sid: "
2774 "failed(%s) to parse "
2775 "trustAuthOutgoing sAMAccountName[%s] "
2777 "returning INTERNAL_DB_CORRUPTION\n",
2778 ndr_map_error2string(ndr_err),
2780 ldb_dn_get_linearized(user_msg->dn),
2781 ldb_dn_get_linearized(tdo_msg->dn)));
2784 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2788 for (i = old_blob.current.count; i > 0; i--) {
2789 struct AuthenticationInformation *a =
2790 &old_blob.current.array[i - 1];
2792 switch (a->AuthType) {
2793 case TRUST_AUTH_TYPE_NONE:
2794 if (i == old_blob.current.count) {
2796 * remove TRUST_AUTH_TYPE_NONE at the
2799 old_blob.current.count--;
2803 case TRUST_AUTH_TYPE_VERSION:
2805 old_version = a->AuthInfo.version.version;
2808 case TRUST_AUTH_TYPE_CLEAR:
2811 case TRUST_AUTH_TYPE_NT4OWF:
2816 if (new_version == NULL) {
2818 new_version = &_new_version;
2821 if (old_version_a != NULL && *new_version != (old_version + 1)) {
2822 old_version_a->LastUpdateTime = now;
2823 old_version_a->AuthType = TRUST_AUTH_TYPE_NONE;
2826 new_blob.count = MAX(old_blob.current.count, 2);
2827 new_blob.current.array = talloc_zero_array(frame,
2828 struct AuthenticationInformation,
2830 if (new_blob.current.array == NULL) {
2831 ldb_transaction_cancel(ldb);
2833 return NT_STATUS_NO_MEMORY;
2835 new_blob.previous.array = talloc_zero_array(frame,
2836 struct AuthenticationInformation,
2838 if (new_blob.current.array == NULL) {
2839 ldb_transaction_cancel(ldb);
2841 return NT_STATUS_NO_MEMORY;
2844 for (i = 0; i < old_blob.current.count; i++) {
2845 struct AuthenticationInformation *o =
2846 &old_blob.current.array[i];
2847 struct AuthenticationInformation *p =
2848 &new_blob.previous.array[i];
2851 new_blob.previous.count++;
2853 for (; i < new_blob.count; i++) {
2854 struct AuthenticationInformation *pi =
2855 &new_blob.previous.array[i];
2859 * new_blob.previous is still empty so
2860 * we'll do new_blob.previous = new_blob.current
2866 pi->LastUpdateTime = now;
2867 pi->AuthType = TRUST_AUTH_TYPE_NONE;
2868 new_blob.previous.count++;
2871 for (i = 0; i < new_blob.count; i++) {
2872 struct AuthenticationInformation *ci =
2873 &new_blob.current.array[i];
2875 ci->LastUpdateTime = now;
2878 if (ntNewHash != NULL) {
2879 ci->AuthType = TRUST_AUTH_TYPE_NT4OWF;
2880 ci->AuthInfo.nt4owf.password = *ntNewHash;
2884 ci->AuthType = TRUST_AUTH_TYPE_CLEAR;
2885 ci->AuthInfo.clear.size = new_password->length;
2886 ci->AuthInfo.clear.password = new_password->data;
2889 ci->AuthType = TRUST_AUTH_TYPE_VERSION;
2890 ci->AuthInfo.version.version = *new_version;
2893 ci->AuthType = TRUST_AUTH_TYPE_NONE;
2897 new_blob.current.count++;
2900 if (new_blob.previous.count == 0) {
2901 TALLOC_FREE(new_blob.previous.array);
2902 new_blob.previous = new_blob.current;
2905 ndr_err = ndr_push_struct_blob(&new_val, frame, &new_blob,
2906 (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2907 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2908 ldb_transaction_cancel(ldb);
2909 DEBUG(1, ("samdb_set_password_sid: "
2910 "failed(%s) to generate "
2911 "trustAuthOutgoing sAMAccountName[%s] "
2913 "returning UNSUCCESSFUL\n",
2914 ndr_map_error2string(ndr_err),
2916 ldb_dn_get_linearized(user_msg->dn),
2917 ldb_dn_get_linearized(tdo_msg->dn)));
2919 return NT_STATUS_UNSUCCESSFUL;
2922 tdo_msg->num_elements = 0;
2923 TALLOC_FREE(tdo_msg->elements);
2925 ret = ldb_msg_append_value(tdo_msg, "trustAuthIncoming",
2926 &new_val, LDB_FLAG_MOD_REPLACE);
2927 if (ret != LDB_SUCCESS) {
2928 ldb_transaction_cancel(ldb);
2930 return NT_STATUS_NO_MEMORY;
2933 ret = ldb_modify(ldb, tdo_msg);
2934 if (ret != LDB_SUCCESS) {
2935 nt_status = dsdb_ldb_err_to_ntstatus(ret);
2936 ldb_transaction_cancel(ldb);
2937 DEBUG(1, ("samdb_set_password_sid: "
2938 "failed to replace "
2939 "trustAuthOutgoing sAMAccountName[%s] "
2943 ldb_dn_get_linearized(user_msg->dn),
2944 ldb_dn_get_linearized(tdo_msg->dn),
2945 nt_errstr(nt_status), ldb_errstring(ldb)));
2951 nt_status = samdb_set_password_internal(ldb, mem_ctx,
2955 old_password_checked,
2956 reject_reason, _dominfo,
2957 true); /* permit trusts */
2958 if (!NT_STATUS_IS_OK(nt_status)) {
2959 ldb_transaction_cancel(ldb);
2964 ret = ldb_transaction_commit(ldb);
2965 if (ret != LDB_SUCCESS) {
2966 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2967 ldb_dn_get_linearized(user_msg->dn),
2968 ldb_errstring(ldb)));
2970 return NT_STATUS_TRANSACTION_ABORTED;
2974 return NT_STATUS_OK;
2978 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
2979 struct dom_sid *sid, struct ldb_dn **ret_dn)
2981 struct ldb_message *msg;
2982 struct ldb_dn *basedn = NULL;
2986 sidstr = dom_sid_string(mem_ctx, sid);
2987 NT_STATUS_HAVE_NO_MEMORY(sidstr);
2989 /* We might have to create a ForeignSecurityPrincipal, even if this user
2990 * is in our own domain */
2992 msg = ldb_msg_new(sidstr);
2994 talloc_free(sidstr);
2995 return NT_STATUS_NO_MEMORY;
2998 ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2999 ldb_get_default_basedn(sam_ctx),
3000 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
3002 if (ret != LDB_SUCCESS) {
3003 DEBUG(0, ("Failed to find DN for "
3004 "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
3005 talloc_free(sidstr);
3006 return NT_STATUS_INTERNAL_DB_CORRUPTION;
3009 /* add core elements to the ldb_message for the alias */
3011 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
3012 talloc_free(sidstr);
3013 return NT_STATUS_NO_MEMORY;
3016 ret = ldb_msg_add_string(msg, "objectClass",
3017 "foreignSecurityPrincipal");
3018 if (ret != LDB_SUCCESS) {
3019 talloc_free(sidstr);
3020 return NT_STATUS_NO_MEMORY;
3023 /* create the alias */
3024 ret = ldb_add(sam_ctx, msg);
3025 if (ret != LDB_SUCCESS) {
3026 DEBUG(0,("Failed to create foreignSecurityPrincipal "
3028 ldb_dn_get_linearized(msg->dn),
3029 ldb_errstring(sam_ctx)));
3030 talloc_free(sidstr);
3031 return NT_STATUS_INTERNAL_DB_CORRUPTION;
3034 *ret_dn = talloc_steal(mem_ctx, msg->dn);
3035 talloc_free(sidstr);
3037 return NT_STATUS_OK;
3042 Find the DN of a domain, assuming it to be a dotted.dns name
3045 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
3048 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3049 const char *binary_encoded;
3050 const char * const *split_realm;
3057 split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
3059 talloc_free(tmp_ctx);
3062 dn = ldb_dn_new(mem_ctx, ldb, NULL);
3063 for (i=0; split_realm[i]; i++) {
3064 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
3065 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
3066 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
3067 binary_encoded, ldb_dn_get_linearized(dn)));
3068 talloc_free(tmp_ctx);
3072 if (!ldb_dn_validate(dn)) {
3073 DEBUG(2, ("Failed to validated DN %s\n",
3074 ldb_dn_get_linearized(dn)));
3075 talloc_free(tmp_ctx);
3078 talloc_free(tmp_ctx);
3084 Find the DNS equivalent of a DN, in dotted DNS form
3086 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
3088 int i, num_components = ldb_dn_get_comp_num(dn);
3089 char *dns_name = talloc_strdup(mem_ctx, "");
3090 if (dns_name == NULL) {
3094 for (i=0; i<num_components; i++) {
3095 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
3098 talloc_free(dns_name);
3101 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
3102 (int)v->length, (int)v->length, (char *)v->data);
3104 talloc_free(dns_name);
3110 /* remove the last '.' */
3111 if (dns_name[0] != 0) {
3112 dns_name[strlen(dns_name)-1] = 0;
3119 Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
3120 name is based on the forest DNS name
3122 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
3123 TALLOC_CTX *mem_ctx,
3124 const struct GUID *ntds_guid)
3126 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3127 const char *guid_str;
3128 struct ldb_dn *forest_dn;
3129 const char *dnsforest;
3132 guid_str = GUID_string(tmp_ctx, ntds_guid);
3133 if (guid_str == NULL) {
3134 talloc_free(tmp_ctx);
3137 forest_dn = ldb_get_root_basedn(samdb);
3138 if (forest_dn == NULL) {
3139 talloc_free(tmp_ctx);
3142 dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
3143 if (dnsforest == NULL) {
3144 talloc_free(tmp_ctx);
3147 ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
3148 talloc_free(tmp_ctx);
3154 Find the DN of a domain, be it the netbios or DNS name
3156 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
3157 const char *domain_name)
3159 const char * const domain_ref_attrs[] = {
3162 const char * const domain_ref2_attrs[] = {
3165 struct ldb_result *res_domain_ref;
3166 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
3167 /* find the domain's DN */
3168 int ret_domain = ldb_search(ldb, mem_ctx,
3170 samdb_partitions_dn(ldb, mem_ctx),
3173 "(&(nETBIOSName=%s)(objectclass=crossRef))",
3175 if (ret_domain != LDB_SUCCESS) {
3179 if (res_domain_ref->count == 0) {
3180 ret_domain = ldb_search(ldb, mem_ctx,
3182 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
3185 "(objectclass=domain)");
3186 if (ret_domain != LDB_SUCCESS) {
3190 if (res_domain_ref->count == 1) {
3191 return res_domain_ref->msgs[0]->dn;
3196 if (res_domain_ref->count > 1) {
3197 DEBUG(0,("Found %d records matching domain [%s]\n",
3198 ret_domain, domain_name));
3202 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
3208 use a GUID to find a DN
3210 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
3211 TALLOC_CTX *mem_ctx,
3212 const struct GUID *guid,
3213 uint32_t dsdb_flags,
3217 struct ldb_result *res;
3218 const char *attrs[] = { NULL };
3219 struct GUID_txt_buf buf;
3220 char *guid_str = GUID_buf_string(guid, &buf);
3222 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3223 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3224 DSDB_SEARCH_SHOW_EXTENDED_DN |
3225 DSDB_SEARCH_ONE_ONLY | dsdb_flags,
3226 "objectGUID=%s", guid_str);
3227 if (ret != LDB_SUCCESS) {
3231 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3238 use a DN to find a GUID with a given attribute name
3240 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
3241 struct ldb_dn *dn, const char *attribute,
3245 struct ldb_result *res = NULL;
3246 const char *attrs[2];
3247 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3249 attrs[0] = attribute;
3252 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3253 DSDB_SEARCH_SHOW_DELETED |
3254 DSDB_SEARCH_SHOW_RECYCLED);
3255 if (ret != LDB_SUCCESS) {
3256 talloc_free(tmp_ctx);
3261 talloc_free(tmp_ctx);
3262 return LDB_ERR_OTHER;
3264 if (res->count < 1) {
3265 talloc_free(tmp_ctx);
3266 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3268 *guid = samdb_result_guid(res->msgs[0], attribute);
3269 talloc_free(tmp_ctx);
3274 use a DN to find a GUID
3276 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
3277 struct ldb_dn *dn, struct GUID *guid)
3279 return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
3285 adds the given GUID to the given ldb_message. This value is added
3286 for the given attr_name (may be either "objectGUID" or "parentGUID").
3287 This function is used in processing 'add' requests.
3289 int dsdb_msg_add_guid(struct ldb_message *msg,
3291 const char *attr_name)
3296 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
3298 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
3299 if (!NT_STATUS_IS_OK(status)) {
3300 ret = LDB_ERR_OPERATIONS_ERROR;
3304 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
3305 if (ret != LDB_SUCCESS) {
3306 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
3314 talloc_free(tmp_ctx);
3321 use a DN to find a SID
3323 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
3324 struct ldb_dn *dn, struct dom_sid *sid)
3327 struct ldb_result *res = NULL;
3328 const char *attrs[] = { "objectSid", NULL };
3329 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3334 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3335 DSDB_SEARCH_SHOW_DELETED |
3336 DSDB_SEARCH_SHOW_RECYCLED);
3337 if (ret != LDB_SUCCESS) {
3338 talloc_free(tmp_ctx);
3342 talloc_free(tmp_ctx);
3343 return LDB_ERR_OTHER;
3345 if (res->count < 1) {
3346 talloc_free(tmp_ctx);
3347 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3349 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
3351 talloc_free(tmp_ctx);
3352 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3355 talloc_free(tmp_ctx);
3360 use a SID to find a DN
3362 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
3363 TALLOC_CTX *mem_ctx,
3364 struct dom_sid *sid, struct ldb_dn **dn)
3367 struct ldb_result *res;
3368 const char *attrs[] = { NULL };
3369 char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
3372 return ldb_operr(ldb);
3375 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3376 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3377 DSDB_SEARCH_SHOW_EXTENDED_DN |
3378 DSDB_SEARCH_ONE_ONLY,
3379 "objectSid=%s", sid_str);
3380 talloc_free(sid_str);
3381 if (ret != LDB_SUCCESS) {
3385 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3392 load a repsFromTo blob list for a given partition GUID
3393 attr must be "repsFrom" or "repsTo"
3395 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3396 const char *attr, struct repsFromToBlob **r, uint32_t *count)
3398 const char *attrs[] = { attr, NULL };
3399 struct ldb_result *res = NULL;
3400 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3402 struct ldb_message_element *el;
3408 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
3409 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3410 /* partition hasn't been replicated yet */
3413 if (ret != LDB_SUCCESS) {
3414 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
3415 talloc_free(tmp_ctx);
3416 return WERR_DS_DRA_INTERNAL_ERROR;
3421 talloc_free(tmp_ctx);
3422 return WERR_DS_DRA_INTERNAL_ERROR;
3424 el = ldb_msg_find_element(res->msgs[0], attr);
3426 /* it's OK to be empty */
3427 talloc_free(tmp_ctx);
3431 *count = el->num_values;
3432 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
3434 talloc_free(tmp_ctx);
3435 return WERR_DS_DRA_INTERNAL_ERROR;
3438 for (i=0; i<(*count); i++) {
3439 enum ndr_err_code ndr_err;
3440 ndr_err = ndr_pull_struct_blob(&el->values[i],
3443 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3444 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3445 talloc_free(tmp_ctx);
3446 return WERR_DS_DRA_INTERNAL_ERROR;
3450 talloc_free(tmp_ctx);
3456 save the repsFromTo blob list for a given partition GUID
3457 attr must be "repsFrom" or "repsTo"
3459 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3460 const char *attr, struct repsFromToBlob *r, uint32_t count)
3462 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3463 struct ldb_message *msg;
3464 struct ldb_message_element *el;
3467 msg = ldb_msg_new(tmp_ctx);
3469 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
3473 el->values = talloc_array(msg, struct ldb_val, count);
3478 for (i=0; i<count; i++) {
3480 enum ndr_err_code ndr_err;
3482 ndr_err = ndr_push_struct_blob(&v, tmp_ctx,
3484 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3485 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3493 if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
3494 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
3498 talloc_free(tmp_ctx);
3503 talloc_free(tmp_ctx);
3504 return WERR_DS_DRA_INTERNAL_ERROR;
3509 load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
3510 object for a partition
3512 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
3513 uint64_t *uSN, uint64_t *urgent_uSN)
3515 struct ldb_request *req;
3517 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3518 struct dsdb_control_current_partition *p_ctrl;
3519 struct ldb_result *res;
3521 res = talloc_zero(tmp_ctx, struct ldb_result);
3523 talloc_free(tmp_ctx);
3524 return ldb_oom(ldb);
3527 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3528 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
3532 res, ldb_search_default_callback,
3534 if (ret != LDB_SUCCESS) {
3535 talloc_free(tmp_ctx);
3539 p_ctrl = talloc(req, struct dsdb_control_current_partition);
3540 if (p_ctrl == NULL) {
3541 talloc_free(tmp_ctx);
3542 return ldb_oom(ldb);
3544 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
3547 ret = ldb_request_add_control(req,
3548 DSDB_CONTROL_CURRENT_PARTITION_OID,
3550 if (ret != LDB_SUCCESS) {
3551 talloc_free(tmp_ctx);
3555 /* Run the new request */
3556 ret = ldb_request(ldb, req);
3558 if (ret == LDB_SUCCESS) {
3559 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3562 if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
3563 /* it hasn't been created yet, which means
3564 an implicit value of zero */
3566 talloc_free(tmp_ctx);
3570 if (ret != LDB_SUCCESS) {
3571 talloc_free(tmp_ctx);
3575 if (res->count < 1) {
3581 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
3583 *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
3587 talloc_free(tmp_ctx);
3592 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
3593 const struct drsuapi_DsReplicaCursor2 *c2)
3595 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3598 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
3599 const struct drsuapi_DsReplicaCursor *c2)
3601 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3605 * Return the NTDS object for a GUID, confirming it is in the
3606 * configuration partition and a nTDSDSA object
3608 int samdb_get_ntds_obj_by_guid(TALLOC_CTX *mem_ctx,
3609 struct ldb_context *sam_ctx,
3610 const struct GUID *objectGUID,
3612 struct ldb_message **msg)
3615 struct ldb_result *res;
3616 struct GUID_txt_buf guid_buf;
3617 char *guid_str = GUID_buf_string(objectGUID, &guid_buf);
3618 struct ldb_dn *config_dn = NULL;
3620 config_dn = ldb_get_config_basedn(sam_ctx);
3621 if (config_dn == NULL) {
3622 return ldb_operr(sam_ctx);
3625 ret = dsdb_search(sam_ctx,
3631 DSDB_SEARCH_ONE_ONLY,
3632 "(&(objectGUID=%s)(objectClass=nTDSDSA))",
3634 if (ret != LDB_SUCCESS) {
3638 *msg = talloc_steal(mem_ctx, res->msgs[0]);
3646 see if a computer identified by its objectGUID is a RODC
3648 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
3650 /* 1) find the DN for this servers NTDSDSA object
3651 2) search for the msDS-isRODC attribute
3652 3) if not present then not a RODC
3653 4) if present and TRUE then is a RODC
3655 const char *attrs[] = { "msDS-isRODC", NULL };
3657 struct ldb_message *msg;
3658 TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
3660 ret = samdb_get_ntds_obj_by_guid(tmp_ctx,
3665 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3667 talloc_free(tmp_ctx);
3671 if (ret != LDB_SUCCESS) {
3672 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
3673 GUID_string(tmp_ctx, objectGUID)));
3675 talloc_free(tmp_ctx);
3679 ret = ldb_msg_find_attr_as_bool(msg, "msDS-isRODC", 0);
3680 *is_rodc = (ret == 1);
3682 talloc_free(tmp_ctx);
3688 see if we are a RODC
3690 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
3692 const struct GUID *objectGUID;
3696 /* see if we have a cached copy */
3697 cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
3703 objectGUID = samdb_ntds_objectGUID(sam_ctx);
3705 return ldb_operr(sam_ctx);
3708 ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
3709 if (ret != LDB_SUCCESS) {
3713 cached = talloc(sam_ctx, bool);
3714 if (cached == NULL) {
3715 return ldb_oom(sam_ctx);
3719 ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
3720 if (ret != LDB_SUCCESS) {
3721 talloc_free(cached);
3722 return ldb_operr(sam_ctx);
3728 int samdb_dns_host_name(struct ldb_context *sam_ctx, const char **host_name)
3730 const char *_host_name = NULL;
3731 const char *attrs[] = { "dnsHostName", NULL };
3732 TALLOC_CTX *tmp_ctx = NULL;
3734 struct ldb_result *res = NULL;
3736 _host_name = (const char *)ldb_get_opaque(sam_ctx, "cache.dns_host_name");
3737 if (_host_name != NULL) {
3738 *host_name = _host_name;
3742 tmp_ctx = talloc_new(sam_ctx);
3744 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, NULL, attrs, 0);
3746 if (res == NULL || res->count != 1 || ret != LDB_SUCCESS) {
3747 DEBUG(0, ("Failed to get rootDSE for dnsHostName: %s",
3748 ldb_errstring(sam_ctx)));
3749 TALLOC_FREE(tmp_ctx);
3753 _host_name = ldb_msg_find_attr_as_string(res->msgs[0],
3756 if (_host_name == NULL) {
3757 DEBUG(0, ("Failed to get dnsHostName from rootDSE"));
3758 TALLOC_FREE(tmp_ctx);
3759 return LDB_ERR_OPERATIONS_ERROR;
3761 ret = ldb_set_opaque(sam_ctx, "cache.dns_host_name",
3762 discard_const_p(char *, _host_name));
3763 if (ret != LDB_SUCCESS) {
3764 TALLOC_FREE(tmp_ctx);
3765 return ldb_operr(sam_ctx);
3768 *host_name = talloc_steal(sam_ctx, _host_name);
3770 TALLOC_FREE(tmp_ctx);
3774 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3776 TALLOC_CTX *tmp_ctx;
3779 tmp_ctx = talloc_new(ldb);
3780 if (tmp_ctx == NULL) {
3784 cached = talloc(tmp_ctx, bool);
3790 if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3794 talloc_steal(ldb, cached);
3795 talloc_free(tmp_ctx);
3799 DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3800 talloc_free(tmp_ctx);
3806 * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3807 * flags are DS_NTDSSETTINGS_OPT_*
3809 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3813 TALLOC_CTX *tmp_ctx;
3814 struct ldb_result *res;
3815 struct ldb_dn *site_dn;
3816 const char *attrs[] = { "options", NULL };
3818 tmp_ctx = talloc_new(ldb_ctx);
3819 if (tmp_ctx == NULL)
3822 /* Retrieve the site dn for the ldb that we
3823 * have open. This is our local site.
3825 site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3826 if (site_dn == NULL)
3829 /* Perform a one level (child) search from the local
3830 * site distinguided name. We're looking for the
3831 * "options" attribute within the nTDSSiteSettings
3834 rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3835 LDB_SCOPE_ONELEVEL, attrs,
3836 "objectClass=nTDSSiteSettings");
3838 if (rc != LDB_SUCCESS || res->count != 1)
3841 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3843 talloc_free(tmp_ctx);
3848 DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3849 talloc_free(tmp_ctx);
3850 return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
3854 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
3856 flags are DS_NTDS_OPTION_*
3858 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3860 TALLOC_CTX *tmp_ctx;
3861 const char *attrs[] = { "options", NULL };
3863 struct ldb_result *res;
3865 tmp_ctx = talloc_new(ldb);
3866 if (tmp_ctx == NULL) {
3870 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3871 if (ret != LDB_SUCCESS) {
3875 if (res->count != 1) {
3879 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3881 talloc_free(tmp_ctx);
3886 DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3887 talloc_free(tmp_ctx);
3888 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3891 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3893 const char *attrs[] = { "objectCategory", NULL };
3895 struct ldb_result *res;
3897 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3898 if (ret != LDB_SUCCESS) {
3902 if (res->count != 1) {
3906 return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3909 DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3914 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3915 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3917 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3919 char **tokens, *ret;
3922 tokens = str_list_make(mem_ctx, cn, " -_");
3923 if (tokens == NULL || tokens[0] == NULL) {
3927 /* "tolower()" and "toupper()" should also work properly on 0x00 */
3928 tokens[0][0] = tolower(tokens[0][0]);
3929 for (i = 1; tokens[i] != NULL; i++)
3930 tokens[i][0] = toupper(tokens[i][0]);
3932 ret = talloc_strdup(mem_ctx, tokens[0]);
3933 for (i = 1; tokens[i] != NULL; i++)
3934 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3936 talloc_free(tokens);
3942 * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3944 int dsdb_functional_level(struct ldb_context *ldb)
3946 int *domainFunctionality =
3947 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3948 if (!domainFunctionality) {
3949 /* this is expected during initial provision */
3950 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3951 return DS_DOMAIN_FUNCTION_2000;
3953 return *domainFunctionality;
3957 * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3959 int dsdb_forest_functional_level(struct ldb_context *ldb)
3961 int *forestFunctionality =
3962 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3963 if (!forestFunctionality) {
3964 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3965 return DS_DOMAIN_FUNCTION_2000;
3967 return *forestFunctionality;
3971 * This detects and returns the DC functional level (DS_DOMAIN_FUNCTION_*)
3973 int dsdb_dc_functional_level(struct ldb_context *ldb)
3975 int *dcFunctionality =
3976 talloc_get_type(ldb_get_opaque(ldb, "domainControllerFunctionality"), int);
3977 if (!dcFunctionality) {
3978 /* this is expected during initial provision */
3979 DEBUG(4,(__location__ ": WARNING: domainControllerFunctionality not setup\n"));
3980 return DS_DOMAIN_FUNCTION_2008_R2;
3982 return *dcFunctionality;
3986 set a GUID in an extended DN structure
3988 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3994 status = GUID_to_ndr_blob(guid, dn, &v);
3995 if (!NT_STATUS_IS_OK(status)) {
3996 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3999 ret = ldb_dn_set_extended_component(dn, component_name, &v);
4005 return a GUID from a extended DN structure
4007 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
4009 const struct ldb_val *v;
4011 v = ldb_dn_get_extended_component(dn, component_name);
4013 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4016 return GUID_from_ndr_blob(v, guid);
4020 return a uint64_t from a extended DN structure
4022 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
4024 const struct ldb_val *v;
4027 v = ldb_dn_get_extended_component(dn, component_name);
4029 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4032 /* Just check we don't allow the caller to fill our stack */
4033 if (v->length >= 64) {
4034 return NT_STATUS_INVALID_PARAMETER;
4036 char s[v->length+1];
4037 memcpy(s, v->data, v->length);
4040 *val = smb_strtoull(s, NULL, 0, &error, SMB_STR_STANDARD);
4042 return NT_STATUS_INVALID_PARAMETER;
4045 return NT_STATUS_OK;
4049 return a NTTIME from a extended DN structure
4051 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
4053 return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
4057 return a uint32_t from a extended DN structure
4059 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
4061 const struct ldb_val *v;
4064 v = ldb_dn_get_extended_component(dn, component_name);
4066 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4069 /* Just check we don't allow the caller to fill our stack */
4070 if (v->length >= 32) {
4071 return NT_STATUS_INVALID_PARAMETER;
4073 char s[v->length + 1];
4074 memcpy(s, v->data, v->length);
4076 *val = smb_strtoul(s, NULL, 0, &error, SMB_STR_STANDARD);
4078 return NT_STATUS_INVALID_PARAMETER;
4082 return NT_STATUS_OK;
4086 return a dom_sid from a extended DN structure
4088 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
4090 const struct ldb_val *sid_blob;
4091 enum ndr_err_code ndr_err;
4093 sid_blob = ldb_dn_get_extended_component(dn, component_name);
4095 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4098 ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
4099 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
4100 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4101 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
4105 return NT_STATUS_OK;
4110 return RMD_FLAGS directly from a ldb_dn
4111 returns 0 if not found
4113 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
4115 uint32_t rmd_flags = 0;
4116 NTSTATUS status = dsdb_get_extended_dn_uint32(dn, &rmd_flags,
4118 if (NT_STATUS_IS_OK(status)) {
4125 return RMD_FLAGS directly from a ldb_val for a DN
4126 returns 0 if RMD_FLAGS is not found
4128 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
4135 if (val->length < 13) {
4138 p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
4142 flags = smb_strtoul(p+11, &end, 10, &error, SMB_STR_STANDARD);
4143 if (!end || *end != '>' || error != 0) {
4144 /* it must end in a > */
4151 return true if a ldb_val containing a DN in storage form is deleted
4153 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
4155 return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
4159 return true if a ldb_val containing a DN in storage form is
4160 in the upgraded w2k3 linked attribute format
4162 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
4164 return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
4168 return a DN for a wellknown GUID
4170 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
4171 struct ldb_dn *nc_root, const char *wk_guid,
4172 struct ldb_dn **wkguid_dn)
4174 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4175 const char *attrs[] = { NULL };
4178 struct ldb_result *res = NULL;
4180 /* construct the magic WKGUID DN */
4181 dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
4182 wk_guid, ldb_dn_get_linearized(nc_root));
4184 talloc_free(tmp_ctx);
4185 return ldb_operr(samdb);
4188 ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
4189 DSDB_SEARCH_SHOW_DELETED |
4190 DSDB_SEARCH_SHOW_RECYCLED);
4191 if (ret != LDB_SUCCESS) {
4192 talloc_free(tmp_ctx);
4195 /* fix clang warning */
4197 talloc_free(tmp_ctx);
4198 return LDB_ERR_OTHER;
4201 (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
4202 talloc_free(tmp_ctx);
4207 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
4209 return ldb_dn_compare(*dn1, *dn2);
4213 find a NC root given a DN within the NC by reading the rootDSE namingContexts
4215 static int dsdb_find_nc_root_string_based(struct ldb_context *samdb,
4216 TALLOC_CTX *mem_ctx,
4218 struct ldb_dn **nc_root)
4220 const char *root_attrs[] = { "namingContexts", NULL };
4221 TALLOC_CTX *tmp_ctx;
4223 struct ldb_message_element *el;
4224 struct ldb_result *root_res;
4226 struct ldb_dn **nc_dns;
4228 tmp_ctx = talloc_new(samdb);
4229 if (tmp_ctx == NULL) {
4230 return ldb_oom(samdb);
4233 ret = ldb_search(samdb, tmp_ctx, &root_res,
4234 ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
4235 if (ret != LDB_SUCCESS || root_res->count == 0) {
4236 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
4237 talloc_free(tmp_ctx);
4241 el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
4242 if ((el == NULL) || (el->num_values < 3)) {
4243 struct ldb_message *tmp_msg;
4245 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list.\n"));
4247 /* This generates a temporary list of NCs in order to let the
4248 * provisioning work. */
4249 tmp_msg = ldb_msg_new(tmp_ctx);
4250 if (tmp_msg == NULL) {
4251 talloc_free(tmp_ctx);
4252 return ldb_oom(samdb);
4254 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4255 ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
4256 if (ret != LDB_SUCCESS) {
4257 talloc_free(tmp_ctx);
4260 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4261 ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
4262 if (ret != LDB_SUCCESS) {
4263 talloc_free(tmp_ctx);
4266 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4267 ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
4268 if (ret != LDB_SUCCESS) {
4269 talloc_free(tmp_ctx);
4272 el = &tmp_msg->elements[0];
4275 nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
4277 talloc_free(tmp_ctx);
4278 return ldb_oom(samdb);
4281 for (i=0; i<el->num_values; i++) {
4282 nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
4283 if (nc_dns[i] == NULL) {
4284 talloc_free(tmp_ctx);
4285 return ldb_operr(samdb);
4289 TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
4291 for (i=0; i<el->num_values; i++) {
4292 if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
4293 (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
4294 talloc_free(tmp_ctx);
4299 talloc_free(tmp_ctx);
4300 return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4303 struct dsdb_get_partition_and_dn {
4304 TALLOC_CTX *mem_ctx;
4307 struct ldb_dn *partition_dn;
4308 bool want_partition_dn;
4311 static int dsdb_get_partition_and_dn(struct ldb_request *req,
4312 struct ldb_reply *ares)
4315 struct dsdb_get_partition_and_dn *context = req->context;
4316 struct ldb_control *partition_ctrl = NULL;
4317 struct dsdb_control_current_partition *partition = NULL;
4320 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
4322 if (ares->error != LDB_SUCCESS
4323 && ares->error != LDB_ERR_NO_SUCH_OBJECT) {
4324 return ldb_request_done(req, ares->error);
4327 switch (ares->type) {
4328 case LDB_REPLY_ENTRY:
4329 if (context->count != 0) {
4330 return ldb_request_done(req,
4331 LDB_ERR_CONSTRAINT_VIOLATION);
4335 context->dn = talloc_steal(context->mem_ctx,
4339 case LDB_REPLY_REFERRAL:
4341 return ldb_request_done(req, LDB_SUCCESS);
4343 case LDB_REPLY_DONE:
4345 = ldb_reply_get_control(ares,
4346 DSDB_CONTROL_CURRENT_PARTITION_OID);
4347 if (!context->want_partition_dn ||
4348 partition_ctrl == NULL) {
4352 return ldb_request_done(req, ret);
4356 = talloc_get_type_abort(partition_ctrl->data,
4357 struct dsdb_control_current_partition);
4358 context->partition_dn
4359 = ldb_dn_copy(context->mem_ctx, partition->dn);
4360 if (context->partition_dn == NULL) {
4361 return ldb_request_done(req,
4362 LDB_ERR_OPERATIONS_ERROR);
4368 return ldb_request_done(req, ret);
4376 find a NC root given a DN within the NC
4378 int dsdb_normalise_dn_and_find_nc_root(struct ldb_context *samdb,
4379 TALLOC_CTX *mem_ctx,
4381 struct ldb_dn **normalised_dn,
4382 struct ldb_dn **nc_root)
4384 TALLOC_CTX *tmp_ctx;
4386 struct ldb_request *req;
4387 struct ldb_result *res;
4388 struct ldb_dn *search_dn = dn;
4389 static const char * attrs[] = { NULL };
4390 bool has_extended = ldb_dn_has_extended(dn);
4391 bool has_normal_components = ldb_dn_get_comp_num(dn) >= 1;
4392 struct dsdb_get_partition_and_dn context = {
4394 .want_partition_dn = nc_root != NULL
4397 if (!has_extended && !has_normal_components) {
4398 return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT,
4399 "Request for NC root for rootDSE (\"\") deined.");
4402 tmp_ctx = talloc_new(samdb);
4403 if (tmp_ctx == NULL) {
4404 return ldb_oom(samdb);
4407 res = talloc_zero(tmp_ctx, struct ldb_result);
4409 talloc_free(tmp_ctx);
4410 return ldb_oom(samdb);
4413 if (has_extended && has_normal_components) {
4415 search_dn = ldb_dn_copy(tmp_ctx, dn);
4416 if (search_dn == NULL) {
4417 talloc_free(tmp_ctx);
4418 return ldb_oom(samdb);
4420 minimise_ok = ldb_dn_minimise(search_dn);
4422 talloc_free(tmp_ctx);
4423 return ldb_operr(samdb);
4427 ret = ldb_build_search_req(&req, samdb, tmp_ctx,
4434 dsdb_get_partition_and_dn,
4436 if (ret != LDB_SUCCESS) {
4437 talloc_free(tmp_ctx);
4441 ret = ldb_request_add_control(req,
4442 DSDB_CONTROL_CURRENT_PARTITION_OID,
4444 if (ret != LDB_SUCCESS) {
4445 talloc_free(tmp_ctx);
4449 ret = dsdb_request_add_controls(req,
4450 DSDB_SEARCH_SHOW_RECYCLED|
4451 DSDB_SEARCH_SHOW_DELETED|
4452 DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT);
4453 if (ret != LDB_SUCCESS) {
4454 talloc_free(tmp_ctx);
4458 ret = ldb_request(samdb, req);
4459 if (ret == LDB_SUCCESS) {
4460 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4464 * This could be a new DN, not in the DB, which is OK. If we
4465 * don't need the normalised DN, we can continue.
4467 * We may be told the partition it would be in in the search
4468 * reply control, or if not we can do a string-based match.
4471 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
4472 if (normalised_dn != NULL) {
4473 talloc_free(tmp_ctx);
4477 ldb_reset_err_string(samdb);
4478 } else if (ret != LDB_SUCCESS) {
4479 talloc_free(tmp_ctx);
4483 if (normalised_dn != NULL) {
4484 if (context.count != 1) {
4486 ldb_asprintf_errstring(samdb,
4487 "Request for NC root for %s failed to return any results.",
4488 ldb_dn_get_linearized(dn));
4489 return LDB_ERR_NO_SUCH_OBJECT;
4491 *normalised_dn = context.dn;
4495 * If the user did not need to find the nc_root,
4498 if (nc_root == NULL) {
4499 talloc_free(tmp_ctx);
4504 * When we are working locally, both for the case were
4505 * we find the DN, and the case where we fail, we get
4506 * back via controls the partition it was in or should
4507 * have been in, to return to the client
4509 if (context.partition_dn != NULL) {
4510 (*nc_root) = context.partition_dn;
4512 talloc_free(tmp_ctx);
4517 * This is a remote operation, which is a little harder as we
4518 * have a work out the nc_root from the list of NCs. If we did
4519 * at least resolve the DN to a string, get that now, it makes
4520 * the string-based match below possible for a GUID-based
4521 * input over remote LDAP.
4525 } else if (has_extended && !has_normal_components) {
4526 ldb_asprintf_errstring(samdb,
4527 "Cannot determine NC root "
4528 "for a not-found bare extended DN %s.",
4529 ldb_dn_get_extended_linearized(tmp_ctx, dn, 1));
4530 talloc_free(tmp_ctx);
4531 return LDB_ERR_NO_SUCH_OBJECT;
4535 * Either we are working aginast a remote LDAP
4536 * server or the object doesn't exist locally.
4538 * This means any GUID that was present in the DN
4539 * therefore could not be evaluated, so do a
4540 * string-based match instead.
4542 talloc_free(tmp_ctx);
4543 return dsdb_find_nc_root_string_based(samdb,
4550 find a NC root given a DN within the NC
4552 int dsdb_find_nc_root(struct ldb_context *samdb,
4553 TALLOC_CTX *mem_ctx,
4555 struct ldb_dn **nc_root)
4557 return dsdb_normalise_dn_and_find_nc_root(samdb,
4565 find the deleted objects DN for any object, by looking for the NC
4566 root, then looking up the wellknown GUID
4568 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
4569 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
4570 struct ldb_dn **do_dn)
4572 struct ldb_dn *nc_root;
4575 ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
4576 if (ret != LDB_SUCCESS) {
4580 ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
4581 talloc_free(nc_root);
4586 return the tombstoneLifetime, in days
4588 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
4591 dn = ldb_get_config_basedn(ldb);
4593 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4595 dn = ldb_dn_copy(ldb, dn);
4597 return ldb_operr(ldb);
4599 /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
4600 be a wellknown GUID for this */
4601 if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
4603 return ldb_operr(ldb);
4606 *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
4612 compare a ldb_val to a string case insensitively
4614 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
4616 size_t len = strlen(s);
4618 if (len > v->length) return 1;
4619 ret = strncasecmp(s, (const char *)v->data, v->length);
4620 if (ret != 0) return ret;
4621 if (v->length > len && v->data[len] != 0) {
4629 load the UDV for a partition in v2 format
4630 The list is returned sorted, and with our local cursor added
4632 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4633 struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
4635 static const char *attrs[] = { "replUpToDateVector", NULL };
4636 struct ldb_result *r = NULL;
4637 const struct ldb_val *ouv_value;
4640 uint64_t highest_usn = 0;
4641 const struct GUID *our_invocation_id;
4642 static const struct timeval tv1970;
4643 NTTIME nt1970 = timeval_to_nttime(&tv1970);
4645 ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
4646 if (ret != LDB_SUCCESS) {
4649 /* fix clang warning */
4651 return LDB_ERR_OTHER;
4653 ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
4655 enum ndr_err_code ndr_err;
4656 struct replUpToDateVectorBlob ouv;
4658 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
4659 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
4660 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4662 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4664 if (ouv.version != 2) {
4665 /* we always store as version 2, and
4666 * replUpToDateVector is not replicated
4668 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4671 *count = ouv.ctr.ctr2.count;
4672 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
4680 our_invocation_id = samdb_ntds_invocation_id(samdb);
4681 if (!our_invocation_id) {
4682 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
4683 talloc_free(*cursors);
4684 return ldb_operr(samdb);
4687 ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
4688 if (ret != LDB_SUCCESS) {
4689 /* nothing to add - this can happen after a vampire */
4690 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4694 for (i=0; i<*count; i++) {
4695 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
4696 (*cursors)[i].highest_usn = highest_usn;
4697 (*cursors)[i].last_sync_success = nt1970;
4698 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4703 (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
4705 return ldb_oom(samdb);
4708 (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
4709 (*cursors)[*count].highest_usn = highest_usn;
4710 (*cursors)[*count].last_sync_success = nt1970;
4713 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4719 load the UDV for a partition in version 1 format
4720 The list is returned sorted, and with our local cursor added
4722 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4723 struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
4725 struct drsuapi_DsReplicaCursor2 *v2 = NULL;
4729 ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
4730 if (ret != LDB_SUCCESS) {
4740 *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
4741 if (*cursors == NULL) {
4743 return ldb_oom(samdb);
4746 for (i=0; i<*count; i++) {
4747 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
4748 (*cursors)[i].highest_usn = v2[i].highest_usn;
4755 add a set of controls to a ldb_request structure based on a set of
4756 flags. See util.h for a list of available flags
4758 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
4761 if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
4762 struct ldb_search_options_control *options;
4763 /* Using the phantom root control allows us to search all partitions */
4764 options = talloc(req, struct ldb_search_options_control);
4765 if (options == NULL) {
4766 return LDB_ERR_OPERATIONS_ERROR;
4768 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
4770 ret = ldb_request_add_control(req,
4771 LDB_CONTROL_SEARCH_OPTIONS_OID,
4773 if (ret != LDB_SUCCESS) {
4778 if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
4779 ret = ldb_request_add_control(req,
4780 DSDB_CONTROL_NO_GLOBAL_CATALOG,
4782 if (ret != LDB_SUCCESS) {
4787 if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
4788 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
4789 if (ret != LDB_SUCCESS) {
4794 if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
4795 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
4796 if (ret != LDB_SUCCESS) {
4801 if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
4802 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
4803 if (ret != LDB_SUCCESS) {
4808 if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
4809 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
4810 if (!extended_ctrl) {
4811 return LDB_ERR_OPERATIONS_ERROR;
4813 extended_ctrl->type = 1;
4815 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
4816 if (ret != LDB_SUCCESS) {
4821 if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
4822 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
4823 if (ret != LDB_SUCCESS) {
4828 if (dsdb_flags & DSDB_MODIFY_RELAX) {
4829 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
4830 if (ret != LDB_SUCCESS) {
4835 if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
4836 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
4837 if (ret != LDB_SUCCESS) {
4842 if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
4843 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
4844 if (ret != LDB_SUCCESS) {
4849 if (dsdb_flags & DSDB_TREE_DELETE) {
4850 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
4851 if (ret != LDB_SUCCESS) {
4856 if (dsdb_flags & DSDB_PROVISION) {
4857 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
4858 if (ret != LDB_SUCCESS) {
4863 /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
4864 if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
4865 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
4866 if (ret != LDB_SUCCESS) {
4871 if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
4873 * This must not be critical, as it will only be
4874 * handled (and need to be handled) if the other
4875 * attributes in the request bring password_hash into
4878 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
4879 if (ret != LDB_SUCCESS) {
4884 if (dsdb_flags & DSDB_REPLMD_VANISH_LINKS) {
4885 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLMD_VANISH_LINKS, true, NULL);
4886 if (ret != LDB_SUCCESS) {
4891 if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
4892 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
4893 if (ret != LDB_SUCCESS) {
4898 if (dsdb_flags & DSDB_FLAG_REPLICATED_UPDATE) {
4899 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
4900 if (ret != LDB_SUCCESS) {
4905 if (dsdb_flags & DSDB_FLAG_FORCE_ALLOW_VALIDATED_DNS_HOSTNAME_SPN_WRITE) {
4906 ret = ldb_request_add_control(req, DSDB_CONTROL_FORCE_ALLOW_VALIDATED_DNS_HOSTNAME_SPN_WRITE_OID, true, NULL);
4907 if (ret != LDB_SUCCESS) {
4912 if (dsdb_flags & DSDB_MARK_REQ_UNTRUSTED) {
4913 ldb_req_mark_untrusted(req);
4920 returns true if a control with the specified "oid" exists
4922 bool dsdb_request_has_control(struct ldb_request *req, const char *oid)
4924 return (ldb_request_get_control(req, oid) != NULL);
4928 an add with a set of controls
4930 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
4931 uint32_t dsdb_flags)
4933 struct ldb_request *req;
4936 ret = ldb_build_add_req(&req, ldb, ldb,
4940 ldb_op_default_callback,
4943 if (ret != LDB_SUCCESS) return ret;
4945 ret = dsdb_request_add_controls(req, dsdb_flags);
4946 if (ret != LDB_SUCCESS) {
4951 ret = dsdb_autotransaction_request(ldb, req);
4958 a modify with a set of controls
4960 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
4961 uint32_t dsdb_flags)
4963 struct ldb_request *req;
4966 ret = ldb_build_mod_req(&req, ldb, ldb,
4970 ldb_op_default_callback,
4973 if (ret != LDB_SUCCESS) return ret;
4975 ret = dsdb_request_add_controls(req, dsdb_flags);
4976 if (ret != LDB_SUCCESS) {
4981 ret = dsdb_autotransaction_request(ldb, req);
4988 a delete with a set of flags
4990 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
4991 uint32_t dsdb_flags)
4993 struct ldb_request *req;
4996 ret = ldb_build_del_req(&req, ldb, ldb,
5000 ldb_op_default_callback,
5003 if (ret != LDB_SUCCESS) return ret;
5005 ret = dsdb_request_add_controls(req, dsdb_flags);
5006 if (ret != LDB_SUCCESS) {
5011 ret = dsdb_autotransaction_request(ldb, req);
5018 like dsdb_modify() but set all the element flags to
5019 LDB_FLAG_MOD_REPLACE
5021 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
5025 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5026 for (i=0;i<msg->num_elements;i++) {
5027 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5030 return dsdb_modify(ldb, msg, dsdb_flags);
5035 search for attrs on one DN, allowing for dsdb_flags controls
5037 int dsdb_search_dn(struct ldb_context *ldb,
5038 TALLOC_CTX *mem_ctx,
5039 struct ldb_result **_result,
5040 struct ldb_dn *basedn,
5041 const char * const *attrs,
5042 uint32_t dsdb_flags)
5045 struct ldb_request *req;
5046 struct ldb_result *res;
5048 res = talloc_zero(mem_ctx, struct ldb_result);
5050 return ldb_oom(ldb);
5053 ret = ldb_build_search_req(&req, ldb, res,
5060 ldb_search_default_callback,
5062 if (ret != LDB_SUCCESS) {
5067 ret = dsdb_request_add_controls(req, dsdb_flags);
5068 if (ret != LDB_SUCCESS) {
5073 ret = ldb_request(ldb, req);
5074 if (ret == LDB_SUCCESS) {
5075 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
5079 if (ret != LDB_SUCCESS) {
5089 search for attrs on one DN, by the GUID of the DN, allowing for
5092 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
5093 TALLOC_CTX *mem_ctx,
5094 struct ldb_result **_result,
5095 const struct GUID *guid,
5096 const char * const *attrs,
5097 uint32_t dsdb_flags)
5099 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5103 dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
5105 talloc_free(tmp_ctx);
5106 return ldb_oom(ldb);
5109 ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
5110 talloc_free(tmp_ctx);
5115 general search with dsdb_flags for controls
5117 int dsdb_search(struct ldb_context *ldb,
5118 TALLOC_CTX *mem_ctx,
5119 struct ldb_result **_result,
5120 struct ldb_dn *basedn,
5121 enum ldb_scope scope,
5122 const char * const *attrs,
5123 uint32_t dsdb_flags,
5124 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
5127 struct ldb_request *req;
5128 struct ldb_result *res;
5130 char *expression = NULL;
5131 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5133 /* cross-partitions searches with a basedn break multi-domain support */
5134 SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
5136 res = talloc_zero(tmp_ctx, struct ldb_result);
5138 talloc_free(tmp_ctx);
5139 return ldb_oom(ldb);
5143 va_start(ap, exp_fmt);
5144 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
5148 talloc_free(tmp_ctx);
5149 return ldb_oom(ldb);
5153 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
5160 ldb_search_default_callback,
5162 if (ret != LDB_SUCCESS) {
5163 talloc_free(tmp_ctx);
5167 ret = dsdb_request_add_controls(req, dsdb_flags);
5168 if (ret != LDB_SUCCESS) {
5169 talloc_free(tmp_ctx);
5170 ldb_reset_err_string(ldb);
5174 ret = ldb_request(ldb, req);
5175 if (ret == LDB_SUCCESS) {
5176 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
5179 if (ret != LDB_SUCCESS) {
5180 talloc_free(tmp_ctx);
5184 if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
5185 if (res->count == 0) {
5186 talloc_free(tmp_ctx);
5187 ldb_reset_err_string(ldb);
5188 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
5190 if (res->count != 1) {
5191 talloc_free(tmp_ctx);
5192 ldb_reset_err_string(ldb);
5193 return LDB_ERR_CONSTRAINT_VIOLATION;
5197 *_result = talloc_steal(mem_ctx, res);
5198 talloc_free(tmp_ctx);
5205 general search with dsdb_flags for controls
5206 returns exactly 1 record or an error
5208 int dsdb_search_one(struct ldb_context *ldb,
5209 TALLOC_CTX *mem_ctx,
5210 struct ldb_message **msg,
5211 struct ldb_dn *basedn,
5212 enum ldb_scope scope,
5213 const char * const *attrs,
5214 uint32_t dsdb_flags,
5215 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
5218 struct ldb_result *res;
5220 char *expression = NULL;
5221 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5223 dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
5225 res = talloc_zero(tmp_ctx, struct ldb_result);
5227 talloc_free(tmp_ctx);
5228 return ldb_oom(ldb);
5232 va_start(ap, exp_fmt);
5233 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
5237 talloc_free(tmp_ctx);
5238 return ldb_oom(ldb);
5240 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
5241 dsdb_flags, "%s", expression);
5243 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
5247 if (ret != LDB_SUCCESS) {
5248 talloc_free(tmp_ctx);
5252 *msg = talloc_steal(mem_ctx, res->msgs[0]);
5253 talloc_free(tmp_ctx);
5258 /* returns back the forest DNS name */
5259 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
5261 const char *forest_name = ldb_dn_canonical_string(mem_ctx,
5262 ldb_get_root_basedn(ldb));
5265 if (forest_name == NULL) {
5269 p = strchr(forest_name, '/');
5277 /* returns back the default domain DNS name */
5278 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
5280 const char *domain_name = ldb_dn_canonical_string(mem_ctx,
5281 ldb_get_default_basedn(ldb));
5284 if (domain_name == NULL) {
5288 p = strchr(domain_name, '/');
5297 validate that an DSA GUID belongs to the specified user sid.
5298 The user SID must be a domain controller account (either RODC or
5301 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
5302 const struct GUID *dsa_guid,
5303 const struct dom_sid *sid)
5306 - find DN of record with the DSA GUID in the
5307 configuration partition (objectGUID)
5308 - remove "NTDS Settings" component from DN
5309 - do a base search on that DN for serverReference with
5311 - extract objectSid from resulting serverReference
5313 - check this sid matches the sid argument
5315 struct ldb_dn *config_dn;
5316 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5317 struct ldb_message *msg;
5318 const char *attrs1[] = { NULL };
5319 const char *attrs2[] = { "serverReference", NULL };
5321 struct ldb_dn *dn, *account_dn;
5322 struct dom_sid sid2;
5325 config_dn = ldb_get_config_basedn(ldb);
5327 ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
5328 attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
5329 if (ret != LDB_SUCCESS) {
5330 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
5331 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
5332 talloc_free(tmp_ctx);
5333 return ldb_operr(ldb);
5337 if (!ldb_dn_remove_child_components(dn, 1)) {
5338 talloc_free(tmp_ctx);
5339 return ldb_operr(ldb);
5342 ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
5343 attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
5344 "(objectClass=server)");
5345 if (ret != LDB_SUCCESS) {
5346 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
5347 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
5348 talloc_free(tmp_ctx);
5349 return ldb_operr(ldb);
5352 account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
5353 if (account_dn == NULL) {
5354 DEBUG(1,(__location__ ": Failed to find account dn "
5355 "(serverReference) for %s, parent of DSA with "
5356 "objectGUID %s, sid %s\n",
5357 ldb_dn_get_linearized(msg->dn),
5358 GUID_string(tmp_ctx, dsa_guid),
5359 dom_sid_string(tmp_ctx, sid)));
5360 talloc_free(tmp_ctx);
5361 return ldb_operr(ldb);
5364 status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
5365 if (!NT_STATUS_IS_OK(status)) {
5366 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
5367 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
5368 talloc_free(tmp_ctx);
5369 return ldb_operr(ldb);
5372 if (!dom_sid_equal(sid, &sid2)) {
5373 /* someone is trying to spoof another account */
5374 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
5375 GUID_string(tmp_ctx, dsa_guid),
5376 dom_sid_string(tmp_ctx, sid),
5377 dom_sid_string(tmp_ctx, &sid2)));
5378 talloc_free(tmp_ctx);
5379 return ldb_operr(ldb);
5382 talloc_free(tmp_ctx);
5386 static const char * const secret_attributes[] = {
5387 DSDB_SECRET_ATTRIBUTES,
5392 check if the attribute belongs to the RODC filtered attribute set
5393 Note that attributes that are in the filtered attribute set are the
5394 ones that _are_ always sent to a RODC
5396 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
5398 /* they never get secret attributes */
5399 if (ldb_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
5403 /* they do get non-secret critical attributes */
5404 if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
5408 /* they do get non-secret attributes marked as being in the FAS */
5409 if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
5413 /* other attributes are denied */
5417 /* return fsmo role dn and role owner dn for a particular role*/
5418 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
5419 struct ldb_context *ldb,
5421 struct ldb_dn **fsmo_role_dn,
5422 struct ldb_dn **role_owner_dn)
5426 case DREPL_NAMING_MASTER:
5427 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
5428 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5429 if (ret != LDB_SUCCESS) {
5430 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
5431 ldb_errstring(ldb)));
5432 talloc_free(tmp_ctx);
5433 return WERR_DS_DRA_INTERNAL_ERROR;
5436 case DREPL_INFRASTRUCTURE_MASTER:
5437 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
5438 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5439 if (ret != LDB_SUCCESS) {
5440 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5441 ldb_errstring(ldb)));
5442 talloc_free(tmp_ctx);
5443 return WERR_DS_DRA_INTERNAL_ERROR;
5446 case DREPL_RID_MASTER:
5447 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
5448 if (ret != LDB_SUCCESS) {
5449 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
5450 talloc_free(tmp_ctx);
5451 return WERR_DS_DRA_INTERNAL_ERROR;
5454 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5455 if (ret != LDB_SUCCESS) {
5456 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
5457 ldb_errstring(ldb)));
5458 talloc_free(tmp_ctx);
5459 return WERR_DS_DRA_INTERNAL_ERROR;
5462 case DREPL_SCHEMA_MASTER:
5463 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
5464 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5465 if (ret != LDB_SUCCESS) {
5466 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5467 ldb_errstring(ldb)));
5468 talloc_free(tmp_ctx);
5469 return WERR_DS_DRA_INTERNAL_ERROR;
5472 case DREPL_PDC_MASTER:
5473 *fsmo_role_dn = ldb_get_default_basedn(ldb);
5474 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5475 if (ret != LDB_SUCCESS) {
5476 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
5477 ldb_errstring(ldb)));
5478 talloc_free(tmp_ctx);
5479 return WERR_DS_DRA_INTERNAL_ERROR;
5483 return WERR_DS_DRA_INTERNAL_ERROR;
5488 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
5489 TALLOC_CTX *mem_ctx,
5490 struct ldb_dn *server_dn)
5493 struct ldb_result *res = NULL;
5494 const char * const attrs[] = { "dNSHostName", NULL};
5496 ldb_ret = ldb_search(ldb, mem_ctx, &res,
5500 if (ldb_ret != LDB_SUCCESS) {
5501 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
5502 ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
5506 return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
5510 returns true if an attribute is in the filter,
5511 false otherwise, provided that attribute value is provided with the expression
5513 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
5517 switch (tree->operation) {
5520 for (i=0;i<tree->u.list.num_elements;i++) {
5521 if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
5527 return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
5528 case LDB_OP_EQUALITY:
5529 case LDB_OP_GREATER:
5532 if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
5536 case LDB_OP_SUBSTRING:
5537 if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
5541 case LDB_OP_PRESENT:
5542 /* (attrname=*) is not filtered out */
5544 case LDB_OP_EXTENDED:
5545 if (tree->u.extended.attr &&
5546 ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
5554 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
5555 const char *location, const char *func,
5558 if (reason == NULL) {
5559 reason = win_errstr(werr);
5561 ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
5562 W_ERROR_V(werr), reason, location, func);
5567 map an ldb error code to an approximate NTSTATUS code
5569 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
5573 return NT_STATUS_OK;
5575 case LDB_ERR_PROTOCOL_ERROR:
5576 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
5578 case LDB_ERR_TIME_LIMIT_EXCEEDED:
5579 return NT_STATUS_IO_TIMEOUT;
5581 case LDB_ERR_SIZE_LIMIT_EXCEEDED:
5582 return NT_STATUS_BUFFER_TOO_SMALL;
5584 case LDB_ERR_COMPARE_FALSE:
5585 case LDB_ERR_COMPARE_TRUE:
5586 return NT_STATUS_REVISION_MISMATCH;
5588 case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
5589 return NT_STATUS_NOT_SUPPORTED;
5591 case LDB_ERR_STRONG_AUTH_REQUIRED:
5592 case LDB_ERR_CONFIDENTIALITY_REQUIRED:
5593 case LDB_ERR_SASL_BIND_IN_PROGRESS:
5594 case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
5595 case LDB_ERR_INVALID_CREDENTIALS:
5596 case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
5597 case LDB_ERR_UNWILLING_TO_PERFORM:
5598 return NT_STATUS_ACCESS_DENIED;
5600 case LDB_ERR_NO_SUCH_OBJECT:
5601 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
5603 case LDB_ERR_REFERRAL:
5604 case LDB_ERR_NO_SUCH_ATTRIBUTE:
5605 return NT_STATUS_NOT_FOUND;
5607 case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
5608 return NT_STATUS_NOT_SUPPORTED;
5610 case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
5611 return NT_STATUS_BUFFER_TOO_SMALL;
5613 case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
5614 case LDB_ERR_INAPPROPRIATE_MATCHING:
5615 case LDB_ERR_CONSTRAINT_VIOLATION:
5616 case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
5617 case LDB_ERR_INVALID_DN_SYNTAX:
5618 case LDB_ERR_NAMING_VIOLATION:
5619 case LDB_ERR_OBJECT_CLASS_VIOLATION:
5620 case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
5621 case LDB_ERR_NOT_ALLOWED_ON_RDN:
5622 return NT_STATUS_INVALID_PARAMETER;
5624 case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
5625 case LDB_ERR_ENTRY_ALREADY_EXISTS:
5626 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
5629 return NT_STATUS_NETWORK_BUSY;
5631 case LDB_ERR_ALIAS_PROBLEM:
5632 case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
5633 case LDB_ERR_UNAVAILABLE:
5634 case LDB_ERR_LOOP_DETECT:
5635 case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
5636 case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
5638 case LDB_ERR_OPERATIONS_ERROR:
5641 return NT_STATUS_UNSUCCESSFUL;
5646 create a new naming context that will hold a partial replica
5648 int dsdb_create_partial_replica_NC(struct ldb_context *ldb, struct ldb_dn *dn)
5650 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5651 struct ldb_message *msg;
5654 msg = ldb_msg_new(tmp_ctx);
5656 talloc_free(tmp_ctx);
5657 return ldb_oom(ldb);
5661 ret = ldb_msg_add_string(msg, "objectClass", "top");
5662 if (ret != LDB_SUCCESS) {
5663 talloc_free(tmp_ctx);
5664 return ldb_oom(ldb);
5667 /* [MS-DRSR] implies that we should only add the 'top'
5668 * objectclass, but that would cause lots of problems with our
5669 * objectclass code as top is not structural, so we add
5670 * 'domainDNS' as well to keep things sane. We're expecting
5671 * this new NC to be of objectclass domainDNS after
5672 * replication anyway
5674 ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
5675 if (ret != LDB_SUCCESS) {
5676 talloc_free(tmp_ctx);
5677 return ldb_oom(ldb);
5680 ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
5681 INSTANCE_TYPE_IS_NC_HEAD|
5682 INSTANCE_TYPE_NC_ABOVE|
5683 INSTANCE_TYPE_UNINSTANT);
5684 if (ret != LDB_SUCCESS) {
5685 talloc_free(tmp_ctx);
5686 return ldb_oom(ldb);
5689 ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
5690 if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
5691 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
5692 ldb_dn_get_linearized(dn),
5693 ldb_errstring(ldb), ldb_strerror(ret)));
5694 talloc_free(tmp_ctx);
5698 DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
5700 talloc_free(tmp_ctx);
5705 * Return the effective badPwdCount
5707 * This requires that the user_msg have (if present):
5711 * This also requires that the domain_msg have (if present):
5712 * - lockOutObservationWindow
5714 int dsdb_effective_badPwdCount(const struct ldb_message *user_msg,
5715 int64_t lockOutObservationWindow,
5718 int64_t badPasswordTime;
5719 badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
5721 if (badPasswordTime - lockOutObservationWindow >= now) {
5722 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
5729 * Returns a user's PSO, or NULL if none was found
5731 static struct ldb_result *lookup_user_pso(struct ldb_context *sam_ldb,
5732 TALLOC_CTX *mem_ctx,
5733 const struct ldb_message *user_msg,
5734 const char * const *attrs)
5736 struct ldb_result *res = NULL;
5737 struct ldb_dn *pso_dn = NULL;
5740 /* if the user has a PSO that applies, then use the PSO's setting */
5741 pso_dn = ldb_msg_find_attr_as_dn(sam_ldb, mem_ctx, user_msg,
5742 "msDS-ResultantPSO");
5744 if (pso_dn != NULL) {
5746 ret = dsdb_search_dn(sam_ldb, mem_ctx, &res, pso_dn, attrs, 0);
5747 if (ret != LDB_SUCCESS) {
5750 * log the error. The caller should fallback to using
5751 * the default domain password settings
5753 DBG_ERR("Error retrieving msDS-ResultantPSO %s for %s",
5754 ldb_dn_get_linearized(pso_dn),
5755 ldb_dn_get_linearized(user_msg->dn));
5757 talloc_free(pso_dn);
5763 * Return the msDS-LockoutObservationWindow for a user message
5765 * This requires that the user_msg have (if present):
5766 * - msDS-ResultantPSO
5768 int64_t samdb_result_msds_LockoutObservationWindow(
5769 struct ldb_context *sam_ldb,
5770 TALLOC_CTX *mem_ctx,
5771 struct ldb_dn *domain_dn,
5772 const struct ldb_message *user_msg)
5774 int64_t lockOutObservationWindow;
5775 struct ldb_result *res = NULL;
5776 const char *attrs[] = { "msDS-LockoutObservationWindow",
5778 if (domain_dn == NULL) {
5779 smb_panic("domain dn is NULL");
5781 res = lookup_user_pso(sam_ldb, mem_ctx, user_msg, attrs);
5784 lockOutObservationWindow =
5785 ldb_msg_find_attr_as_int64(res->msgs[0],
5786 "msDS-LockoutObservationWindow",
5787 DEFAULT_OBSERVATION_WINDOW);
5791 /* no PSO was found, lookup the default domain setting */
5792 lockOutObservationWindow =
5793 samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
5794 "lockOutObservationWindow", NULL);
5796 return lockOutObservationWindow;
5800 * Return the effective badPwdCount
5802 * This requires that the user_msg have (if present):
5805 * - msDS-ResultantPSO
5807 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
5808 TALLOC_CTX *mem_ctx,
5809 struct ldb_dn *domain_dn,
5810 const struct ldb_message *user_msg)
5812 struct timeval tv_now = timeval_current();
5813 NTTIME now = timeval_to_nttime(&tv_now);
5814 int64_t lockOutObservationWindow =
5815 samdb_result_msds_LockoutObservationWindow(
5816 sam_ldb, mem_ctx, domain_dn, user_msg);
5817 return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5821 * Returns the lockoutThreshold that applies. If a PSO is specified, then that
5822 * setting is used over the domain defaults
5824 static int64_t get_lockout_threshold(struct ldb_message *domain_msg,
5825 struct ldb_message *pso_msg)
5827 if (pso_msg != NULL) {
5828 return ldb_msg_find_attr_as_int(pso_msg,
5829 "msDS-LockoutThreshold", 0);
5831 return ldb_msg_find_attr_as_int(domain_msg,
5832 "lockoutThreshold", 0);
5837 * Returns the lockOutObservationWindow that applies. If a PSO is specified,
5838 * then that setting is used over the domain defaults
5840 static int64_t get_lockout_observation_window(struct ldb_message *domain_msg,
5841 struct ldb_message *pso_msg)
5843 if (pso_msg != NULL) {
5844 return ldb_msg_find_attr_as_int64(pso_msg,
5845 "msDS-LockoutObservationWindow",
5846 DEFAULT_OBSERVATION_WINDOW);
5848 return ldb_msg_find_attr_as_int64(domain_msg,
5849 "lockOutObservationWindow",
5850 DEFAULT_OBSERVATION_WINDOW);
5855 * Prepare an update to the badPwdCount and associated attributes.
5857 * This requires that the user_msg have (if present):
5862 * This also requires that the domain_msg have (if present):
5864 * - lockoutThreshold
5865 * - lockOutObservationWindow
5867 * This also requires that the pso_msg have (if present):
5868 * - msDS-LockoutThreshold
5869 * - msDS-LockoutObservationWindow
5871 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
5872 struct ldb_context *sam_ctx,
5873 struct ldb_message *user_msg,
5874 struct ldb_message *domain_msg,
5875 struct ldb_message *pso_msg,
5876 struct ldb_message **_mod_msg)
5878 int ret, badPwdCount;
5880 int64_t lockoutThreshold, lockOutObservationWindow;
5881 struct dom_sid *sid;
5882 struct timeval tv_now = timeval_current();
5883 NTTIME now = timeval_to_nttime(&tv_now);
5885 uint32_t pwdProperties, rid = 0;
5886 struct ldb_message *mod_msg;
5888 sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
5890 pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
5891 "pwdProperties", -1);
5892 if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
5893 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
5894 if (!NT_STATUS_IS_OK(status)) {
5896 * This can't happen anyway, but always try
5897 * and update the badPwdCount on failure
5905 * Work out if we are doing password lockout on the domain.
5906 * Also, the built in administrator account is exempt:
5907 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
5909 lockoutThreshold = get_lockout_threshold(domain_msg, pso_msg);
5910 if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
5911 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
5912 ldb_dn_get_linearized(user_msg->dn)));
5913 return NT_STATUS_OK;
5916 mod_msg = ldb_msg_new(mem_ctx);
5917 if (mod_msg == NULL) {
5918 return NT_STATUS_NO_MEMORY;
5920 mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
5921 if (mod_msg->dn == NULL) {
5922 TALLOC_FREE(mod_msg);
5923 return NT_STATUS_NO_MEMORY;
5926 lockOutObservationWindow = get_lockout_observation_window(domain_msg,
5929 badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5933 ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
5934 if (ret != LDB_SUCCESS) {
5935 TALLOC_FREE(mod_msg);
5936 return NT_STATUS_NO_MEMORY;
5938 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
5939 if (ret != LDB_SUCCESS) {
5940 TALLOC_FREE(mod_msg);
5941 return NT_STATUS_NO_MEMORY;
5944 if (badPwdCount >= lockoutThreshold) {
5945 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
5946 if (ret != LDB_SUCCESS) {
5947 TALLOC_FREE(mod_msg);
5948 return NT_STATUS_NO_MEMORY;
5950 DEBUGC( DBGC_AUTH, 1, ("Locked out user %s after %d wrong passwords\n",
5951 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5953 DEBUGC( DBGC_AUTH, 5, ("Updated badPwdCount on %s after %d wrong passwords\n",
5954 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5957 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5958 for (i=0; i< mod_msg->num_elements; i++) {
5959 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5962 *_mod_msg = mod_msg;
5963 return NT_STATUS_OK;
5967 * Sets defaults for a User object
5968 * List of default attributes set:
5969 * accountExpires, badPasswordTime, badPwdCount,
5970 * codePage, countryCode, lastLogoff, lastLogon
5971 * logonCount, pwdLastSet
5973 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
5974 struct ldb_message *usr_obj,
5975 struct ldb_request *req)
5979 const struct attribute_values {
5982 const char *add_value;
5983 const char *mod_value;
5984 const char *control;
5989 .name = "accountExpires",
5990 .add_value = "9223372036854775807",
5994 .name = "badPasswordTime",
5998 .name = "badPwdCount",
6006 .name = "countryCode",
6010 .name = "lastLogoff",
6014 .name = "lastLogon",
6018 .name = "logonCount",
6022 .name = "logonHours",
6023 .add_flags = DSDB_FLAG_INTERNAL_FORCE_META_DATA,
6026 .name = "pwdLastSet",
6028 .control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
6031 .name = "adminCount",
6035 .name = "operatorCount",
6040 for (i = 0; i < ARRAY_SIZE(map); i++) {
6042 const char *value = NULL;
6045 if (req != NULL && req->operation == LDB_ADD) {
6046 value = map[i].add_value;
6047 flags = map[i].add_flags;
6049 value = map[i].mod_value;
6050 flags = map[i].mod_flags;
6053 if (value == NULL) {
6054 value = map[i].value;
6057 if (value != NULL) {
6058 flags |= LDB_FLAG_MOD_ADD;
6065 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
6069 if (ret != LDB_SUCCESS) {
6073 if (req != NULL && added && map[i].control != NULL) {
6074 ret = ldb_request_add_control(req,
6077 if (ret != LDB_SUCCESS) {
6087 * Sets 'sAMAccountType on user object based on userAccountControl.
6088 * This function is used in processing both 'add' and 'modify' requests.
6089 * @param ldb Current ldb_context
6090 * @param usr_obj ldb_message representing User object
6091 * @param user_account_control Value for userAccountControl flags
6092 * @param account_type_p Optional pointer to account_type to return
6093 * @return LDB_SUCCESS or LDB_ERR* code on failure
6095 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
6096 uint32_t user_account_control, uint32_t *account_type_p)
6099 uint32_t account_type;
6101 account_type = ds_uf2atype(user_account_control);
6102 if (account_type == 0) {
6103 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
6104 return LDB_ERR_UNWILLING_TO_PERFORM;
6106 ret = samdb_msg_add_uint_flags(ldb, usr_obj, usr_obj,
6109 LDB_FLAG_MOD_REPLACE);
6110 if (ret != LDB_SUCCESS) {
6114 if (account_type_p) {
6115 *account_type_p = account_type;
6122 * Determine and set primaryGroupID based on userAccountControl value.
6123 * This function is used in processing both 'add' and 'modify' requests.
6124 * @param ldb Current ldb_context
6125 * @param usr_obj ldb_message representing User object
6126 * @param user_account_control Value for userAccountControl flags
6127 * @param group_rid_p Optional pointer to group RID to return
6128 * @return LDB_SUCCESS or LDB_ERR* code on failure
6130 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
6131 uint32_t user_account_control, uint32_t *group_rid_p)
6136 rid = ds_uf2prim_group_rid(user_account_control);
6138 ret = samdb_msg_add_uint_flags(ldb, usr_obj, usr_obj,
6139 "primaryGroupID", rid,
6140 LDB_FLAG_MOD_REPLACE);
6141 if (ret != LDB_SUCCESS) {
6153 * Returns True if the source and target DNs both have the same naming context,
6154 * i.e. they're both in the same partition.
6156 bool dsdb_objects_have_same_nc(struct ldb_context *ldb,
6157 TALLOC_CTX *mem_ctx,
6158 struct ldb_dn *source_dn,
6159 struct ldb_dn *target_dn)
6161 TALLOC_CTX *tmp_ctx;
6162 struct ldb_dn *source_nc = NULL;
6163 struct ldb_dn *target_nc = NULL;
6165 bool same_nc = true;
6167 tmp_ctx = talloc_new(mem_ctx);
6169 ret = dsdb_find_nc_root(ldb, tmp_ctx, source_dn, &source_nc);
6170 /* fix clang warning */
6171 if (source_nc == NULL) {
6172 ret = LDB_ERR_OTHER;
6174 if (ret != LDB_SUCCESS) {
6175 DBG_ERR("Failed to find base DN for source %s: %s\n",
6176 ldb_dn_get_linearized(source_dn), ldb_errstring(ldb));
6177 talloc_free(tmp_ctx);
6181 ret = dsdb_find_nc_root(ldb, tmp_ctx, target_dn, &target_nc);
6182 /* fix clang warning */
6183 if (target_nc == NULL) {
6184 ret = LDB_ERR_OTHER;
6186 if (ret != LDB_SUCCESS) {
6187 DBG_ERR("Failed to find base DN for target %s: %s\n",
6188 ldb_dn_get_linearized(target_dn), ldb_errstring(ldb));
6189 talloc_free(tmp_ctx);
6193 same_nc = (ldb_dn_compare(source_nc, target_nc) == 0);
6195 talloc_free(tmp_ctx);
6200 * Context for dsdb_count_domain_callback
6202 struct dsdb_count_domain_context {
6204 * Number of matching records
6208 * sid of the domain that the records must belong to.
6209 * if NULL records can belong to any domain.
6211 struct dom_sid *dom_sid;
6215 * @brief ldb aysnc callback for dsdb_domain_count.
6217 * count the number of records in the database matching an LDAP query,
6218 * optionally filtering for domain membership.
6220 * @param [in,out] req the ldb request being processed
6221 * req->context contains:
6222 * count The number of matching records
6223 * dom_sid The domain sid, if present records must belong
6224 * to the domain to be counted.
6225 *@param [in,out] ares The query result.
6227 * @return an LDB error code
6230 static int dsdb_count_domain_callback(
6231 struct ldb_request *req,
6232 struct ldb_reply *ares)
6236 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
6238 if (ares->error != LDB_SUCCESS) {
6239 int error = ares->error;
6241 return ldb_request_done(req, error);
6244 switch (ares->type) {
6245 case LDB_REPLY_ENTRY:
6247 struct dsdb_count_domain_context *context = NULL;
6251 const struct ldb_val *v;
6253 context = req->context;
6254 if (context->dom_sid == NULL) {
6259 v = ldb_msg_find_ldb_val(ares->message, "objectSid");
6264 ret = sid_parse(v->data, v->length, &sid);
6269 in_domain = dom_sid_in_domain(context->dom_sid, &sid);
6277 case LDB_REPLY_REFERRAL:
6280 case LDB_REPLY_DONE:
6282 return ldb_request_done(req, LDB_SUCCESS);
6291 * @brief Count the number of records matching a query.
6293 * Count the number of entries in the database matching the supplied query,
6294 * optionally filtering only those entries belonging to the supplied domain.
6296 * @param ldb [in] Current ldb context
6297 * @param count [out] Pointer to the count
6298 * @param base [in] The base dn for the quey
6299 * @param dom_sid [in] The domain sid, if non NULL records that are not a member
6300 * of the domain are ignored.
6301 * @param scope [in] Search scope.
6302 * @param exp_fmt [in] format string for the query.
6304 * @return LDB_STATUS code.
6306 int PRINTF_ATTRIBUTE(6, 7) dsdb_domain_count(
6307 struct ldb_context *ldb,
6309 struct ldb_dn *base,
6310 struct dom_sid *dom_sid,
6311 enum ldb_scope scope,
6312 const char *exp_fmt, ...)
6314 TALLOC_CTX *tmp_ctx = NULL;
6315 struct ldb_request *req = NULL;
6316 struct dsdb_count_domain_context *context = NULL;
6317 char *expression = NULL;
6318 const char *object_sid[] = {"objectSid", NULL};
6319 const char *none[] = {NULL};
6324 tmp_ctx = talloc_new(ldb);
6326 context = talloc_zero(tmp_ctx, struct dsdb_count_domain_context);
6327 if (context == NULL) {
6328 return LDB_ERR_OPERATIONS_ERROR;
6330 context->dom_sid = dom_sid;
6333 va_start(ap, exp_fmt);
6334 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
6337 if (expression == NULL) {
6338 TALLOC_FREE(context);
6339 TALLOC_FREE(tmp_ctx);
6340 return LDB_ERR_OPERATIONS_ERROR;
6344 ret = ldb_build_search_req(
6351 (dom_sid == NULL) ? none : object_sid,
6354 dsdb_count_domain_callback,
6356 ldb_req_set_location(req, "dsdb_domain_count");
6358 if (ret != LDB_SUCCESS) goto done;
6360 ret = ldb_request(ldb, req);
6362 if (ret == LDB_SUCCESS) {
6363 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
6364 if (ret == LDB_SUCCESS) {
6365 *count = context->count;
6371 TALLOC_FREE(expression);
6373 TALLOC_FREE(context);
6374 TALLOC_FREE(tmp_ctx);
6380 * Returns 1 if 'sids' contains the Protected Users group SID for the domain, 0
6381 * if not. Returns a negative value on error.
6383 int dsdb_is_protected_user(struct ldb_context *ldb,
6384 const struct auth_SidAttr *sids,
6387 const struct dom_sid *domain_sid = NULL;
6388 struct dom_sid protected_users_sid;
6391 domain_sid = samdb_domain_sid(ldb);
6392 if (domain_sid == NULL) {
6396 protected_users_sid = *domain_sid;
6397 if (!sid_append_rid(&protected_users_sid, DOMAIN_RID_PROTECTED_USERS)) {
6401 for (i = 0; i < num_sids; ++i) {
6402 if (dom_sid_equal(&protected_users_sid, &sids[i].sid)) {