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/util_runcmd.h"
49 #include "lib/util/access.h"
52 * This included to allow us to handle DSDB_FLAG_REPLICATED_UPDATE in
53 * dsdb_request_add_controls()
55 #include "dsdb/samdb/ldb_modules/util.h"
58 search the sam for the specified attributes in a specific domain, filter on
59 objectSid being in domain_sid.
61 int samdb_search_domain(struct ldb_context *sam_ldb,
63 struct ldb_dn *basedn,
64 struct ldb_message ***res,
65 const char * const *attrs,
66 const struct dom_sid *domain_sid,
67 const char *format, ...) _PRINTF_ATTRIBUTE(7,8)
73 count = gendb_search_v(sam_ldb, mem_ctx, basedn,
74 res, attrs, format, ap);
80 struct dom_sid *entry_sid;
82 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
84 if ((entry_sid == NULL) ||
85 (!dom_sid_in_domain(domain_sid, entry_sid))) {
86 /* Delete that entry from the result set */
87 (*res)[i] = (*res)[count-1];
89 talloc_free(entry_sid);
92 talloc_free(entry_sid);
100 search the sam for a single string attribute in exactly 1 record
102 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
104 struct ldb_dn *basedn,
105 const char *attr_name,
106 const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
109 const char *attrs[2] = { NULL, NULL };
110 struct ldb_message **res = NULL;
112 attrs[0] = attr_name;
114 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
116 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
117 attr_name, format, count));
124 return ldb_msg_find_attr_as_string(res[0], attr_name, NULL);
128 search the sam for a single string attribute in exactly 1 record
130 const char *samdb_search_string(struct ldb_context *sam_ldb,
132 struct ldb_dn *basedn,
133 const char *attr_name,
134 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
139 va_start(ap, format);
140 str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
146 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
148 struct ldb_dn *basedn,
149 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
153 struct ldb_message **res = NULL;
156 va_start(ap, format);
157 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
160 if (count != 1) return NULL;
162 ret = talloc_steal(mem_ctx, res[0]->dn);
169 search the sam for a dom_sid attribute in exactly 1 record
171 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
173 struct ldb_dn *basedn,
174 const char *attr_name,
175 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
179 struct ldb_message **res;
180 const char *attrs[2] = { NULL, NULL };
183 attrs[0] = attr_name;
185 va_start(ap, format);
186 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
189 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
190 attr_name, format, count));
196 sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
202 return the count of the number of records in the sam matching the query
204 int samdb_search_count(struct ldb_context *sam_ldb,
206 struct ldb_dn *basedn,
207 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
210 const char *attrs[] = { NULL };
213 va_start(ap, format);
214 ret = gendb_search_v(sam_ldb, mem_ctx, basedn, NULL, attrs, format, ap);
222 search the sam for a single integer attribute in exactly 1 record
224 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
226 unsigned int default_value,
227 struct ldb_dn *basedn,
228 const char *attr_name,
229 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
233 struct ldb_message **res;
234 const char *attrs[2] = { NULL, NULL };
236 attrs[0] = attr_name;
238 va_start(ap, format);
239 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
243 return default_value;
246 return ldb_msg_find_attr_as_uint(res[0], attr_name, default_value);
250 search the sam for a single signed 64 bit integer attribute in exactly 1 record
252 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
254 int64_t default_value,
255 struct ldb_dn *basedn,
256 const char *attr_name,
257 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
261 struct ldb_message **res;
262 const char *attrs[2] = { NULL, NULL };
264 attrs[0] = attr_name;
266 va_start(ap, format);
267 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
271 return default_value;
274 return ldb_msg_find_attr_as_int64(res[0], attr_name, default_value);
278 search the sam for multipe records each giving a single string attribute
279 return the number of matches, or -1 on error
281 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
283 struct ldb_dn *basedn,
285 const char *attr_name,
286 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
290 const char *attrs[2] = { NULL, NULL };
291 struct ldb_message **res = NULL;
293 attrs[0] = attr_name;
295 va_start(ap, format);
296 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
303 /* make sure its single valued */
304 for (i=0;i<count;i++) {
305 if (res[i]->num_elements != 1) {
306 DEBUG(1,("samdb: search for %s %s not single valued\n",
313 *strs = talloc_array(mem_ctx, const char *, count+1);
319 for (i=0;i<count;i++) {
320 (*strs)[i] = ldb_msg_find_attr_as_string(res[i], attr_name, NULL);
322 (*strs)[count] = NULL;
327 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
328 const char *attr, struct ldb_dn *default_value)
330 struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
332 return default_value;
338 pull a rid from a objectSid in a result set.
340 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
341 const char *attr, uint32_t default_value)
346 sid = samdb_result_dom_sid(mem_ctx, msg, attr);
348 return default_value;
350 rid = sid->sub_auths[sid->num_auths-1];
356 pull a dom_sid structure from a objectSid in a result set.
358 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
362 const struct ldb_val *v;
364 v = ldb_msg_find_ldb_val(msg, attr);
368 sid = talloc(mem_ctx, struct dom_sid);
372 ok = sid_parse(v->data, v->length, sid);
381 pull a guid structure from a objectGUID in a result set.
383 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
385 const struct ldb_val *v;
389 v = ldb_msg_find_ldb_val(msg, attr);
390 if (!v) return GUID_zero();
392 status = GUID_from_ndr_blob(v, &guid);
393 if (!NT_STATUS_IS_OK(status)) {
401 pull a sid prefix from a objectSid in a result set.
402 this is used to find the domain sid for a user
404 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
407 struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
408 if (!sid || sid->num_auths < 1) return NULL;
414 pull a NTTIME in a result set.
416 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
417 NTTIME default_value)
419 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
423 * Windows stores 0 for lastLogoff.
424 * But when a MS DC return the lastLogoff (as Logoff Time)
425 * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
426 * cause windows 2008 and newer version to fail for SMB requests
428 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
430 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
433 ret = 0x7FFFFFFFFFFFFFFFULL;
439 * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
440 * indicate an account doesn't expire.
442 * When Windows initially creates an account, it sets
443 * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF). However,
444 * when changing from an account having a specific expiration date to
445 * that account never expiring, it sets accountExpires = 0.
447 * Consolidate that logic here to allow clearer logic for account expiry in
448 * the rest of the code.
450 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
452 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
456 ret = 0x7FFFFFFFFFFFFFFFULL;
462 construct the allow_password_change field from the PwdLastSet attribute and the
463 domain password settings
465 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb,
467 struct ldb_dn *domain_dn,
468 struct ldb_message *msg,
471 uint64_t attr_time = ldb_msg_find_attr_as_uint64(msg, attr, 0);
474 if (attr_time == 0) {
478 minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
480 /* yes, this is a -= not a += as minPwdAge is stored as the negative
481 of the number of 100-nano-seconds */
482 attr_time -= minPwdAge;
488 pull a samr_Password structutre from a result set.
490 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
492 struct samr_Password *hash = NULL;
493 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
494 if (val && (val->length >= sizeof(hash->hash))) {
495 hash = talloc(mem_ctx, struct samr_Password);
496 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
502 pull an array of samr_Password structures from a result set.
504 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
505 const char *attr, struct samr_Password **hashes)
507 unsigned int count, i;
508 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
514 count = val->length / 16;
519 *hashes = talloc_array(mem_ctx, struct samr_Password, count);
524 for (i=0;i<count;i++) {
525 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
531 NTSTATUS samdb_result_passwords_from_history(TALLOC_CTX *mem_ctx,
532 struct loadparm_context *lp_ctx,
533 struct ldb_message *msg,
535 struct samr_Password **lm_pwd,
536 struct samr_Password **nt_pwd)
538 struct samr_Password *lmPwdHash, *ntPwdHash;
542 num_nt = samdb_result_hashes(mem_ctx, msg, "ntPwdHistory", &ntPwdHash);
546 *nt_pwd = &ntPwdHash[idx];
550 /* Ensure that if we have turned off LM
551 * authentication, that we never use the LM hash, even
553 if (lpcfg_lanman_auth(lp_ctx)) {
555 num_lm = samdb_result_hashes(mem_ctx, msg, "lmPwdHistory", &lmPwdHash);
559 *lm_pwd = &lmPwdHash[idx];
568 NTSTATUS samdb_result_passwords_no_lockout(TALLOC_CTX *mem_ctx,
569 struct loadparm_context *lp_ctx,
570 const struct ldb_message *msg,
571 struct samr_Password **lm_pwd,
572 struct samr_Password **nt_pwd)
574 struct samr_Password *lmPwdHash, *ntPwdHash;
578 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
581 } else if (num_nt > 1) {
582 return NT_STATUS_INTERNAL_DB_CORRUPTION;
584 *nt_pwd = &ntPwdHash[0];
588 /* Ensure that if we have turned off LM
589 * authentication, that we never use the LM hash, even
591 if (lpcfg_lanman_auth(lp_ctx)) {
593 num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
596 } else if (num_lm > 1) {
597 return NT_STATUS_INTERNAL_DB_CORRUPTION;
599 *lm_pwd = &lmPwdHash[0];
608 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx,
609 struct loadparm_context *lp_ctx,
610 const struct ldb_message *msg,
611 struct samr_Password **lm_pwd,
612 struct samr_Password **nt_pwd)
616 acct_flags = samdb_result_acct_flags(msg,
617 "msDS-User-Account-Control-Computed");
618 /* Quit if the account was locked out. */
619 if (acct_flags & ACB_AUTOLOCK) {
620 DEBUG(3,("samdb_result_passwords: Account for user %s was locked out.\n",
621 ldb_dn_get_linearized(msg->dn)));
622 return NT_STATUS_ACCOUNT_LOCKED_OUT;
625 return samdb_result_passwords_no_lockout(mem_ctx, lp_ctx, msg,
630 pull a samr_LogonHours structutre from a result set.
632 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
634 struct samr_LogonHours hours;
635 size_t units_per_week = 168;
636 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
641 units_per_week = val->length * 8;
644 hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
648 hours.units_per_week = units_per_week;
649 memset(hours.bits, 0xFF, units_per_week/8);
651 memcpy(hours.bits, val->data, val->length);
658 pull a set of account_flags from a result set.
660 Naturally, this requires that userAccountControl and
661 (if not null) the attributes 'attr' be already
664 uint32_t samdb_result_acct_flags(const struct ldb_message *msg, const char *attr)
666 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
667 uint32_t attr_flags = 0;
668 uint32_t acct_flags = ds_uf2acb(userAccountControl);
670 attr_flags = ldb_msg_find_attr_as_uint(msg, attr, UF_ACCOUNTDISABLE);
671 if (attr_flags == UF_ACCOUNTDISABLE) {
672 DEBUG(0, ("Attribute %s not found, disabling account %s!\n", attr,
673 ldb_dn_get_linearized(msg->dn)));
675 acct_flags |= ds_uf2acb(attr_flags);
681 NTSTATUS samdb_result_parameters(TALLOC_CTX *mem_ctx,
682 struct ldb_message *msg,
684 struct lsa_BinaryString *s)
687 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
695 if ((val->length % 2) != 0) {
697 * If the on-disk data is not even in length, we know
698 * it is corrupt, and can not be safely pushed. We
699 * would either truncate, send either a un-initilaised
700 * byte or send a forced zero byte
702 return NT_STATUS_INTERNAL_DB_CORRUPTION;
705 s->array = talloc_array(mem_ctx, uint16_t, val->length/2);
707 return NT_STATUS_NO_MEMORY;
709 s->length = s->size = val->length;
711 /* The on-disk format is the 'network' format, being UTF16LE (sort of) */
712 for (i = 0; i < s->length / 2; i++) {
713 s->array[i] = SVAL(val->data, i * 2);
719 /* Find an attribute, with a particular value */
721 /* The current callers of this function expect a very specific
722 * behaviour: In particular, objectClass subclass equivilance is not
723 * wanted. This means that we should not lookup the schema for the
724 * comparison function */
725 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
726 const struct ldb_message *msg,
727 const char *name, const char *value)
730 struct ldb_message_element *el = ldb_msg_find_element(msg, name);
736 for (i=0;i<el->num_values;i++) {
737 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
745 static int samdb_find_or_add_attribute_ex(struct ldb_context *ldb,
746 struct ldb_message *msg,
748 const char *set_value,
753 struct ldb_message_element *el;
755 SMB_ASSERT(attr_flags != 0);
757 el = ldb_msg_find_element(msg, name);
766 ret = ldb_msg_add_empty(msg, name,
769 if (ret != LDB_SUCCESS) {
773 if (set_value != NULL) {
774 ret = ldb_msg_add_string(msg, name, set_value);
775 if (ret != LDB_SUCCESS) {
786 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
788 return samdb_find_or_add_attribute_ex(ldb, msg, name, set_value, LDB_FLAG_MOD_ADD, NULL);
792 add a dom_sid element to a message
794 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
795 const char *attr_name, const struct dom_sid *sid)
798 enum ndr_err_code ndr_err;
800 ndr_err = ndr_push_struct_blob(&v, mem_ctx,
802 (ndr_push_flags_fn_t)ndr_push_dom_sid);
803 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
804 return ldb_operr(sam_ldb);
806 return ldb_msg_add_value(msg, attr_name, &v, NULL);
811 add a delete element operation to a message
813 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
814 const char *attr_name)
816 /* we use an empty replace rather than a delete, as it allows for
817 dsdb_replace() to be used everywhere */
818 return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
822 add an add attribute value to a message or enhance an existing attribute
823 which has the same name and the add flag set.
825 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
826 struct ldb_message *msg, const char *attr_name,
829 struct ldb_message_element *el;
830 struct ldb_val val, *vals;
836 v = talloc_strdup(mem_ctx, value);
838 return ldb_oom(sam_ldb);
841 val.data = (uint8_t *) v;
842 val.length = strlen(v);
844 if (val.length == 0) {
845 /* allow empty strings as non-existent attributes */
849 for (i = 0; i < msg->num_elements; i++) {
850 el = &msg->elements[i];
851 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
852 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
858 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
860 if (ret != LDB_SUCCESS) {
865 vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
868 return ldb_oom(sam_ldb);
871 el->values[el->num_values] = val;
878 add a delete attribute value to a message or enhance an existing attribute
879 which has the same name and the delete flag set.
881 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
882 struct ldb_message *msg, const char *attr_name,
885 struct ldb_message_element *el;
886 struct ldb_val val, *vals;
892 v = talloc_strdup(mem_ctx, value);
894 return ldb_oom(sam_ldb);
897 val.data = (uint8_t *) v;
898 val.length = strlen(v);
900 if (val.length == 0) {
901 /* allow empty strings as non-existent attributes */
905 for (i = 0; i < msg->num_elements; i++) {
906 el = &msg->elements[i];
907 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
908 (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
914 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
916 if (ret != LDB_SUCCESS) {
921 vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
924 return ldb_oom(sam_ldb);
927 el->values[el->num_values] = val;
934 add a int element to a message
936 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
937 const char *attr_name, int v)
939 const char *s = talloc_asprintf(mem_ctx, "%d", v);
941 return ldb_oom(sam_ldb);
943 return ldb_msg_add_string(msg, attr_name, s);
947 * Add an unsigned int element to a message
949 * The issue here is that we have not yet first cast to int32_t explicitly,
950 * before we cast to an signed int to printf() into the %d or cast to a
951 * int64_t before we then cast to a long long to printf into a %lld.
953 * There are *no* unsigned integers in Active Directory LDAP, even the RID
954 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
955 * (See the schema, and the syntax definitions in schema_syntax.c).
958 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
959 const char *attr_name, unsigned int v)
961 return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
965 add a (signed) int64_t element to a message
967 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
968 const char *attr_name, int64_t v)
970 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
972 return ldb_oom(sam_ldb);
974 return ldb_msg_add_string(msg, attr_name, s);
978 * Add an unsigned int64_t (uint64_t) element to a message
980 * The issue here is that we have not yet first cast to int32_t explicitly,
981 * before we cast to an signed int to printf() into the %d or cast to a
982 * int64_t before we then cast to a long long to printf into a %lld.
984 * There are *no* unsigned integers in Active Directory LDAP, even the RID
985 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
986 * (See the schema, and the syntax definitions in schema_syntax.c).
989 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
990 const char *attr_name, uint64_t v)
992 return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
996 add a samr_Password element to a message
998 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
999 const char *attr_name, const struct samr_Password *hash)
1002 val.data = talloc_memdup(mem_ctx, hash->hash, 16);
1004 return ldb_oom(sam_ldb);
1007 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1011 add a samr_Password array to a message
1013 int samdb_msg_add_hashes(struct ldb_context *ldb,
1014 TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1015 const char *attr_name, struct samr_Password *hashes,
1020 val.data = talloc_array_size(mem_ctx, 16, count);
1021 val.length = count*16;
1023 return ldb_oom(ldb);
1025 for (i=0;i<count;i++) {
1026 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
1028 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1032 add a acct_flags element to a message
1034 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1035 const char *attr_name, uint32_t v)
1037 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1041 add a logon_hours element to a message
1043 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1044 const char *attr_name, struct samr_LogonHours *hours)
1047 val.length = hours->units_per_week / 8;
1048 val.data = hours->bits;
1049 return ldb_msg_add_value(msg, attr_name, &val, NULL);
1053 add a parameters element to a message
1055 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1056 const char *attr_name, struct lsa_BinaryString *parameters)
1060 if ((parameters->length % 2) != 0) {
1061 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
1064 val.data = talloc_array(mem_ctx, uint8_t, parameters->length);
1065 if (val.data == NULL) {
1066 return LDB_ERR_OPERATIONS_ERROR;
1068 val.length = parameters->length;
1069 for (i = 0; i < parameters->length / 2; i++) {
1071 * The on-disk format needs to be in the 'network'
1072 * format, parmeters->array is a uint16_t array of
1073 * length parameters->length / 2
1075 SSVAL(val.data, i * 2, parameters->array[i]);
1077 return ldb_msg_add_steal_value(msg, attr_name, &val);
1081 * Sets an unsigned int element in a message
1083 * The issue here is that we have not yet first cast to int32_t explicitly,
1084 * before we cast to an signed int to printf() into the %d or cast to a
1085 * int64_t before we then cast to a long long to printf into a %lld.
1087 * There are *no* unsigned integers in Active Directory LDAP, even the RID
1088 * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1089 * (See the schema, and the syntax definitions in schema_syntax.c).
1092 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1093 struct ldb_message *msg, const char *attr_name,
1096 struct ldb_message_element *el;
1098 el = ldb_msg_find_element(msg, attr_name);
1102 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1106 * Handle ldb_request in transaction
1108 int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1109 struct ldb_request *req)
1113 ret = ldb_transaction_start(sam_ldb);
1114 if (ret != LDB_SUCCESS) {
1118 ret = ldb_request(sam_ldb, req);
1119 if (ret == LDB_SUCCESS) {
1120 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1123 if (ret == LDB_SUCCESS) {
1124 return ldb_transaction_commit(sam_ldb);
1126 ldb_transaction_cancel(sam_ldb);
1132 return a default security descriptor
1134 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1136 struct security_descriptor *sd;
1138 sd = security_descriptor_initialise(mem_ctx);
1143 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1145 struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1146 struct ldb_dn *aggregate_dn;
1151 aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1152 if (!aggregate_dn) {
1155 if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1158 return aggregate_dn;
1161 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1163 struct ldb_dn *new_dn;
1165 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1166 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1167 talloc_free(new_dn);
1173 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1175 struct ldb_dn *new_dn;
1177 new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1178 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1179 talloc_free(new_dn);
1185 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1187 struct ldb_dn *new_dn;
1189 new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1190 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1191 talloc_free(new_dn);
1198 work out the domain sid for the current open ldb
1200 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1202 TALLOC_CTX *tmp_ctx;
1203 const struct dom_sid *domain_sid;
1204 const char *attrs[] = {
1208 struct ldb_result *res;
1211 /* see if we have a cached copy */
1212 domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1217 tmp_ctx = talloc_new(ldb);
1218 if (tmp_ctx == NULL) {
1222 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1224 if (ret != LDB_SUCCESS) {
1228 if (res->count != 1) {
1232 domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1233 if (domain_sid == NULL) {
1237 /* cache the domain_sid in the ldb */
1238 if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1242 talloc_steal(ldb, domain_sid);
1243 talloc_free(tmp_ctx);
1248 talloc_free(tmp_ctx);
1253 get domain sid from cache
1255 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1257 return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1260 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1262 TALLOC_CTX *tmp_ctx;
1263 struct dom_sid *dom_sid_new;
1264 struct dom_sid *dom_sid_old;
1266 /* see if we have a cached copy */
1267 dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1268 "cache.domain_sid"), struct dom_sid);
1270 tmp_ctx = talloc_new(ldb);
1271 if (tmp_ctx == NULL) {
1275 dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1280 /* cache the domain_sid in the ldb */
1281 if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1285 talloc_steal(ldb, dom_sid_new);
1286 talloc_free(tmp_ctx);
1287 talloc_free(dom_sid_old);
1292 DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1293 talloc_free(tmp_ctx);
1297 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1299 TALLOC_CTX *tmp_ctx;
1300 struct ldb_dn *ntds_settings_dn_new;
1301 struct ldb_dn *ntds_settings_dn_old;
1303 /* see if we have a forced copy from provision */
1304 ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb,
1305 "forced.ntds_settings_dn"), struct ldb_dn);
1307 tmp_ctx = talloc_new(ldb);
1308 if (tmp_ctx == NULL) {
1312 ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1313 if (!ntds_settings_dn_new) {
1317 /* set the DN in the ldb to avoid lookups during provision */
1318 if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1322 talloc_steal(ldb, ntds_settings_dn_new);
1323 talloc_free(tmp_ctx);
1324 talloc_free(ntds_settings_dn_old);
1329 DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1330 talloc_free(tmp_ctx);
1335 work out the ntds settings dn for the current open ldb
1337 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1339 TALLOC_CTX *tmp_ctx;
1340 const char *root_attrs[] = { "dsServiceName", NULL };
1342 struct ldb_result *root_res;
1343 struct ldb_dn *settings_dn;
1345 /* see if we have a cached copy */
1346 settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1348 return ldb_dn_copy(mem_ctx, settings_dn);
1351 tmp_ctx = talloc_new(mem_ctx);
1352 if (tmp_ctx == NULL) {
1356 ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1357 if (ret != LDB_SUCCESS) {
1358 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1359 ldb_errstring(ldb)));
1363 if (root_res->count != 1) {
1367 settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1369 /* note that we do not cache the DN here, as that would mean
1370 * we could not handle server renames at runtime. Only
1371 * provision sets up forced.ntds_settings_dn */
1373 talloc_steal(mem_ctx, settings_dn);
1374 talloc_free(tmp_ctx);
1379 DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1380 talloc_free(tmp_ctx);
1385 work out the ntds settings invocationId for the current open ldb
1387 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1389 TALLOC_CTX *tmp_ctx;
1390 const char *attrs[] = { "invocationId", NULL };
1392 struct ldb_result *res;
1393 struct GUID *invocation_id;
1395 /* see if we have a cached copy */
1396 invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1397 if (invocation_id) {
1398 SMB_ASSERT(!GUID_all_zero(invocation_id));
1399 return invocation_id;
1402 tmp_ctx = talloc_new(ldb);
1403 if (tmp_ctx == NULL) {
1407 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1412 if (res->count != 1) {
1416 invocation_id = talloc(tmp_ctx, struct GUID);
1417 if (!invocation_id) {
1421 *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1422 if (GUID_all_zero(invocation_id)) {
1423 if (ldb_msg_find_ldb_val(res->msgs[0], "invocationId")) {
1424 DEBUG(0, ("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1426 DEBUG(0, ("Failed to find parse own NTDS Settings invocationId from the ldb!\n"));
1431 /* cache the domain_sid in the ldb */
1432 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1436 talloc_steal(ldb, invocation_id);
1437 talloc_free(tmp_ctx);
1439 return invocation_id;
1442 DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1443 talloc_free(tmp_ctx);
1447 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1449 TALLOC_CTX *tmp_ctx;
1450 struct GUID *invocation_id_new;
1451 struct GUID *invocation_id_old;
1453 /* see if we have a cached copy */
1454 invocation_id_old = (struct GUID *)ldb_get_opaque(ldb,
1455 "cache.invocation_id");
1457 tmp_ctx = talloc_new(ldb);
1458 if (tmp_ctx == NULL) {
1462 invocation_id_new = talloc(tmp_ctx, struct GUID);
1463 if (!invocation_id_new) {
1467 SMB_ASSERT(!GUID_all_zero(invocation_id_in));
1468 *invocation_id_new = *invocation_id_in;
1470 /* cache the domain_sid in the ldb */
1471 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1475 talloc_steal(ldb, invocation_id_new);
1476 talloc_free(tmp_ctx);
1477 talloc_free(invocation_id_old);
1482 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1483 talloc_free(tmp_ctx);
1488 work out the ntds settings objectGUID for the current open ldb
1490 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1492 TALLOC_CTX *tmp_ctx;
1493 const char *attrs[] = { "objectGUID", NULL };
1495 struct ldb_result *res;
1496 struct GUID *ntds_guid;
1498 /* see if we have a cached copy */
1499 ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1504 tmp_ctx = talloc_new(ldb);
1505 if (tmp_ctx == NULL) {
1509 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1514 if (res->count != 1) {
1518 ntds_guid = talloc(tmp_ctx, struct GUID);
1523 *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1525 /* cache the domain_sid in the ldb */
1526 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1530 talloc_steal(ldb, ntds_guid);
1531 talloc_free(tmp_ctx);
1536 DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1537 talloc_free(tmp_ctx);
1541 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1543 TALLOC_CTX *tmp_ctx;
1544 struct GUID *ntds_guid_new;
1545 struct GUID *ntds_guid_old;
1547 /* see if we have a cached copy */
1548 ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1550 tmp_ctx = talloc_new(ldb);
1551 if (tmp_ctx == NULL) {
1555 ntds_guid_new = talloc(tmp_ctx, struct GUID);
1556 if (!ntds_guid_new) {
1560 *ntds_guid_new = *ntds_guid_in;
1562 /* cache the domain_sid in the ldb */
1563 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1567 talloc_steal(ldb, ntds_guid_new);
1568 talloc_free(tmp_ctx);
1569 talloc_free(ntds_guid_old);
1574 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1575 talloc_free(tmp_ctx);
1580 work out the server dn for the current open ldb
1582 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1584 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1589 dn = ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb, tmp_ctx));
1590 talloc_free(tmp_ctx);
1596 work out the server dn for the current open ldb
1598 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1600 struct ldb_dn *server_dn;
1601 struct ldb_dn *servers_dn;
1602 struct ldb_dn *server_site_dn;
1604 /* TODO: there must be a saner way to do this!! */
1605 server_dn = samdb_server_dn(ldb, mem_ctx);
1606 if (!server_dn) return NULL;
1608 servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1609 talloc_free(server_dn);
1610 if (!servers_dn) return NULL;
1612 server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1613 talloc_free(servers_dn);
1615 return server_site_dn;
1619 find the site name from a computers DN record
1621 int samdb_find_site_for_computer(struct ldb_context *ldb,
1622 TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1623 const char **site_name)
1627 const struct ldb_val *rdn_val;
1631 ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1632 if (ret != LDB_SUCCESS) {
1636 if (!ldb_dn_remove_child_components(dn, 2)) {
1638 return LDB_ERR_INVALID_DN_SYNTAX;
1641 rdn_val = ldb_dn_get_rdn_val(dn);
1642 if (rdn_val == NULL) {
1643 return LDB_ERR_OPERATIONS_ERROR;
1646 (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1649 return LDB_ERR_OPERATIONS_ERROR;
1655 find the NTDS GUID from a computers DN record
1657 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1658 struct GUID *ntds_guid)
1663 *ntds_guid = GUID_zero();
1665 ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1666 if (ret != LDB_SUCCESS) {
1670 if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1672 return LDB_ERR_OPERATIONS_ERROR;
1675 ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1681 find a 'reference' DN that points at another object
1682 (eg. serverReference, rIDManagerReference etc)
1684 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1685 const char *attribute, struct ldb_dn **dn)
1687 const char *attrs[2];
1688 struct ldb_result *res;
1691 attrs[0] = attribute;
1694 ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY|DSDB_SEARCH_SHOW_EXTENDED_DN, NULL);
1695 if (ret != LDB_SUCCESS) {
1696 ldb_asprintf_errstring(ldb, "Cannot find DN %s to get attribute %s for reference dn: %s",
1697 ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb));
1701 *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1703 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1704 ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1705 ldb_dn_get_linearized(base));
1707 ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1708 ldb_dn_get_linearized(base));
1711 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1719 find if a DN (must have GUID component!) is our ntdsDsa
1721 int samdb_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *dn, bool *is_ntdsa)
1724 struct GUID dn_guid;
1725 const struct GUID *our_ntds_guid;
1726 status = dsdb_get_extended_dn_guid(dn, &dn_guid, "GUID");
1727 if (!NT_STATUS_IS_OK(status)) {
1728 return LDB_ERR_OPERATIONS_ERROR;
1731 our_ntds_guid = samdb_ntds_objectGUID(ldb);
1732 if (!our_ntds_guid) {
1733 DEBUG(0, ("Failed to find our NTDS Settings GUID for comparison with %s - %s\n", ldb_dn_get_linearized(dn), ldb_errstring(ldb)));
1734 return LDB_ERR_OPERATIONS_ERROR;
1737 *is_ntdsa = GUID_equal(&dn_guid, our_ntds_guid);
1742 find a 'reference' DN that points at another object and indicate if it is our ntdsDsa
1744 int samdb_reference_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *base,
1745 const char *attribute, bool *is_ntdsa)
1748 struct ldb_dn *referenced_dn;
1749 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1750 if (tmp_ctx == NULL) {
1751 return LDB_ERR_OPERATIONS_ERROR;
1753 ret = samdb_reference_dn(ldb, tmp_ctx, base, attribute, &referenced_dn);
1754 if (ret != LDB_SUCCESS) {
1755 DEBUG(0, ("Failed to find object %s for attribute %s - %s\n", ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb)));
1759 ret = samdb_dn_is_our_ntdsa(ldb, referenced_dn, is_ntdsa);
1761 talloc_free(tmp_ctx);
1766 find our machine account via the serverReference attribute in the
1769 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1771 struct ldb_dn *server_dn;
1774 server_dn = samdb_server_dn(ldb, mem_ctx);
1775 if (server_dn == NULL) {
1776 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
1779 ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1780 talloc_free(server_dn);
1786 find the RID Manager$ DN via the rIDManagerReference attribute in the
1789 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1791 return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1792 "rIDManagerReference", dn);
1796 find the RID Set DN via the rIDSetReferences attribute in our
1799 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1801 struct ldb_dn *server_ref_dn;
1804 ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1805 if (ret != LDB_SUCCESS) {
1808 ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1809 talloc_free(server_ref_dn);
1813 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1815 const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1822 return (const char *) val->data;
1826 * Finds the client site by using the client's IP address.
1827 * The "subnet_name" returns the name of the subnet if parameter != NULL
1829 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1830 const char *ip_address, char **subnet_name)
1832 const char *attrs[] = { "cn", "siteObject", NULL };
1833 struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1834 struct ldb_result *res;
1835 const struct ldb_val *val;
1836 const char *site_name = NULL, *l_subnet_name = NULL;
1837 const char *allow_list[2] = { NULL, NULL };
1838 unsigned int i, count;
1842 * if we don't have a client ip e.g. ncalrpc
1843 * the server site is the client site
1845 if (ip_address == NULL) {
1846 return samdb_server_site_name(ldb, mem_ctx);
1849 sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1850 if (sites_container_dn == NULL) {
1854 subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1855 if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1856 talloc_free(sites_container_dn);
1857 talloc_free(subnets_dn);
1861 ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1863 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1865 } else if (ret != LDB_SUCCESS) {
1866 talloc_free(sites_container_dn);
1867 talloc_free(subnets_dn);
1873 for (i = 0; i < count; i++) {
1874 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1877 allow_list[0] = l_subnet_name;
1879 if (allow_access_nolog(NULL, allow_list, "", ip_address)) {
1880 sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1883 if (sites_dn == NULL) {
1884 /* No reference, maybe another subnet matches */
1888 /* "val" cannot be NULL here since "sites_dn" != NULL */
1889 val = ldb_dn_get_rdn_val(sites_dn);
1890 site_name = talloc_strdup(mem_ctx,
1891 (const char *) val->data);
1893 talloc_free(sites_dn);
1899 if (site_name == NULL) {
1900 /* This is the Windows Server fallback rule: when no subnet
1901 * exists and we have only one site available then use it (it
1902 * is for sure the same as our server site). If more sites do
1903 * exist then we don't know which one to use and set the site
1905 cnt = samdb_search_count(ldb, mem_ctx, sites_container_dn,
1906 "(objectClass=site)");
1908 site_name = samdb_server_site_name(ldb, mem_ctx);
1910 site_name = talloc_strdup(mem_ctx, "");
1912 l_subnet_name = NULL;
1915 if (subnet_name != NULL) {
1916 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1919 talloc_free(sites_container_dn);
1920 talloc_free(subnets_dn);
1927 work out if we are the PDC for the domain of the current open ldb
1929 bool samdb_is_pdc(struct ldb_context *ldb)
1934 ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner",
1936 if (ret != LDB_SUCCESS) {
1937 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n",
1938 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
1939 ldb_errstring(ldb)));
1947 work out if we are a Global Catalog server for the domain of the current open ldb
1949 bool samdb_is_gc(struct ldb_context *ldb)
1952 if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
1955 return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
1958 /* Find a domain object in the parents of a particular DN. */
1959 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1960 struct ldb_dn **parent_dn, const char **errstring)
1962 TALLOC_CTX *local_ctx;
1963 struct ldb_dn *sdn = dn;
1964 struct ldb_result *res = NULL;
1965 int ret = LDB_SUCCESS;
1966 const char *attrs[] = { NULL };
1968 local_ctx = talloc_new(mem_ctx);
1969 if (local_ctx == NULL) return ldb_oom(ldb);
1971 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1972 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1973 "(|(objectClass=domain)(objectClass=builtinDomain))");
1974 if (ret == LDB_SUCCESS) {
1975 if (res->count == 1) {
1983 if (ret != LDB_SUCCESS) {
1984 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1985 ldb_dn_get_linearized(dn),
1986 ldb_dn_get_linearized(sdn),
1987 ldb_errstring(ldb));
1988 talloc_free(local_ctx);
1991 if (res->count != 1) {
1992 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1993 ldb_dn_get_linearized(dn));
1994 DEBUG(0,(__location__ ": %s\n", *errstring));
1995 talloc_free(local_ctx);
1996 return LDB_ERR_CONSTRAINT_VIOLATION;
1999 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2000 talloc_free(local_ctx);
2004 static void pwd_timeout_debug(struct tevent_context *unused1,
2005 struct tevent_timer *unused2,
2006 struct timeval unused3,
2009 DEBUG(0, ("WARNING: check_password_complexity: password script "
2010 "took more than 1 second to run\n"));
2015 * Performs checks on a user password (plaintext UNIX format - attribute
2016 * "password"). The remaining parameters have to be extracted from the domain
2019 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
2021 enum samr_ValidationStatus samdb_check_password(TALLOC_CTX *mem_ctx,
2022 struct loadparm_context *lp_ctx,
2023 const DATA_BLOB *utf8_blob,
2024 const uint32_t pwdProperties,
2025 const uint32_t minPwdLength)
2027 const char *utf8_pw = (const char *)utf8_blob->data;
2028 size_t utf8_len = strlen_m(utf8_pw);
2029 char *password_script = NULL;
2031 /* checks if the "minPwdLength" property is satisfied */
2032 if (minPwdLength > utf8_len) {
2033 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2036 /* checks the password complexity */
2037 if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
2038 return SAMR_VALIDATION_STATUS_SUCCESS;
2041 if (utf8_len == 0) {
2042 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2045 password_script = lpcfg_check_password_script(lp_ctx, mem_ctx);
2046 if (password_script != NULL && *password_script != '\0') {
2049 struct tevent_context *event_ctx = NULL;
2050 struct tevent_req *req = NULL;
2051 struct samba_runcmd_state *run_cmd = NULL;
2052 const char * const cmd[4] = {
2058 event_ctx = tevent_context_init(mem_ctx);
2059 if (event_ctx == NULL) {
2060 TALLOC_FREE(password_script);
2061 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2064 /* Gives a warning after 1 second, terminates after 10 */
2065 tevent_add_timer(event_ctx, event_ctx,
2066 tevent_timeval_current_ofs(1, 0),
2067 pwd_timeout_debug, NULL);
2069 req = samba_runcmd_send(event_ctx, event_ctx,
2070 tevent_timeval_current_ofs(10, 0),
2071 100, 100, cmd, NULL);
2072 run_cmd = tevent_req_data(req, struct samba_runcmd_state);
2073 if (write(run_cmd->fd_stdin, utf8_pw, utf8_len) != utf8_len) {
2074 TALLOC_FREE(password_script);
2075 TALLOC_FREE(event_ctx);
2076 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2079 close(run_cmd->fd_stdin);
2080 run_cmd->fd_stdin = -1;
2082 if (!tevent_req_poll(req, event_ctx)) {
2083 TALLOC_FREE(password_script);
2084 TALLOC_FREE(event_ctx);
2085 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2088 check_ret = samba_runcmd_recv(req, &error);
2089 TALLOC_FREE(event_ctx);
2091 if (error == ETIMEDOUT) {
2092 DEBUG(0, ("check_password_complexity: check password script took too long!\n"));
2093 TALLOC_FREE(password_script);
2094 return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2096 DEBUG(5,("check_password_complexity: check password script (%s) "
2097 "returned [%d]\n", password_script, check_ret));
2099 if (check_ret != 0) {
2100 DEBUG(1,("check_password_complexity: "
2101 "check password script said new password is not good "
2103 TALLOC_FREE(password_script);
2104 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2108 TALLOC_FREE(password_script);
2109 return SAMR_VALIDATION_STATUS_SUCCESS;
2112 TALLOC_FREE(password_script);
2114 if (!check_password_quality(utf8_pw)) {
2115 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2118 return SAMR_VALIDATION_STATUS_SUCCESS;
2122 * Callback for "samdb_set_password" password change
2124 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2129 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2132 if (ares->error != LDB_SUCCESS) {
2134 req->context = talloc_steal(req,
2135 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2137 return ldb_request_done(req, ret);
2140 if (ares->type != LDB_REPLY_DONE) {
2142 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2145 req->context = talloc_steal(req,
2146 ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2148 return ldb_request_done(req, LDB_SUCCESS);
2152 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2153 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2154 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2155 * user change or not. The "rejectReason" gives some more information if the
2158 * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2159 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2161 static NTSTATUS samdb_set_password_internal(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2162 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2163 const DATA_BLOB *new_password,
2164 const struct samr_Password *lmNewHash,
2165 const struct samr_Password *ntNewHash,
2166 const struct samr_Password *lmOldHash,
2167 const struct samr_Password *ntOldHash,
2168 enum samPwdChangeReason *reject_reason,
2169 struct samr_DomInfo1 **_dominfo,
2170 bool permit_interdomain_trust)
2172 struct ldb_message *msg;
2173 struct ldb_message_element *el;
2174 struct ldb_request *req;
2175 struct dsdb_control_password_change_status *pwd_stat = NULL;
2177 bool hash_values = false;
2178 NTSTATUS status = NT_STATUS_OK;
2180 #define CHECK_RET(x) \
2181 if (x != LDB_SUCCESS) { \
2183 return NT_STATUS_NO_MEMORY; \
2186 msg = ldb_msg_new(mem_ctx);
2188 return NT_STATUS_NO_MEMORY;
2191 if ((new_password != NULL)
2192 && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2193 /* we have the password as plaintext UTF16 */
2194 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2195 new_password, NULL));
2196 el = ldb_msg_find_element(msg, "clearTextPassword");
2197 el->flags = LDB_FLAG_MOD_REPLACE;
2198 } else if ((new_password == NULL)
2199 && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2200 /* we have a password as LM and/or NT hash */
2201 if (lmNewHash != NULL) {
2202 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2203 "dBCSPwd", lmNewHash));
2204 el = ldb_msg_find_element(msg, "dBCSPwd");
2205 el->flags = LDB_FLAG_MOD_REPLACE;
2207 if (ntNewHash != NULL) {
2208 CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2209 "unicodePwd", ntNewHash));
2210 el = ldb_msg_find_element(msg, "unicodePwd");
2211 el->flags = LDB_FLAG_MOD_REPLACE;
2215 /* the password wasn't specified correctly */
2217 return NT_STATUS_INVALID_PARAMETER;
2220 /* build modify request */
2221 ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2222 samdb_set_password_callback, NULL);
2223 if (ret != LDB_SUCCESS) {
2225 return NT_STATUS_NO_MEMORY;
2228 /* A password change operation */
2229 if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2230 struct dsdb_control_password_change *change;
2232 change = talloc(req, struct dsdb_control_password_change);
2233 if (change == NULL) {
2236 return NT_STATUS_NO_MEMORY;
2239 change->old_nt_pwd_hash = ntOldHash;
2240 change->old_lm_pwd_hash = lmOldHash;
2242 ret = ldb_request_add_control(req,
2243 DSDB_CONTROL_PASSWORD_CHANGE_OID,
2245 if (ret != LDB_SUCCESS) {
2248 return NT_STATUS_NO_MEMORY;
2252 ret = ldb_request_add_control(req,
2253 DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2255 if (ret != LDB_SUCCESS) {
2258 return NT_STATUS_NO_MEMORY;
2261 if (permit_interdomain_trust) {
2262 ret = ldb_request_add_control(req,
2263 DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
2265 if (ret != LDB_SUCCESS) {
2268 return NT_STATUS_NO_MEMORY;
2271 ret = ldb_request_add_control(req,
2272 DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2274 if (ret != LDB_SUCCESS) {
2277 return NT_STATUS_NO_MEMORY;
2280 ret = dsdb_autotransaction_request(ldb, req);
2282 if (req->context != NULL) {
2283 struct ldb_control *control = talloc_get_type_abort(req->context,
2284 struct ldb_control);
2285 pwd_stat = talloc_get_type_abort(control->data,
2286 struct dsdb_control_password_change_status);
2287 talloc_steal(mem_ctx, pwd_stat);
2293 /* Sets the domain info (if requested) */
2294 if (_dominfo != NULL) {
2295 struct samr_DomInfo1 *dominfo;
2297 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2298 if (dominfo == NULL) {
2299 return NT_STATUS_NO_MEMORY;
2302 if (pwd_stat != NULL) {
2303 dominfo->min_password_length = pwd_stat->domain_data.minPwdLength;
2304 dominfo->password_properties = pwd_stat->domain_data.pwdProperties;
2305 dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2306 dominfo->max_password_age = pwd_stat->domain_data.maxPwdAge;
2307 dominfo->min_password_age = pwd_stat->domain_data.minPwdAge;
2310 *_dominfo = dominfo;
2313 if (reject_reason != NULL) {
2314 if (pwd_stat != NULL) {
2315 *reject_reason = pwd_stat->reject_reason;
2317 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2321 if (pwd_stat != NULL) {
2322 talloc_free(pwd_stat);
2325 if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2326 const char *errmsg = ldb_errstring(ldb);
2327 char *endptr = NULL;
2328 WERROR werr = WERR_GEN_FAILURE;
2329 status = NT_STATUS_UNSUCCESSFUL;
2330 if (errmsg != NULL) {
2331 werr = W_ERROR(strtol(errmsg, &endptr, 16));
2332 DBG_WARNING("%s\n", errmsg);
2334 if (endptr != errmsg) {
2335 if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2336 status = NT_STATUS_WRONG_PASSWORD;
2338 if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2339 status = NT_STATUS_PASSWORD_RESTRICTION;
2342 } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2343 /* don't let the caller know if an account doesn't exist */
2344 status = NT_STATUS_WRONG_PASSWORD;
2345 } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2346 status = NT_STATUS_ACCESS_DENIED;
2347 } else if (ret != LDB_SUCCESS) {
2348 DEBUG(1, ("Failed to set password on %s: %s\n",
2349 ldb_dn_get_linearized(user_dn),
2350 ldb_errstring(ldb)));
2351 status = NT_STATUS_UNSUCCESSFUL;
2357 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2358 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2359 const DATA_BLOB *new_password,
2360 const struct samr_Password *lmNewHash,
2361 const struct samr_Password *ntNewHash,
2362 const struct samr_Password *lmOldHash,
2363 const struct samr_Password *ntOldHash,
2364 enum samPwdChangeReason *reject_reason,
2365 struct samr_DomInfo1 **_dominfo)
2367 return samdb_set_password_internal(ldb, mem_ctx,
2370 lmNewHash, ntNewHash,
2371 lmOldHash, ntOldHash,
2372 reject_reason, _dominfo,
2373 false); /* reject trusts */
2377 * Sets the user password using plaintext UTF16 (attribute "new_password") or
2378 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2379 * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2380 * user change or not. The "rejectReason" gives some more information if the
2383 * This wrapper function for "samdb_set_password" takes a SID as input rather
2386 * This call encapsulates a new LDB transaction for changing the password;
2387 * therefore the user hasn't to start a new one.
2389 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2390 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2391 * NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2392 * NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2394 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2395 const struct dom_sid *user_sid,
2396 const uint32_t *new_version, /* optional for trusts */
2397 const DATA_BLOB *new_password,
2398 const struct samr_Password *lmNewHash,
2399 const struct samr_Password *ntNewHash,
2400 const struct samr_Password *lmOldHash,
2401 const struct samr_Password *ntOldHash,
2402 enum samPwdChangeReason *reject_reason,
2403 struct samr_DomInfo1 **_dominfo)
2405 TALLOC_CTX *frame = talloc_stackframe();
2407 const char * const user_attrs[] = {
2408 "userAccountControl",
2412 struct ldb_message *user_msg = NULL;
2416 ret = ldb_transaction_start(ldb);
2417 if (ret != LDB_SUCCESS) {
2418 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2420 return NT_STATUS_TRANSACTION_ABORTED;
2423 ret = dsdb_search_one(ldb, frame, &user_msg, ldb_get_default_basedn(ldb),
2424 LDB_SCOPE_SUBTREE, user_attrs, 0,
2425 "(&(objectSid=%s)(objectClass=user))",
2426 ldap_encode_ndr_dom_sid(frame, user_sid));
2427 if (ret != LDB_SUCCESS) {
2428 ldb_transaction_cancel(ldb);
2429 DEBUG(3, ("samdb_set_password_sid: SID[%s] not found in samdb %s - %s, "
2430 "returning NO_SUCH_USER\n",
2431 dom_sid_string(frame, user_sid),
2432 ldb_strerror(ret), ldb_errstring(ldb)));
2434 return NT_STATUS_NO_SUCH_USER;
2437 uac = ldb_msg_find_attr_as_uint(user_msg, "userAccountControl", 0);
2438 if (!(uac & UF_ACCOUNT_TYPE_MASK)) {
2439 ldb_transaction_cancel(ldb);
2440 DEBUG(1, ("samdb_set_password_sid: invalid "
2441 "userAccountControl[0x%08X] for SID[%s] DN[%s], "
2442 "returning NO_SUCH_USER\n",
2443 (unsigned)uac, dom_sid_string(frame, user_sid),
2444 ldb_dn_get_linearized(user_msg->dn)));
2446 return NT_STATUS_NO_SUCH_USER;
2449 if (uac & UF_INTERDOMAIN_TRUST_ACCOUNT) {
2450 const char * const tdo_attrs[] = {
2451 "trustAuthIncoming",
2455 struct ldb_message *tdo_msg = NULL;
2456 const char *account_name = NULL;
2457 uint32_t trust_direction;
2459 const struct ldb_val *old_val = NULL;
2460 struct trustAuthInOutBlob old_blob = {};
2461 uint32_t old_version = 0;
2462 struct AuthenticationInformation *old_version_a = NULL;
2463 uint32_t _new_version = 0;
2464 struct trustAuthInOutBlob new_blob = {};
2465 struct ldb_val new_val = {};
2466 struct timeval tv = timeval_current();
2467 NTTIME now = timeval_to_nttime(&tv);
2468 enum ndr_err_code ndr_err;
2470 if (new_password == NULL && ntNewHash == NULL) {
2471 ldb_transaction_cancel(ldb);
2472 DEBUG(1, ("samdb_set_password_sid: "
2473 "no new password provided "
2474 "sAMAccountName for SID[%s] DN[%s], "
2475 "returning INVALID_PARAMETER\n",
2476 dom_sid_string(frame, user_sid),
2477 ldb_dn_get_linearized(user_msg->dn)));
2479 return NT_STATUS_INVALID_PARAMETER;
2482 if (new_password != NULL && ntNewHash != NULL) {
2483 ldb_transaction_cancel(ldb);
2484 DEBUG(1, ("samdb_set_password_sid: "
2485 "two new passwords provided "
2486 "sAMAccountName for SID[%s] DN[%s], "
2487 "returning INVALID_PARAMETER\n",
2488 dom_sid_string(frame, user_sid),
2489 ldb_dn_get_linearized(user_msg->dn)));
2491 return NT_STATUS_INVALID_PARAMETER;
2494 if (new_password != NULL && (new_password->length % 2)) {
2495 ldb_transaction_cancel(ldb);
2496 DEBUG(2, ("samdb_set_password_sid: "
2497 "invalid utf16 length (%zu) "
2498 "sAMAccountName for SID[%s] DN[%s], "
2499 "returning WRONG_PASSWORD\n",
2500 new_password->length,
2501 dom_sid_string(frame, user_sid),
2502 ldb_dn_get_linearized(user_msg->dn)));
2504 return NT_STATUS_WRONG_PASSWORD;
2507 if (new_password != NULL && new_password->length >= 500) {
2508 ldb_transaction_cancel(ldb);
2509 DEBUG(2, ("samdb_set_password_sid: "
2510 "utf16 password too long (%zu) "
2511 "sAMAccountName for SID[%s] DN[%s], "
2512 "returning WRONG_PASSWORD\n",
2513 new_password->length,
2514 dom_sid_string(frame, user_sid),
2515 ldb_dn_get_linearized(user_msg->dn)));
2517 return NT_STATUS_WRONG_PASSWORD;
2520 account_name = ldb_msg_find_attr_as_string(user_msg,
2521 "sAMAccountName", NULL);
2522 if (account_name == NULL) {
2523 ldb_transaction_cancel(ldb);
2524 DEBUG(1, ("samdb_set_password_sid: missing "
2525 "sAMAccountName for SID[%s] DN[%s], "
2526 "returning NO_SUCH_USER\n",
2527 dom_sid_string(frame, user_sid),
2528 ldb_dn_get_linearized(user_msg->dn)));
2530 return NT_STATUS_NO_SUCH_USER;
2533 nt_status = dsdb_trust_search_tdo_by_type(ldb,
2538 if (!NT_STATUS_IS_OK(nt_status)) {
2539 ldb_transaction_cancel(ldb);
2540 DEBUG(1, ("samdb_set_password_sid: dsdb_trust_search_tdo "
2541 "failed(%s) for sAMAccountName[%s] SID[%s] DN[%s], "
2542 "returning INTERNAL_DB_CORRUPTION\n",
2543 nt_errstr(nt_status), account_name,
2544 dom_sid_string(frame, user_sid),
2545 ldb_dn_get_linearized(user_msg->dn)));
2547 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2550 trust_direction = ldb_msg_find_attr_as_int(tdo_msg,
2551 "trustDirection", 0);
2552 if (!(trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {
2553 ldb_transaction_cancel(ldb);
2554 DEBUG(1, ("samdb_set_password_sid: direction[0x%08X] is "
2555 "not inbound for sAMAccountName[%s] "
2557 "returning INTERNAL_DB_CORRUPTION\n",
2558 (unsigned)trust_direction,
2560 ldb_dn_get_linearized(user_msg->dn),
2561 ldb_dn_get_linearized(tdo_msg->dn)));
2563 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2566 old_val = ldb_msg_find_ldb_val(tdo_msg, "trustAuthIncoming");
2567 if (old_val != NULL) {
2568 ndr_err = ndr_pull_struct_blob(old_val, frame, &old_blob,
2569 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2570 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2571 ldb_transaction_cancel(ldb);
2572 DEBUG(1, ("samdb_set_password_sid: "
2573 "failed(%s) to parse "
2574 "trustAuthOutgoing sAMAccountName[%s] "
2576 "returning INTERNAL_DB_CORRUPTION\n",
2577 ndr_map_error2string(ndr_err),
2579 ldb_dn_get_linearized(user_msg->dn),
2580 ldb_dn_get_linearized(tdo_msg->dn)));
2583 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2587 for (i = old_blob.current.count; i > 0; i--) {
2588 struct AuthenticationInformation *a =
2589 &old_blob.current.array[i - 1];
2591 switch (a->AuthType) {
2592 case TRUST_AUTH_TYPE_NONE:
2593 if (i == old_blob.current.count) {
2595 * remove TRUST_AUTH_TYPE_NONE at the
2598 old_blob.current.count--;
2602 case TRUST_AUTH_TYPE_VERSION:
2604 old_version = a->AuthInfo.version.version;
2607 case TRUST_AUTH_TYPE_CLEAR:
2610 case TRUST_AUTH_TYPE_NT4OWF:
2615 if (new_version == NULL) {
2617 new_version = &_new_version;
2620 if (old_version_a != NULL && *new_version != (old_version + 1)) {
2621 old_version_a->LastUpdateTime = now;
2622 old_version_a->AuthType = TRUST_AUTH_TYPE_NONE;
2625 new_blob.count = MAX(old_blob.current.count, 2);
2626 new_blob.current.array = talloc_zero_array(frame,
2627 struct AuthenticationInformation,
2629 if (new_blob.current.array == NULL) {
2630 ldb_transaction_cancel(ldb);
2632 return NT_STATUS_NO_MEMORY;
2634 new_blob.previous.array = talloc_zero_array(frame,
2635 struct AuthenticationInformation,
2637 if (new_blob.current.array == NULL) {
2638 ldb_transaction_cancel(ldb);
2640 return NT_STATUS_NO_MEMORY;
2643 for (i = 0; i < old_blob.current.count; i++) {
2644 struct AuthenticationInformation *o =
2645 &old_blob.current.array[i];
2646 struct AuthenticationInformation *p =
2647 &new_blob.previous.array[i];
2650 new_blob.previous.count++;
2652 for (; i < new_blob.count; i++) {
2653 struct AuthenticationInformation *pi =
2654 &new_blob.previous.array[i];
2658 * new_blob.previous is still empty so
2659 * we'll do new_blob.previous = new_blob.current
2665 pi->LastUpdateTime = now;
2666 pi->AuthType = TRUST_AUTH_TYPE_NONE;
2667 new_blob.previous.count++;
2670 for (i = 0; i < new_blob.count; i++) {
2671 struct AuthenticationInformation *ci =
2672 &new_blob.current.array[i];
2674 ci->LastUpdateTime = now;
2677 if (ntNewHash != NULL) {
2678 ci->AuthType = TRUST_AUTH_TYPE_NT4OWF;
2679 ci->AuthInfo.nt4owf.password = *ntNewHash;
2683 ci->AuthType = TRUST_AUTH_TYPE_CLEAR;
2684 ci->AuthInfo.clear.size = new_password->length;
2685 ci->AuthInfo.clear.password = new_password->data;
2688 ci->AuthType = TRUST_AUTH_TYPE_VERSION;
2689 ci->AuthInfo.version.version = *new_version;
2692 ci->AuthType = TRUST_AUTH_TYPE_NONE;
2696 new_blob.current.count++;
2699 if (new_blob.previous.count == 0) {
2700 TALLOC_FREE(new_blob.previous.array);
2701 new_blob.previous = new_blob.current;
2704 ndr_err = ndr_push_struct_blob(&new_val, frame, &new_blob,
2705 (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2706 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2707 ldb_transaction_cancel(ldb);
2708 DEBUG(1, ("samdb_set_password_sid: "
2709 "failed(%s) to generate "
2710 "trustAuthOutgoing sAMAccountName[%s] "
2712 "returning UNSUCCESSFUL\n",
2713 ndr_map_error2string(ndr_err),
2715 ldb_dn_get_linearized(user_msg->dn),
2716 ldb_dn_get_linearized(tdo_msg->dn)));
2718 return NT_STATUS_UNSUCCESSFUL;
2721 tdo_msg->num_elements = 0;
2722 TALLOC_FREE(tdo_msg->elements);
2724 ret = ldb_msg_add_empty(tdo_msg, "trustAuthIncoming",
2725 LDB_FLAG_MOD_REPLACE, NULL);
2726 if (ret != LDB_SUCCESS) {
2727 ldb_transaction_cancel(ldb);
2729 return NT_STATUS_NO_MEMORY;
2731 ret = ldb_msg_add_value(tdo_msg, "trustAuthIncoming",
2733 if (ret != LDB_SUCCESS) {
2734 ldb_transaction_cancel(ldb);
2736 return NT_STATUS_NO_MEMORY;
2739 ret = ldb_modify(ldb, tdo_msg);
2740 if (ret != LDB_SUCCESS) {
2741 nt_status = dsdb_ldb_err_to_ntstatus(ret);
2742 ldb_transaction_cancel(ldb);
2743 DEBUG(1, ("samdb_set_password_sid: "
2744 "failed to replace "
2745 "trustAuthOutgoing sAMAccountName[%s] "
2749 ldb_dn_get_linearized(user_msg->dn),
2750 ldb_dn_get_linearized(tdo_msg->dn),
2751 nt_errstr(nt_status), ldb_errstring(ldb)));
2757 nt_status = samdb_set_password_internal(ldb, mem_ctx,
2760 lmNewHash, ntNewHash,
2761 lmOldHash, ntOldHash,
2762 reject_reason, _dominfo,
2763 true); /* permit trusts */
2764 if (!NT_STATUS_IS_OK(nt_status)) {
2765 ldb_transaction_cancel(ldb);
2770 ret = ldb_transaction_commit(ldb);
2771 if (ret != LDB_SUCCESS) {
2772 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2773 ldb_dn_get_linearized(user_msg->dn),
2774 ldb_errstring(ldb)));
2776 return NT_STATUS_TRANSACTION_ABORTED;
2780 return NT_STATUS_OK;
2784 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
2785 struct dom_sid *sid, struct ldb_dn **ret_dn)
2787 struct ldb_message *msg;
2788 struct ldb_dn *basedn;
2792 sidstr = dom_sid_string(mem_ctx, sid);
2793 NT_STATUS_HAVE_NO_MEMORY(sidstr);
2795 /* We might have to create a ForeignSecurityPrincipal, even if this user
2796 * is in our own domain */
2798 msg = ldb_msg_new(sidstr);
2800 talloc_free(sidstr);
2801 return NT_STATUS_NO_MEMORY;
2804 ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2805 ldb_get_default_basedn(sam_ctx),
2806 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2808 if (ret != LDB_SUCCESS) {
2809 DEBUG(0, ("Failed to find DN for "
2810 "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2811 talloc_free(sidstr);
2812 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2815 /* add core elements to the ldb_message for the alias */
2817 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2818 talloc_free(sidstr);
2819 return NT_STATUS_NO_MEMORY;
2822 ret = ldb_msg_add_string(msg, "objectClass",
2823 "foreignSecurityPrincipal");
2824 if (ret != LDB_SUCCESS) {
2825 talloc_free(sidstr);
2826 return NT_STATUS_NO_MEMORY;
2829 /* create the alias */
2830 ret = ldb_add(sam_ctx, msg);
2831 if (ret != LDB_SUCCESS) {
2832 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2834 ldb_dn_get_linearized(msg->dn),
2835 ldb_errstring(sam_ctx)));
2836 talloc_free(sidstr);
2837 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2840 *ret_dn = talloc_steal(mem_ctx, msg->dn);
2841 talloc_free(sidstr);
2843 return NT_STATUS_OK;
2848 Find the DN of a domain, assuming it to be a dotted.dns name
2851 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
2854 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2855 const char *binary_encoded;
2856 const char * const *split_realm;
2863 split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
2865 talloc_free(tmp_ctx);
2868 dn = ldb_dn_new(mem_ctx, ldb, NULL);
2869 for (i=0; split_realm[i]; i++) {
2870 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2871 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2872 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2873 binary_encoded, ldb_dn_get_linearized(dn)));
2874 talloc_free(tmp_ctx);
2878 if (!ldb_dn_validate(dn)) {
2879 DEBUG(2, ("Failed to validated DN %s\n",
2880 ldb_dn_get_linearized(dn)));
2881 talloc_free(tmp_ctx);
2884 talloc_free(tmp_ctx);
2890 Find the DNS equivalent of a DN, in dotted DNS form
2892 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
2894 int i, num_components = ldb_dn_get_comp_num(dn);
2895 char *dns_name = talloc_strdup(mem_ctx, "");
2896 if (dns_name == NULL) {
2900 for (i=0; i<num_components; i++) {
2901 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
2904 talloc_free(dns_name);
2907 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
2908 (int)v->length, (int)v->length, (char *)v->data);
2910 talloc_free(dns_name);
2916 /* remove the last '.' */
2917 if (dns_name[0] != 0) {
2918 dns_name[strlen(dns_name)-1] = 0;
2925 Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
2926 name is based on the forest DNS name
2928 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
2929 TALLOC_CTX *mem_ctx,
2930 const struct GUID *ntds_guid)
2932 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2933 const char *guid_str;
2934 struct ldb_dn *forest_dn;
2935 const char *dnsforest;
2938 guid_str = GUID_string(tmp_ctx, ntds_guid);
2939 if (guid_str == NULL) {
2940 talloc_free(tmp_ctx);
2943 forest_dn = ldb_get_root_basedn(samdb);
2944 if (forest_dn == NULL) {
2945 talloc_free(tmp_ctx);
2948 dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
2949 if (dnsforest == NULL) {
2950 talloc_free(tmp_ctx);
2953 ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
2954 talloc_free(tmp_ctx);
2960 Find the DN of a domain, be it the netbios or DNS name
2962 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2963 const char *domain_name)
2965 const char * const domain_ref_attrs[] = {
2968 const char * const domain_ref2_attrs[] = {
2971 struct ldb_result *res_domain_ref;
2972 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2973 /* find the domain's DN */
2974 int ret_domain = ldb_search(ldb, mem_ctx,
2976 samdb_partitions_dn(ldb, mem_ctx),
2979 "(&(nETBIOSName=%s)(objectclass=crossRef))",
2981 if (ret_domain != LDB_SUCCESS) {
2985 if (res_domain_ref->count == 0) {
2986 ret_domain = ldb_search(ldb, mem_ctx,
2988 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2991 "(objectclass=domain)");
2992 if (ret_domain != LDB_SUCCESS) {
2996 if (res_domain_ref->count == 1) {
2997 return res_domain_ref->msgs[0]->dn;
3002 if (res_domain_ref->count > 1) {
3003 DEBUG(0,("Found %d records matching domain [%s]\n",
3004 ret_domain, domain_name));
3008 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
3014 use a GUID to find a DN
3016 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
3017 TALLOC_CTX *mem_ctx,
3018 const struct GUID *guid,
3019 uint32_t dsdb_flags,
3023 struct ldb_result *res;
3024 const char *attrs[] = { NULL };
3025 char *guid_str = GUID_string(mem_ctx, guid);
3028 return ldb_operr(ldb);
3031 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3032 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3033 DSDB_SEARCH_SHOW_EXTENDED_DN |
3034 DSDB_SEARCH_ONE_ONLY | dsdb_flags,
3035 "objectGUID=%s", guid_str);
3036 talloc_free(guid_str);
3037 if (ret != LDB_SUCCESS) {
3041 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3048 use a DN to find a GUID with a given attribute name
3050 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
3051 struct ldb_dn *dn, const char *attribute,
3055 struct ldb_result *res;
3056 const char *attrs[2];
3057 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3059 attrs[0] = attribute;
3062 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3063 DSDB_SEARCH_SHOW_DELETED |
3064 DSDB_SEARCH_SHOW_RECYCLED);
3065 if (ret != LDB_SUCCESS) {
3066 talloc_free(tmp_ctx);
3069 if (res->count < 1) {
3070 talloc_free(tmp_ctx);
3071 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3073 *guid = samdb_result_guid(res->msgs[0], attribute);
3074 talloc_free(tmp_ctx);
3079 use a DN to find a GUID
3081 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
3082 struct ldb_dn *dn, struct GUID *guid)
3084 return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
3090 adds the given GUID to the given ldb_message. This value is added
3091 for the given attr_name (may be either "objectGUID" or "parentGUID").
3093 int dsdb_msg_add_guid(struct ldb_message *msg,
3095 const char *attr_name)
3100 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
3102 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
3103 if (!NT_STATUS_IS_OK(status)) {
3104 ret = LDB_ERR_OPERATIONS_ERROR;
3108 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
3109 if (ret != LDB_SUCCESS) {
3110 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
3118 talloc_free(tmp_ctx);
3125 use a DN to find a SID
3127 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
3128 struct ldb_dn *dn, struct dom_sid *sid)
3131 struct ldb_result *res;
3132 const char *attrs[] = { "objectSid", NULL };
3133 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3138 ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3139 DSDB_SEARCH_SHOW_DELETED |
3140 DSDB_SEARCH_SHOW_RECYCLED);
3141 if (ret != LDB_SUCCESS) {
3142 talloc_free(tmp_ctx);
3145 if (res->count < 1) {
3146 talloc_free(tmp_ctx);
3147 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3149 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
3151 talloc_free(tmp_ctx);
3152 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3155 talloc_free(tmp_ctx);
3160 use a SID to find a DN
3162 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
3163 TALLOC_CTX *mem_ctx,
3164 struct dom_sid *sid, struct ldb_dn **dn)
3167 struct ldb_result *res;
3168 const char *attrs[] = { NULL };
3169 char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
3172 return ldb_operr(ldb);
3175 ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3176 DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3177 DSDB_SEARCH_SHOW_EXTENDED_DN |
3178 DSDB_SEARCH_ONE_ONLY,
3179 "objectSid=%s", sid_str);
3180 talloc_free(sid_str);
3181 if (ret != LDB_SUCCESS) {
3185 *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3192 load a repsFromTo blob list for a given partition GUID
3193 attr must be "repsFrom" or "repsTo"
3195 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3196 const char *attr, struct repsFromToBlob **r, uint32_t *count)
3198 const char *attrs[] = { attr, NULL };
3199 struct ldb_result *res = NULL;
3200 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3202 struct ldb_message_element *el;
3208 ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
3209 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3210 /* partition hasn't been replicated yet */
3213 if (ret != LDB_SUCCESS) {
3214 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
3215 talloc_free(tmp_ctx);
3216 return WERR_DS_DRA_INTERNAL_ERROR;
3219 el = ldb_msg_find_element(res->msgs[0], attr);
3221 /* it's OK to be empty */
3222 talloc_free(tmp_ctx);
3226 *count = el->num_values;
3227 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
3229 talloc_free(tmp_ctx);
3230 return WERR_DS_DRA_INTERNAL_ERROR;
3233 for (i=0; i<(*count); i++) {
3234 enum ndr_err_code ndr_err;
3235 ndr_err = ndr_pull_struct_blob(&el->values[i],
3238 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3239 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3240 talloc_free(tmp_ctx);
3241 return WERR_DS_DRA_INTERNAL_ERROR;
3245 talloc_free(tmp_ctx);
3251 save the repsFromTo blob list for a given partition GUID
3252 attr must be "repsFrom" or "repsTo"
3254 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3255 const char *attr, struct repsFromToBlob *r, uint32_t count)
3257 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3258 struct ldb_message *msg;
3259 struct ldb_message_element *el;
3262 msg = ldb_msg_new(tmp_ctx);
3264 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
3268 el->values = talloc_array(msg, struct ldb_val, count);
3273 for (i=0; i<count; i++) {
3275 enum ndr_err_code ndr_err;
3277 ndr_err = ndr_push_struct_blob(&v, tmp_ctx,
3279 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3280 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3288 if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
3289 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
3293 talloc_free(tmp_ctx);
3298 talloc_free(tmp_ctx);
3299 return WERR_DS_DRA_INTERNAL_ERROR;
3304 load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
3305 object for a partition
3307 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
3308 uint64_t *uSN, uint64_t *urgent_uSN)
3310 struct ldb_request *req;
3312 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3313 struct dsdb_control_current_partition *p_ctrl;
3314 struct ldb_result *res;
3316 res = talloc_zero(tmp_ctx, struct ldb_result);
3318 talloc_free(tmp_ctx);
3319 return ldb_oom(ldb);
3322 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3323 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
3327 res, ldb_search_default_callback,
3329 if (ret != LDB_SUCCESS) {
3330 talloc_free(tmp_ctx);
3334 p_ctrl = talloc(req, struct dsdb_control_current_partition);
3335 if (p_ctrl == NULL) {
3336 talloc_free(tmp_ctx);
3337 return ldb_oom(ldb);
3339 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
3342 ret = ldb_request_add_control(req,
3343 DSDB_CONTROL_CURRENT_PARTITION_OID,
3345 if (ret != LDB_SUCCESS) {
3346 talloc_free(tmp_ctx);
3350 /* Run the new request */
3351 ret = ldb_request(ldb, req);
3353 if (ret == LDB_SUCCESS) {
3354 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3357 if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
3358 /* it hasn't been created yet, which means
3359 an implicit value of zero */
3361 talloc_free(tmp_ctx);
3365 if (ret != LDB_SUCCESS) {
3366 talloc_free(tmp_ctx);
3370 if (res->count < 1) {
3376 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
3378 *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
3382 talloc_free(tmp_ctx);
3387 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
3388 const struct drsuapi_DsReplicaCursor2 *c2)
3390 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3393 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
3394 const struct drsuapi_DsReplicaCursor *c2)
3396 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3401 see if a computer identified by its invocationId is a RODC
3403 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
3405 /* 1) find the DN for this servers NTDSDSA object
3406 2) search for the msDS-isRODC attribute
3407 3) if not present then not a RODC
3408 4) if present and TRUE then is a RODC
3410 struct ldb_dn *config_dn;
3411 const char *attrs[] = { "msDS-isRODC", NULL };
3413 struct ldb_result *res;
3414 TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
3416 config_dn = ldb_get_config_basedn(sam_ctx);
3418 talloc_free(tmp_ctx);
3419 return ldb_operr(sam_ctx);
3422 ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
3423 DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
3425 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3427 talloc_free(tmp_ctx);
3431 if (ret != LDB_SUCCESS) {
3432 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
3433 GUID_string(tmp_ctx, objectGUID)));
3435 talloc_free(tmp_ctx);
3439 ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
3440 *is_rodc = (ret == 1);
3442 talloc_free(tmp_ctx);
3448 see if we are a RODC
3450 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
3452 const struct GUID *objectGUID;
3456 /* see if we have a cached copy */
3457 cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
3463 objectGUID = samdb_ntds_objectGUID(sam_ctx);
3465 return ldb_operr(sam_ctx);
3468 ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
3469 if (ret != LDB_SUCCESS) {
3473 cached = talloc(sam_ctx, bool);
3474 if (cached == NULL) {
3475 return ldb_oom(sam_ctx);
3479 ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
3480 if (ret != LDB_SUCCESS) {
3481 talloc_free(cached);
3482 return ldb_operr(sam_ctx);
3488 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3490 TALLOC_CTX *tmp_ctx;
3493 tmp_ctx = talloc_new(ldb);
3494 if (tmp_ctx == NULL) {
3498 cached = talloc(tmp_ctx, bool);
3504 if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3508 talloc_steal(ldb, cached);
3509 talloc_free(tmp_ctx);
3513 DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3514 talloc_free(tmp_ctx);
3520 * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3521 * flags are DS_NTDSSETTINGS_OPT_*
3523 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3527 TALLOC_CTX *tmp_ctx;
3528 struct ldb_result *res;
3529 struct ldb_dn *site_dn;
3530 const char *attrs[] = { "options", NULL };
3532 tmp_ctx = talloc_new(ldb_ctx);
3533 if (tmp_ctx == NULL)
3536 /* Retrieve the site dn for the ldb that we
3537 * have open. This is our local site.
3539 site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3540 if (site_dn == NULL)
3543 /* Perform a one level (child) search from the local
3544 * site distinguided name. We're looking for the
3545 * "options" attribute within the nTDSSiteSettings
3548 rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3549 LDB_SCOPE_ONELEVEL, attrs,
3550 "objectClass=nTDSSiteSettings");
3552 if (rc != LDB_SUCCESS || res->count != 1)
3555 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3557 talloc_free(tmp_ctx);
3562 DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3563 talloc_free(tmp_ctx);
3564 return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
3568 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
3570 flags are DS_NTDS_OPTION_*
3572 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3574 TALLOC_CTX *tmp_ctx;
3575 const char *attrs[] = { "options", NULL };
3577 struct ldb_result *res;
3579 tmp_ctx = talloc_new(ldb);
3580 if (tmp_ctx == NULL) {
3584 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3585 if (ret != LDB_SUCCESS) {
3589 if (res->count != 1) {
3593 *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3595 talloc_free(tmp_ctx);
3600 DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3601 talloc_free(tmp_ctx);
3602 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3605 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3607 const char *attrs[] = { "objectCategory", NULL };
3609 struct ldb_result *res;
3611 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3612 if (ret != LDB_SUCCESS) {
3616 if (res->count != 1) {
3620 return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3623 DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3628 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3629 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3631 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3633 char **tokens, *ret;
3636 tokens = str_list_make(mem_ctx, cn, " -_");
3637 if (tokens == NULL || tokens[0] == NULL) {
3641 /* "tolower()" and "toupper()" should also work properly on 0x00 */
3642 tokens[0][0] = tolower(tokens[0][0]);
3643 for (i = 1; tokens[i] != NULL; i++)
3644 tokens[i][0] = toupper(tokens[i][0]);
3646 ret = talloc_strdup(mem_ctx, tokens[0]);
3647 for (i = 1; tokens[i] != NULL; i++)
3648 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3650 talloc_free(tokens);
3656 * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3658 int dsdb_functional_level(struct ldb_context *ldb)
3660 int *domainFunctionality =
3661 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3662 if (!domainFunctionality) {
3663 /* this is expected during initial provision */
3664 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3665 return DS_DOMAIN_FUNCTION_2000;
3667 return *domainFunctionality;
3671 * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3673 int dsdb_forest_functional_level(struct ldb_context *ldb)
3675 int *forestFunctionality =
3676 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3677 if (!forestFunctionality) {
3678 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3679 return DS_DOMAIN_FUNCTION_2000;
3681 return *forestFunctionality;
3685 set a GUID in an extended DN structure
3687 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3693 status = GUID_to_ndr_blob(guid, dn, &v);
3694 if (!NT_STATUS_IS_OK(status)) {
3695 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3698 ret = ldb_dn_set_extended_component(dn, component_name, &v);
3704 return a GUID from a extended DN structure
3706 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3708 const struct ldb_val *v;
3710 v = ldb_dn_get_extended_component(dn, component_name);
3712 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3715 return GUID_from_ndr_blob(v, guid);
3719 return a uint64_t from a extended DN structure
3721 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3723 const struct ldb_val *v;
3725 v = ldb_dn_get_extended_component(dn, component_name);
3727 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3730 /* Just check we don't allow the caller to fill our stack */
3731 if (v->length >= 64) {
3732 return NT_STATUS_INVALID_PARAMETER;
3734 char s[v->length+1];
3735 memcpy(s, v->data, v->length);
3738 *val = strtoull(s, NULL, 0);
3740 return NT_STATUS_OK;
3744 return a NTTIME from a extended DN structure
3746 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3748 return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3752 return a uint32_t from a extended DN structure
3754 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3756 const struct ldb_val *v;
3758 v = ldb_dn_get_extended_component(dn, component_name);
3760 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3763 /* Just check we don't allow the caller to fill our stack */
3764 if (v->length >= 32) {
3765 return NT_STATUS_INVALID_PARAMETER;
3767 char s[v->length + 1];
3768 memcpy(s, v->data, v->length);
3770 *val = strtoul(s, NULL, 0);
3773 return NT_STATUS_OK;
3777 return a dom_sid from a extended DN structure
3779 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3781 const struct ldb_val *sid_blob;
3782 enum ndr_err_code ndr_err;
3784 sid_blob = ldb_dn_get_extended_component(dn, component_name);
3786 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3789 ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
3790 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3791 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3792 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3796 return NT_STATUS_OK;
3801 return RMD_FLAGS directly from a ldb_dn
3802 returns 0 if not found
3804 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3806 uint32_t rmd_flags = 0;
3807 NTSTATUS status = dsdb_get_extended_dn_uint32(dn, &rmd_flags,
3809 if (NT_STATUS_IS_OK(status)) {
3816 return RMD_FLAGS directly from a ldb_val for a DN
3817 returns 0 if RMD_FLAGS is not found
3819 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3825 if (val->length < 13) {
3828 p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3832 flags = strtoul(p+11, &end, 10);
3833 if (!end || *end != '>') {
3834 /* it must end in a > */
3841 return true if a ldb_val containing a DN in storage form is deleted
3843 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3845 return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3849 return true if a ldb_val containing a DN in storage form is
3850 in the upgraded w2k3 linked attribute format
3852 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
3854 return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
3858 return a DN for a wellknown GUID
3860 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3861 struct ldb_dn *nc_root, const char *wk_guid,
3862 struct ldb_dn **wkguid_dn)
3864 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3865 const char *attrs[] = { NULL };
3868 struct ldb_result *res;
3870 /* construct the magic WKGUID DN */
3871 dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3872 wk_guid, ldb_dn_get_linearized(nc_root));
3874 talloc_free(tmp_ctx);
3875 return ldb_operr(samdb);
3878 ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
3879 DSDB_SEARCH_SHOW_DELETED |
3880 DSDB_SEARCH_SHOW_RECYCLED);
3881 if (ret != LDB_SUCCESS) {
3882 talloc_free(tmp_ctx);
3886 (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3887 talloc_free(tmp_ctx);
3892 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3894 return ldb_dn_compare(*dn1, *dn2);
3898 find a NC root given a DN within the NC
3900 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3901 struct ldb_dn **nc_root)
3903 const char *root_attrs[] = { "namingContexts", NULL };
3904 TALLOC_CTX *tmp_ctx;
3906 struct ldb_message_element *el;
3907 struct ldb_result *root_res;
3909 struct ldb_dn **nc_dns;
3911 tmp_ctx = talloc_new(samdb);
3912 if (tmp_ctx == NULL) {
3913 return ldb_oom(samdb);
3916 ret = ldb_search(samdb, tmp_ctx, &root_res,
3917 ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3918 if (ret != LDB_SUCCESS || root_res->count == 0) {
3919 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3920 talloc_free(tmp_ctx);
3924 el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3925 if ((el == NULL) || (el->num_values < 3)) {
3926 struct ldb_message *tmp_msg;
3928 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list."));
3930 /* This generates a temporary list of NCs in order to let the
3931 * provisioning work. */
3932 tmp_msg = ldb_msg_new(tmp_ctx);
3933 if (tmp_msg == NULL) {
3934 talloc_free(tmp_ctx);
3935 return ldb_oom(samdb);
3937 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3938 ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
3939 if (ret != LDB_SUCCESS) {
3940 talloc_free(tmp_ctx);
3943 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3944 ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
3945 if (ret != LDB_SUCCESS) {
3946 talloc_free(tmp_ctx);
3949 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3950 ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
3951 if (ret != LDB_SUCCESS) {
3952 talloc_free(tmp_ctx);
3955 el = &tmp_msg->elements[0];
3958 nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3960 talloc_free(tmp_ctx);
3961 return ldb_oom(samdb);
3964 for (i=0; i<el->num_values; i++) {
3965 nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3966 if (nc_dns[i] == NULL) {
3967 talloc_free(tmp_ctx);
3968 return ldb_operr(samdb);
3972 TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3974 for (i=0; i<el->num_values; i++) {
3975 if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3976 (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3977 talloc_free(tmp_ctx);
3982 talloc_free(tmp_ctx);
3983 return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3988 find the deleted objects DN for any object, by looking for the NC
3989 root, then looking up the wellknown GUID
3991 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3992 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3993 struct ldb_dn **do_dn)
3995 struct ldb_dn *nc_root;
3998 ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3999 if (ret != LDB_SUCCESS) {
4003 ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
4004 talloc_free(nc_root);
4009 return the tombstoneLifetime, in days
4011 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
4014 dn = ldb_get_config_basedn(ldb);
4016 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4018 dn = ldb_dn_copy(ldb, dn);
4020 return ldb_operr(ldb);
4022 /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
4023 be a wellknown GUID for this */
4024 if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
4026 return ldb_operr(ldb);
4029 *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
4035 compare a ldb_val to a string case insensitively
4037 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
4039 size_t len = strlen(s);
4041 if (len > v->length) return 1;
4042 ret = strncasecmp(s, (const char *)v->data, v->length);
4043 if (ret != 0) return ret;
4044 if (v->length > len && v->data[len] != 0) {
4052 load the UDV for a partition in v2 format
4053 The list is returned sorted, and with our local cursor added
4055 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4056 struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
4058 static const char *attrs[] = { "replUpToDateVector", NULL };
4059 struct ldb_result *r;
4060 const struct ldb_val *ouv_value;
4063 uint64_t highest_usn = 0;
4064 const struct GUID *our_invocation_id;
4065 static const struct timeval tv1970;
4066 NTTIME nt1970 = timeval_to_nttime(&tv1970);
4068 ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
4069 if (ret != LDB_SUCCESS) {
4073 ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
4075 enum ndr_err_code ndr_err;
4076 struct replUpToDateVectorBlob ouv;
4078 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
4079 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
4080 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4082 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4084 if (ouv.version != 2) {
4085 /* we always store as version 2, and
4086 * replUpToDateVector is not replicated
4088 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4091 *count = ouv.ctr.ctr2.count;
4092 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
4100 our_invocation_id = samdb_ntds_invocation_id(samdb);
4101 if (!our_invocation_id) {
4102 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
4103 talloc_free(*cursors);
4104 return ldb_operr(samdb);
4107 ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
4108 if (ret != LDB_SUCCESS) {
4109 /* nothing to add - this can happen after a vampire */
4110 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4114 for (i=0; i<*count; i++) {
4115 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
4116 (*cursors)[i].highest_usn = highest_usn;
4117 (*cursors)[i].last_sync_success = nt1970;
4118 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4123 (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
4125 return ldb_oom(samdb);
4128 (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
4129 (*cursors)[*count].highest_usn = highest_usn;
4130 (*cursors)[*count].last_sync_success = nt1970;
4133 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4139 load the UDV for a partition in version 1 format
4140 The list is returned sorted, and with our local cursor added
4142 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4143 struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
4145 struct drsuapi_DsReplicaCursor2 *v2;
4149 ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
4150 if (ret != LDB_SUCCESS) {
4160 *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
4161 if (*cursors == NULL) {
4163 return ldb_oom(samdb);
4166 for (i=0; i<*count; i++) {
4167 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
4168 (*cursors)[i].highest_usn = v2[i].highest_usn;
4175 add a set of controls to a ldb_request structure based on a set of
4176 flags. See util.h for a list of available flags
4178 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
4181 if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
4182 struct ldb_search_options_control *options;
4183 /* Using the phantom root control allows us to search all partitions */
4184 options = talloc(req, struct ldb_search_options_control);
4185 if (options == NULL) {
4186 return LDB_ERR_OPERATIONS_ERROR;
4188 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
4190 ret = ldb_request_add_control(req,
4191 LDB_CONTROL_SEARCH_OPTIONS_OID,
4193 if (ret != LDB_SUCCESS) {
4198 if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
4199 ret = ldb_request_add_control(req,
4200 DSDB_CONTROL_NO_GLOBAL_CATALOG,
4202 if (ret != LDB_SUCCESS) {
4207 if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
4208 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
4209 if (ret != LDB_SUCCESS) {
4214 if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
4215 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
4216 if (ret != LDB_SUCCESS) {
4221 if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
4222 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
4223 if (ret != LDB_SUCCESS) {
4228 if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
4229 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
4230 if (!extended_ctrl) {
4231 return LDB_ERR_OPERATIONS_ERROR;
4233 extended_ctrl->type = 1;
4235 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
4236 if (ret != LDB_SUCCESS) {
4241 if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
4242 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
4243 if (ret != LDB_SUCCESS) {
4248 if (dsdb_flags & DSDB_MODIFY_RELAX) {
4249 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
4250 if (ret != LDB_SUCCESS) {
4255 if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
4256 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
4257 if (ret != LDB_SUCCESS) {
4262 if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
4263 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
4264 if (ret != LDB_SUCCESS) {
4269 if (dsdb_flags & DSDB_TREE_DELETE) {
4270 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
4271 if (ret != LDB_SUCCESS) {
4276 if (dsdb_flags & DSDB_PROVISION) {
4277 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
4278 if (ret != LDB_SUCCESS) {
4283 /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
4284 if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
4285 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
4286 if (ret != LDB_SUCCESS) {
4291 if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
4293 * This must not be critical, as it will only be
4294 * handled (and need to be handled) if the other
4295 * attributes in the request bring password_hash into
4298 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
4299 if (ret != LDB_SUCCESS) {
4304 if (dsdb_flags & DSDB_REPLMD_VANISH_LINKS) {
4305 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLMD_VANISH_LINKS, true, NULL);
4306 if (ret != LDB_SUCCESS) {
4311 if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
4312 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
4313 if (ret != LDB_SUCCESS) {
4318 if (dsdb_flags & DSDB_FLAG_REPLICATED_UPDATE) {
4319 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
4320 if (ret != LDB_SUCCESS) {
4329 an add with a set of controls
4331 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
4332 uint32_t dsdb_flags)
4334 struct ldb_request *req;
4337 ret = ldb_build_add_req(&req, ldb, ldb,
4341 ldb_op_default_callback,
4344 if (ret != LDB_SUCCESS) return ret;
4346 ret = dsdb_request_add_controls(req, dsdb_flags);
4347 if (ret != LDB_SUCCESS) {
4352 ret = dsdb_autotransaction_request(ldb, req);
4359 a modify with a set of controls
4361 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
4362 uint32_t dsdb_flags)
4364 struct ldb_request *req;
4367 ret = ldb_build_mod_req(&req, ldb, ldb,
4371 ldb_op_default_callback,
4374 if (ret != LDB_SUCCESS) return ret;
4376 ret = dsdb_request_add_controls(req, dsdb_flags);
4377 if (ret != LDB_SUCCESS) {
4382 ret = dsdb_autotransaction_request(ldb, req);
4389 a delete with a set of flags
4391 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
4392 uint32_t dsdb_flags)
4394 struct ldb_request *req;
4397 ret = ldb_build_del_req(&req, ldb, ldb,
4401 ldb_op_default_callback,
4404 if (ret != LDB_SUCCESS) return ret;
4406 ret = dsdb_request_add_controls(req, dsdb_flags);
4407 if (ret != LDB_SUCCESS) {
4412 ret = dsdb_autotransaction_request(ldb, req);
4419 like dsdb_modify() but set all the element flags to
4420 LDB_FLAG_MOD_REPLACE
4422 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
4426 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
4427 for (i=0;i<msg->num_elements;i++) {
4428 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
4431 return dsdb_modify(ldb, msg, dsdb_flags);
4436 search for attrs on one DN, allowing for dsdb_flags controls
4438 int dsdb_search_dn(struct ldb_context *ldb,
4439 TALLOC_CTX *mem_ctx,
4440 struct ldb_result **_result,
4441 struct ldb_dn *basedn,
4442 const char * const *attrs,
4443 uint32_t dsdb_flags)
4446 struct ldb_request *req;
4447 struct ldb_result *res;
4449 res = talloc_zero(mem_ctx, struct ldb_result);
4451 return ldb_oom(ldb);
4454 ret = ldb_build_search_req(&req, ldb, res,
4461 ldb_search_default_callback,
4463 if (ret != LDB_SUCCESS) {
4468 ret = dsdb_request_add_controls(req, dsdb_flags);
4469 if (ret != LDB_SUCCESS) {
4474 ret = ldb_request(ldb, req);
4475 if (ret == LDB_SUCCESS) {
4476 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4480 if (ret != LDB_SUCCESS) {
4490 search for attrs on one DN, by the GUID of the DN, allowing for
4493 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
4494 TALLOC_CTX *mem_ctx,
4495 struct ldb_result **_result,
4496 const struct GUID *guid,
4497 const char * const *attrs,
4498 uint32_t dsdb_flags)
4500 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4504 dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
4506 talloc_free(tmp_ctx);
4507 return ldb_oom(ldb);
4510 ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
4511 talloc_free(tmp_ctx);
4516 general search with dsdb_flags for controls
4518 int dsdb_search(struct ldb_context *ldb,
4519 TALLOC_CTX *mem_ctx,
4520 struct ldb_result **_result,
4521 struct ldb_dn *basedn,
4522 enum ldb_scope scope,
4523 const char * const *attrs,
4524 uint32_t dsdb_flags,
4525 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4528 struct ldb_request *req;
4529 struct ldb_result *res;
4531 char *expression = NULL;
4532 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4534 /* cross-partitions searches with a basedn break multi-domain support */
4535 SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
4537 res = talloc_zero(tmp_ctx, struct ldb_result);
4539 talloc_free(tmp_ctx);
4540 return ldb_oom(ldb);
4544 va_start(ap, exp_fmt);
4545 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4549 talloc_free(tmp_ctx);
4550 return ldb_oom(ldb);
4554 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
4561 ldb_search_default_callback,
4563 if (ret != LDB_SUCCESS) {
4564 talloc_free(tmp_ctx);
4568 ret = dsdb_request_add_controls(req, dsdb_flags);
4569 if (ret != LDB_SUCCESS) {
4570 talloc_free(tmp_ctx);
4571 ldb_reset_err_string(ldb);
4575 ret = ldb_request(ldb, req);
4576 if (ret == LDB_SUCCESS) {
4577 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4580 if (ret != LDB_SUCCESS) {
4581 talloc_free(tmp_ctx);
4585 if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
4586 if (res->count == 0) {
4587 talloc_free(tmp_ctx);
4588 ldb_reset_err_string(ldb);
4589 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4591 if (res->count != 1) {
4592 talloc_free(tmp_ctx);
4593 ldb_reset_err_string(ldb);
4594 return LDB_ERR_CONSTRAINT_VIOLATION;
4598 *_result = talloc_steal(mem_ctx, res);
4599 talloc_free(tmp_ctx);
4606 general search with dsdb_flags for controls
4607 returns exactly 1 record or an error
4609 int dsdb_search_one(struct ldb_context *ldb,
4610 TALLOC_CTX *mem_ctx,
4611 struct ldb_message **msg,
4612 struct ldb_dn *basedn,
4613 enum ldb_scope scope,
4614 const char * const *attrs,
4615 uint32_t dsdb_flags,
4616 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4619 struct ldb_result *res;
4621 char *expression = NULL;
4622 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4624 dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4626 res = talloc_zero(tmp_ctx, struct ldb_result);
4628 talloc_free(tmp_ctx);
4629 return ldb_oom(ldb);
4633 va_start(ap, exp_fmt);
4634 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4638 talloc_free(tmp_ctx);
4639 return ldb_oom(ldb);
4641 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4642 dsdb_flags, "%s", expression);
4644 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4648 if (ret != LDB_SUCCESS) {
4649 talloc_free(tmp_ctx);
4653 *msg = talloc_steal(mem_ctx, res->msgs[0]);
4654 talloc_free(tmp_ctx);
4659 /* returns back the forest DNS name */
4660 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4662 const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4663 ldb_get_root_basedn(ldb));
4666 if (forest_name == NULL) {
4670 p = strchr(forest_name, '/');
4678 /* returns back the default domain DNS name */
4679 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4681 const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4682 ldb_get_default_basedn(ldb));
4685 if (domain_name == NULL) {
4689 p = strchr(domain_name, '/');
4698 validate that an DSA GUID belongs to the specified user sid.
4699 The user SID must be a domain controller account (either RODC or
4702 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4703 const struct GUID *dsa_guid,
4704 const struct dom_sid *sid)
4707 - find DN of record with the DSA GUID in the
4708 configuration partition (objectGUID)
4709 - remove "NTDS Settings" component from DN
4710 - do a base search on that DN for serverReference with
4712 - extract objectSid from resulting serverReference
4714 - check this sid matches the sid argument
4716 struct ldb_dn *config_dn;
4717 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4718 struct ldb_message *msg;
4719 const char *attrs1[] = { NULL };
4720 const char *attrs2[] = { "serverReference", NULL };
4722 struct ldb_dn *dn, *account_dn;
4723 struct dom_sid sid2;
4726 config_dn = ldb_get_config_basedn(ldb);
4728 ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4729 attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4730 if (ret != LDB_SUCCESS) {
4731 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4732 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4733 talloc_free(tmp_ctx);
4734 return ldb_operr(ldb);
4738 if (!ldb_dn_remove_child_components(dn, 1)) {
4739 talloc_free(tmp_ctx);
4740 return ldb_operr(ldb);
4743 ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4744 attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4745 "(objectClass=server)");
4746 if (ret != LDB_SUCCESS) {
4747 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4748 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4749 talloc_free(tmp_ctx);
4750 return ldb_operr(ldb);
4753 account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4754 if (account_dn == NULL) {
4755 DEBUG(1,(__location__ ": Failed to find account dn "
4756 "(serverReference) for %s, parent of DSA with "
4757 "objectGUID %s, sid %s\n",
4758 ldb_dn_get_linearized(msg->dn),
4759 GUID_string(tmp_ctx, dsa_guid),
4760 dom_sid_string(tmp_ctx, sid)));
4761 talloc_free(tmp_ctx);
4762 return ldb_operr(ldb);
4765 status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4766 if (!NT_STATUS_IS_OK(status)) {
4767 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4768 GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4769 talloc_free(tmp_ctx);
4770 return ldb_operr(ldb);
4773 if (!dom_sid_equal(sid, &sid2)) {
4774 /* someone is trying to spoof another account */
4775 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4776 GUID_string(tmp_ctx, dsa_guid),
4777 dom_sid_string(tmp_ctx, sid),
4778 dom_sid_string(tmp_ctx, &sid2)));
4779 talloc_free(tmp_ctx);
4780 return ldb_operr(ldb);
4783 talloc_free(tmp_ctx);
4787 static const char * const secret_attributes[] = {
4788 DSDB_SECRET_ATTRIBUTES,
4793 check if the attribute belongs to the RODC filtered attribute set
4794 Note that attributes that are in the filtered attribute set are the
4795 ones that _are_ always sent to a RODC
4797 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4799 /* they never get secret attributes */
4800 if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4804 /* they do get non-secret critical attributes */
4805 if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4809 /* they do get non-secret attributes marked as being in the FAS */
4810 if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4814 /* other attributes are denied */
4818 /* return fsmo role dn and role owner dn for a particular role*/
4819 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4820 struct ldb_context *ldb,
4822 struct ldb_dn **fsmo_role_dn,
4823 struct ldb_dn **role_owner_dn)
4827 case DREPL_NAMING_MASTER:
4828 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4829 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4830 if (ret != LDB_SUCCESS) {
4831 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4832 ldb_errstring(ldb)));
4833 talloc_free(tmp_ctx);
4834 return WERR_DS_DRA_INTERNAL_ERROR;
4837 case DREPL_INFRASTRUCTURE_MASTER:
4838 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4839 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4840 if (ret != LDB_SUCCESS) {
4841 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4842 ldb_errstring(ldb)));
4843 talloc_free(tmp_ctx);
4844 return WERR_DS_DRA_INTERNAL_ERROR;
4847 case DREPL_RID_MASTER:
4848 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
4849 if (ret != LDB_SUCCESS) {
4850 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
4851 talloc_free(tmp_ctx);
4852 return WERR_DS_DRA_INTERNAL_ERROR;
4855 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4856 if (ret != LDB_SUCCESS) {
4857 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
4858 ldb_errstring(ldb)));
4859 talloc_free(tmp_ctx);
4860 return WERR_DS_DRA_INTERNAL_ERROR;
4863 case DREPL_SCHEMA_MASTER:
4864 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
4865 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4866 if (ret != LDB_SUCCESS) {
4867 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4868 ldb_errstring(ldb)));
4869 talloc_free(tmp_ctx);
4870 return WERR_DS_DRA_INTERNAL_ERROR;
4873 case DREPL_PDC_MASTER:
4874 *fsmo_role_dn = ldb_get_default_basedn(ldb);
4875 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4876 if (ret != LDB_SUCCESS) {
4877 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
4878 ldb_errstring(ldb)));
4879 talloc_free(tmp_ctx);
4880 return WERR_DS_DRA_INTERNAL_ERROR;
4884 return WERR_DS_DRA_INTERNAL_ERROR;
4889 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
4890 TALLOC_CTX *mem_ctx,
4891 struct ldb_dn *server_dn)
4894 struct ldb_result *res = NULL;
4895 const char * const attrs[] = { "dNSHostName", NULL};
4897 ldb_ret = ldb_search(ldb, mem_ctx, &res,
4901 if (ldb_ret != LDB_SUCCESS) {
4902 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
4903 ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
4907 return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
4911 returns true if an attribute is in the filter,
4912 false otherwise, provided that attribute value is provided with the expression
4914 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
4918 switch (tree->operation) {
4921 for (i=0;i<tree->u.list.num_elements;i++) {
4922 if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
4928 return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
4929 case LDB_OP_EQUALITY:
4930 case LDB_OP_GREATER:
4933 if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
4937 case LDB_OP_SUBSTRING:
4938 if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
4942 case LDB_OP_PRESENT:
4943 /* (attrname=*) is not filtered out */
4945 case LDB_OP_EXTENDED:
4946 if (tree->u.extended.attr &&
4947 ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
4955 bool is_attr_in_list(const char * const * attrs, const char *attr)
4959 for (i = 0; attrs[i]; i++) {
4960 if (ldb_attr_cmp(attrs[i], attr) == 0)
4967 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
4968 const char *location, const char *func,
4971 if (reason == NULL) {
4972 reason = win_errstr(werr);
4974 ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
4975 W_ERROR_V(werr), reason, location, func);
4980 map an ldb error code to an approximate NTSTATUS code
4982 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
4986 return NT_STATUS_OK;
4988 case LDB_ERR_PROTOCOL_ERROR:
4989 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
4991 case LDB_ERR_TIME_LIMIT_EXCEEDED:
4992 return NT_STATUS_IO_TIMEOUT;
4994 case LDB_ERR_SIZE_LIMIT_EXCEEDED:
4995 return NT_STATUS_BUFFER_TOO_SMALL;
4997 case LDB_ERR_COMPARE_FALSE:
4998 case LDB_ERR_COMPARE_TRUE:
4999 return NT_STATUS_REVISION_MISMATCH;
5001 case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
5002 return NT_STATUS_NOT_SUPPORTED;
5004 case LDB_ERR_STRONG_AUTH_REQUIRED:
5005 case LDB_ERR_CONFIDENTIALITY_REQUIRED:
5006 case LDB_ERR_SASL_BIND_IN_PROGRESS:
5007 case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
5008 case LDB_ERR_INVALID_CREDENTIALS:
5009 case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
5010 case LDB_ERR_UNWILLING_TO_PERFORM:
5011 return NT_STATUS_ACCESS_DENIED;
5013 case LDB_ERR_NO_SUCH_OBJECT:
5014 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
5016 case LDB_ERR_REFERRAL:
5017 case LDB_ERR_NO_SUCH_ATTRIBUTE:
5018 return NT_STATUS_NOT_FOUND;
5020 case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
5021 return NT_STATUS_NOT_SUPPORTED;
5023 case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
5024 return NT_STATUS_BUFFER_TOO_SMALL;
5026 case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
5027 case LDB_ERR_INAPPROPRIATE_MATCHING:
5028 case LDB_ERR_CONSTRAINT_VIOLATION:
5029 case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
5030 case LDB_ERR_INVALID_DN_SYNTAX:
5031 case LDB_ERR_NAMING_VIOLATION:
5032 case LDB_ERR_OBJECT_CLASS_VIOLATION:
5033 case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
5034 case LDB_ERR_NOT_ALLOWED_ON_RDN:
5035 return NT_STATUS_INVALID_PARAMETER;
5037 case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
5038 case LDB_ERR_ENTRY_ALREADY_EXISTS:
5039 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
5042 return NT_STATUS_NETWORK_BUSY;
5044 case LDB_ERR_ALIAS_PROBLEM:
5045 case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
5046 case LDB_ERR_UNAVAILABLE:
5047 case LDB_ERR_LOOP_DETECT:
5048 case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
5049 case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
5051 case LDB_ERR_OPERATIONS_ERROR:
5054 return NT_STATUS_UNSUCCESSFUL;
5059 create a new naming context that will hold a partial replica
5061 int dsdb_create_partial_replica_NC(struct ldb_context *ldb, struct ldb_dn *dn)
5063 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5064 struct ldb_message *msg;
5067 msg = ldb_msg_new(tmp_ctx);
5069 talloc_free(tmp_ctx);
5070 return ldb_oom(ldb);
5074 ret = ldb_msg_add_string(msg, "objectClass", "top");
5075 if (ret != LDB_SUCCESS) {
5076 talloc_free(tmp_ctx);
5077 return ldb_oom(ldb);
5080 /* [MS-DRSR] implies that we should only add the 'top'
5081 * objectclass, but that would cause lots of problems with our
5082 * objectclass code as top is not structural, so we add
5083 * 'domainDNS' as well to keep things sane. We're expecting
5084 * this new NC to be of objectclass domainDNS after
5085 * replication anyway
5087 ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
5088 if (ret != LDB_SUCCESS) {
5089 talloc_free(tmp_ctx);
5090 return ldb_oom(ldb);
5093 ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
5094 INSTANCE_TYPE_IS_NC_HEAD|
5095 INSTANCE_TYPE_NC_ABOVE|
5096 INSTANCE_TYPE_UNINSTANT);
5097 if (ret != LDB_SUCCESS) {
5098 talloc_free(tmp_ctx);
5099 return ldb_oom(ldb);
5102 ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
5103 if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
5104 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
5105 ldb_dn_get_linearized(dn),
5106 ldb_errstring(ldb), ldb_strerror(ret)));
5107 talloc_free(tmp_ctx);
5111 DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
5113 talloc_free(tmp_ctx);
5118 build a GUID from a string
5120 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
5122 NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
5124 uint32_t time_mid, time_hi_and_version;
5125 uint32_t clock_seq[2];
5130 return NT_STATUS_INVALID_PARAMETER;
5133 if (11 == sscanf(s, "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5134 &time_low, &time_mid, &time_hi_and_version,
5135 &clock_seq[0], &clock_seq[1],
5136 &node[0], &node[1], &node[2], &node[3], &node[4], &node[5])) {
5137 status = NT_STATUS_OK;
5140 if (!NT_STATUS_IS_OK(status)) {
5144 guid->time_low = time_low;
5145 guid->time_mid = time_mid;
5146 guid->time_hi_and_version = time_hi_and_version;
5147 guid->clock_seq[0] = clock_seq[0];
5148 guid->clock_seq[1] = clock_seq[1];
5150 guid->node[i] = node[i];
5153 return NT_STATUS_OK;
5156 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
5158 return talloc_asprintf(mem_ctx,
5159 "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5160 guid->time_low, guid->time_mid,
5161 guid->time_hi_and_version,
5164 guid->node[0], guid->node[1],
5165 guid->node[2], guid->node[3],
5166 guid->node[4], guid->node[5]);
5170 * Return the effective badPwdCount
5172 * This requires that the user_msg have (if present):
5176 * This also requires that the domain_msg have (if present):
5177 * - lockOutObservationWindow
5179 static int dsdb_effective_badPwdCount(const struct ldb_message *user_msg,
5180 int64_t lockOutObservationWindow,
5183 int64_t badPasswordTime;
5184 badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
5186 if (badPasswordTime - lockOutObservationWindow >= now) {
5187 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
5194 * Return the effective badPwdCount
5196 * This requires that the user_msg have (if present):
5201 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
5202 TALLOC_CTX *mem_ctx,
5203 struct ldb_dn *domain_dn,
5204 const struct ldb_message *user_msg)
5206 struct timeval tv_now = timeval_current();
5207 NTTIME now = timeval_to_nttime(&tv_now);
5208 int64_t lockOutObservationWindow = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
5209 "lockOutObservationWindow", NULL);
5210 return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5214 * Prepare an update to the badPwdCount and associated attributes.
5216 * This requires that the user_msg have (if present):
5221 * This also requires that the domain_msg have (if present):
5223 * - lockoutThreshold
5224 * - lockOutObservationWindow
5226 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
5227 struct ldb_context *sam_ctx,
5228 struct ldb_message *user_msg,
5229 struct ldb_message *domain_msg,
5230 struct ldb_message **_mod_msg)
5232 int i, ret, badPwdCount;
5233 int64_t lockoutThreshold, lockOutObservationWindow;
5234 struct dom_sid *sid;
5235 struct timeval tv_now = timeval_current();
5236 NTTIME now = timeval_to_nttime(&tv_now);
5238 uint32_t pwdProperties, rid = 0;
5239 struct ldb_message *mod_msg;
5241 sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
5243 pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
5244 "pwdProperties", -1);
5245 if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
5246 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
5247 if (!NT_STATUS_IS_OK(status)) {
5249 * This can't happen anyway, but always try
5250 * and update the badPwdCount on failure
5258 * Work out if we are doing password lockout on the domain.
5259 * Also, the built in administrator account is exempt:
5260 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
5262 lockoutThreshold = ldb_msg_find_attr_as_int(domain_msg,
5263 "lockoutThreshold", 0);
5264 if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
5265 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
5266 ldb_dn_get_linearized(user_msg->dn)));
5267 return NT_STATUS_OK;
5270 mod_msg = ldb_msg_new(mem_ctx);
5271 if (mod_msg == NULL) {
5272 return NT_STATUS_NO_MEMORY;
5274 mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
5275 if (mod_msg->dn == NULL) {
5276 TALLOC_FREE(mod_msg);
5277 return NT_STATUS_NO_MEMORY;
5280 lockOutObservationWindow = ldb_msg_find_attr_as_int64(domain_msg,
5281 "lockOutObservationWindow", 0);
5283 badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5287 ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
5288 if (ret != LDB_SUCCESS) {
5289 TALLOC_FREE(mod_msg);
5290 return NT_STATUS_NO_MEMORY;
5292 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
5293 if (ret != LDB_SUCCESS) {
5294 TALLOC_FREE(mod_msg);
5295 return NT_STATUS_NO_MEMORY;
5298 if (badPwdCount >= lockoutThreshold) {
5299 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
5300 if (ret != LDB_SUCCESS) {
5301 TALLOC_FREE(mod_msg);
5302 return NT_STATUS_NO_MEMORY;
5304 DEBUG(5, ("Locked out user %s after %d wrong passwords\n",
5305 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5307 DEBUG(5, ("Updated badPwdCount on %s after %d wrong passwords\n",
5308 ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5311 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5312 for (i=0; i< mod_msg->num_elements; i++) {
5313 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5316 *_mod_msg = mod_msg;
5317 return NT_STATUS_OK;
5321 * Sets defaults for a User object
5322 * List of default attributes set:
5323 * accountExpires, badPasswordTime, badPwdCount,
5324 * codePage, countryCode, lastLogoff, lastLogon
5325 * logonCount, pwdLastSet
5327 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
5328 struct ldb_message *usr_obj,
5329 struct ldb_request *req)
5332 const struct attribute_values {
5335 const char *add_value;
5336 const char *mod_value;
5337 const char *control;
5342 .name = "accountExpires",
5343 .add_value = "9223372036854775807",
5347 .name = "badPasswordTime",
5351 .name = "badPwdCount",
5359 .name = "countryCode",
5363 .name = "lastLogoff",
5367 .name = "lastLogon",
5371 .name = "logonCount",
5375 .name = "logonHours",
5376 .add_flags = DSDB_FLAG_INTERNAL_FORCE_META_DATA,
5379 .name = "pwdLastSet",
5381 .control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
5384 .name = "adminCount",
5388 .name = "operatorCount",
5393 for (i = 0; i < ARRAY_SIZE(map); i++) {
5395 const char *value = NULL;
5398 if (req != NULL && req->operation == LDB_ADD) {
5399 value = map[i].add_value;
5400 flags = map[i].add_flags;
5402 value = map[i].mod_value;
5403 flags = map[i].mod_flags;
5406 if (value == NULL) {
5407 value = map[i].value;
5410 if (value != NULL) {
5411 flags |= LDB_FLAG_MOD_ADD;
5418 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
5422 if (ret != LDB_SUCCESS) {
5426 if (req != NULL && added && map[i].control != NULL) {
5427 ret = ldb_request_add_control(req,
5430 if (ret != LDB_SUCCESS) {
5440 * Sets 'sAMAccountType on user object based on userAccountControl
5441 * @param ldb Current ldb_context
5442 * @param usr_obj ldb_message representing User object
5443 * @param user_account_control Value for userAccountControl flags
5444 * @param account_type_p Optional pointer to account_type to return
5445 * @return LDB_SUCCESS or LDB_ERR* code on failure
5447 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
5448 uint32_t user_account_control, uint32_t *account_type_p)
5451 uint32_t account_type;
5452 struct ldb_message_element *el;
5454 account_type = ds_uf2atype(user_account_control);
5455 if (account_type == 0) {
5456 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
5457 return LDB_ERR_UNWILLING_TO_PERFORM;
5459 ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5462 if (ret != LDB_SUCCESS) {
5465 el = ldb_msg_find_element(usr_obj, "sAMAccountType");
5466 el->flags = LDB_FLAG_MOD_REPLACE;
5468 if (account_type_p) {
5469 *account_type_p = account_type;
5476 * Determine and set primaryGroupID based on userAccountControl value
5477 * @param ldb Current ldb_context
5478 * @param usr_obj ldb_message representing User object
5479 * @param user_account_control Value for userAccountControl flags
5480 * @param group_rid_p Optional pointer to group RID to return
5481 * @return LDB_SUCCESS or LDB_ERR* code on failure
5483 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
5484 uint32_t user_account_control, uint32_t *group_rid_p)
5488 struct ldb_message_element *el;
5490 rid = ds_uf2prim_group_rid(user_account_control);
5492 ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5493 "primaryGroupID", rid);
5494 if (ret != LDB_SUCCESS) {
5497 el = ldb_msg_find_element(usr_obj, "primaryGroupID");
5498 el->flags = LDB_FLAG_MOD_REPLACE;