s4:"samdb_set_password_sid" - clean up created objects correctly
[Samba/cd1.git] / source4 / dsdb / common / util.c
blob3aa415ef23b5d446616983c8afe15d8e4583212c
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
5 Copyright (C) Andrew Tridgell 2004
6 Copyright (C) Volker Lendecke 2004
7 Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006
8 Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "includes.h"
25 #include "events/events.h"
26 #include "ldb.h"
27 #include "ldb_errors.h"
28 #include "../lib/util/util_ldb.h"
29 #include "../lib/crypto/crypto.h"
30 #include "dsdb/samdb/samdb.h"
31 #include "libcli/security/security.h"
32 #include "librpc/gen_ndr/ndr_security.h"
33 #include "librpc/gen_ndr/ndr_misc.h"
34 #include "../libds/common/flags.h"
35 #include "dsdb/common/proto.h"
36 #include "libcli/ldap/ldap_ndr.h"
37 #include "param/param.h"
38 #include "libcli/auth/libcli_auth.h"
39 #include "librpc/gen_ndr/ndr_drsblobs.h"
40 #include "system/locale.h"
43 search the sam for the specified attributes in a specific domain, filter on
44 objectSid being in domain_sid.
46 int samdb_search_domain(struct ldb_context *sam_ldb,
47 TALLOC_CTX *mem_ctx,
48 struct ldb_dn *basedn,
49 struct ldb_message ***res,
50 const char * const *attrs,
51 const struct dom_sid *domain_sid,
52 const char *format, ...) _PRINTF_ATTRIBUTE(7,8)
54 va_list ap;
55 int i, count;
57 va_start(ap, format);
58 count = gendb_search_v(sam_ldb, mem_ctx, basedn,
59 res, attrs, format, ap);
60 va_end(ap);
62 i=0;
64 while (i<count) {
65 struct dom_sid *entry_sid;
67 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
69 if ((entry_sid == NULL) ||
70 (!dom_sid_in_domain(domain_sid, entry_sid))) {
71 /* Delete that entry from the result set */
72 (*res)[i] = (*res)[count-1];
73 count -= 1;
74 talloc_free(entry_sid);
75 continue;
77 talloc_free(entry_sid);
78 i += 1;
81 return count;
85 search the sam for a single string attribute in exactly 1 record
87 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
88 TALLOC_CTX *mem_ctx,
89 struct ldb_dn *basedn,
90 const char *attr_name,
91 const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
93 int count;
94 const char *attrs[2] = { NULL, NULL };
95 struct ldb_message **res = NULL;
97 attrs[0] = attr_name;
99 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
100 if (count > 1) {
101 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
102 attr_name, format, count));
104 if (count != 1) {
105 talloc_free(res);
106 return NULL;
109 return samdb_result_string(res[0], attr_name, NULL);
113 search the sam for a single string attribute in exactly 1 record
115 const char *samdb_search_string(struct ldb_context *sam_ldb,
116 TALLOC_CTX *mem_ctx,
117 struct ldb_dn *basedn,
118 const char *attr_name,
119 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
121 va_list ap;
122 const char *str;
124 va_start(ap, format);
125 str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
126 va_end(ap);
128 return str;
131 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
132 TALLOC_CTX *mem_ctx,
133 struct ldb_dn *basedn,
134 const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
136 va_list ap;
137 struct ldb_dn *ret;
138 struct ldb_message **res = NULL;
139 int count;
141 va_start(ap, format);
142 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
143 va_end(ap);
145 if (count != 1) return NULL;
147 ret = talloc_steal(mem_ctx, res[0]->dn);
148 talloc_free(res);
150 return ret;
154 search the sam for a dom_sid attribute in exactly 1 record
156 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
157 TALLOC_CTX *mem_ctx,
158 struct ldb_dn *basedn,
159 const char *attr_name,
160 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
162 va_list ap;
163 int count;
164 struct ldb_message **res;
165 const char *attrs[2] = { NULL, NULL };
166 struct dom_sid *sid;
168 attrs[0] = attr_name;
170 va_start(ap, format);
171 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
172 va_end(ap);
173 if (count > 1) {
174 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
175 attr_name, format, count));
177 if (count != 1) {
178 talloc_free(res);
179 return NULL;
181 sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
182 talloc_free(res);
183 return sid;
187 return the count of the number of records in the sam matching the query
189 int samdb_search_count(struct ldb_context *sam_ldb,
190 struct ldb_dn *basedn,
191 const char *format, ...) _PRINTF_ATTRIBUTE(3,4)
193 va_list ap;
194 struct ldb_message **res;
195 const char *attrs[] = { NULL };
196 int ret;
197 TALLOC_CTX *tmp_ctx = talloc_new(sam_ldb);
199 va_start(ap, format);
200 ret = gendb_search_v(sam_ldb, tmp_ctx, basedn, &res, attrs, format, ap);
201 va_end(ap);
202 talloc_free(tmp_ctx);
204 return ret;
209 search the sam for a single integer attribute in exactly 1 record
211 uint_t samdb_search_uint(struct ldb_context *sam_ldb,
212 TALLOC_CTX *mem_ctx,
213 uint_t default_value,
214 struct ldb_dn *basedn,
215 const char *attr_name,
216 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
218 va_list ap;
219 int count;
220 struct ldb_message **res;
221 const char *attrs[2] = { NULL, NULL };
223 attrs[0] = attr_name;
225 va_start(ap, format);
226 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
227 va_end(ap);
229 if (count != 1) {
230 return default_value;
233 return samdb_result_uint(res[0], attr_name, default_value);
237 search the sam for a single signed 64 bit integer attribute in exactly 1 record
239 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
240 TALLOC_CTX *mem_ctx,
241 int64_t default_value,
242 struct ldb_dn *basedn,
243 const char *attr_name,
244 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
246 va_list ap;
247 int count;
248 struct ldb_message **res;
249 const char *attrs[2] = { NULL, NULL };
251 attrs[0] = attr_name;
253 va_start(ap, format);
254 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
255 va_end(ap);
257 if (count != 1) {
258 return default_value;
261 return samdb_result_int64(res[0], attr_name, default_value);
265 search the sam for multipe records each giving a single string attribute
266 return the number of matches, or -1 on error
268 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
269 TALLOC_CTX *mem_ctx,
270 struct ldb_dn *basedn,
271 const char ***strs,
272 const char *attr_name,
273 const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
275 va_list ap;
276 int count, i;
277 const char *attrs[2] = { NULL, NULL };
278 struct ldb_message **res = NULL;
280 attrs[0] = attr_name;
282 va_start(ap, format);
283 count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
284 va_end(ap);
286 if (count <= 0) {
287 return count;
290 /* make sure its single valued */
291 for (i=0;i<count;i++) {
292 if (res[i]->num_elements != 1) {
293 DEBUG(1,("samdb: search for %s %s not single valued\n",
294 attr_name, format));
295 talloc_free(res);
296 return -1;
300 *strs = talloc_array(mem_ctx, const char *, count+1);
301 if (! *strs) {
302 talloc_free(res);
303 return -1;
306 for (i=0;i<count;i++) {
307 (*strs)[i] = samdb_result_string(res[i], attr_name, NULL);
309 (*strs)[count] = NULL;
311 return count;
315 pull a uint from a result set.
317 uint_t samdb_result_uint(const struct ldb_message *msg, const char *attr, uint_t default_value)
319 return ldb_msg_find_attr_as_uint(msg, attr, default_value);
323 pull a (signed) int64 from a result set.
325 int64_t samdb_result_int64(const struct ldb_message *msg, const char *attr, int64_t default_value)
327 return ldb_msg_find_attr_as_int64(msg, attr, default_value);
331 pull a string from a result set.
333 const char *samdb_result_string(const struct ldb_message *msg, const char *attr,
334 const char *default_value)
336 return ldb_msg_find_attr_as_string(msg, attr, default_value);
339 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
340 const char *attr, struct ldb_dn *default_value)
342 struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
343 if (!ret_dn) {
344 return default_value;
346 return ret_dn;
350 pull a rid from a objectSid in a result set.
352 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
353 const char *attr, uint32_t default_value)
355 struct dom_sid *sid;
356 uint32_t rid;
358 sid = samdb_result_dom_sid(mem_ctx, msg, attr);
359 if (sid == NULL) {
360 return default_value;
362 rid = sid->sub_auths[sid->num_auths-1];
363 talloc_free(sid);
364 return rid;
368 pull a dom_sid structure from a objectSid in a result set.
370 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
371 const char *attr)
373 const struct ldb_val *v;
374 struct dom_sid *sid;
375 enum ndr_err_code ndr_err;
376 v = ldb_msg_find_ldb_val(msg, attr);
377 if (v == NULL) {
378 return NULL;
380 sid = talloc(mem_ctx, struct dom_sid);
381 if (sid == NULL) {
382 return NULL;
384 ndr_err = ndr_pull_struct_blob(v, sid, NULL, sid,
385 (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
386 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
387 talloc_free(sid);
388 return NULL;
390 return sid;
394 pull a guid structure from a objectGUID in a result set.
396 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
398 const struct ldb_val *v;
399 struct GUID guid;
400 NTSTATUS status;
402 v = ldb_msg_find_ldb_val(msg, attr);
403 if (!v) return guid;
405 status = GUID_from_ndr_blob(v, &guid);
406 if (!NT_STATUS_IS_OK(status)) {
407 return GUID_zero();
410 return guid;
414 pull a sid prefix from a objectSid in a result set.
415 this is used to find the domain sid for a user
417 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
418 const char *attr)
420 struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
421 if (!sid || sid->num_auths < 1) return NULL;
422 sid->num_auths--;
423 return sid;
427 pull a NTTIME in a result set.
429 NTTIME samdb_result_nttime(struct ldb_message *msg, const char *attr, NTTIME default_value)
431 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
435 * Windows stores 0 for lastLogoff.
436 * But when a MS DC return the lastLogoff (as Logoff Time)
437 * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
438 * cause windows 2008 and newer version to fail for SMB requests
440 NTTIME samdb_result_last_logoff(struct ldb_message *msg)
442 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
444 if (ret == 0)
445 ret = 0x7FFFFFFFFFFFFFFFULL;
447 return ret;
451 * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
452 * indicate an account doesn't expire.
454 * When Windows initially creates an account, it sets
455 * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF). However,
456 * when changing from an account having a specific expiration date to
457 * that account never expiring, it sets accountExpires = 0.
459 * Consolidate that logic here to allow clearer logic for account expiry in
460 * the rest of the code.
462 NTTIME samdb_result_account_expires(struct ldb_message *msg)
464 NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
467 if (ret == 0)
468 ret = 0x7FFFFFFFFFFFFFFFULL;
470 return ret;
474 pull a uint64_t from a result set.
476 uint64_t samdb_result_uint64(struct ldb_message *msg, const char *attr, uint64_t default_value)
478 return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
483 construct the allow_password_change field from the PwdLastSet attribute and the
484 domain password settings
486 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb,
487 TALLOC_CTX *mem_ctx,
488 struct ldb_dn *domain_dn,
489 struct ldb_message *msg,
490 const char *attr)
492 uint64_t attr_time = samdb_result_uint64(msg, attr, 0);
493 int64_t minPwdAge;
495 if (attr_time == 0) {
496 return 0;
499 minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
501 /* yes, this is a -= not a += as minPwdAge is stored as the negative
502 of the number of 100-nano-seconds */
503 attr_time -= minPwdAge;
505 return attr_time;
509 construct the force_password_change field from the PwdLastSet
510 attribute, the userAccountControl and the domain password settings
512 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb,
513 TALLOC_CTX *mem_ctx,
514 struct ldb_dn *domain_dn,
515 struct ldb_message *msg)
517 uint64_t attr_time = samdb_result_uint64(msg, "pwdLastSet", 0);
518 uint32_t userAccountControl = samdb_result_uint64(msg, "userAccountControl", 0);
519 int64_t maxPwdAge;
521 /* Machine accounts don't expire, and there is a flag for 'no expiry' */
522 if (!(userAccountControl & UF_NORMAL_ACCOUNT)
523 || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
524 return 0x7FFFFFFFFFFFFFFFULL;
527 if (attr_time == 0) {
528 return 0;
531 maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "maxPwdAge", NULL);
532 if (maxPwdAge == 0) {
533 return 0x7FFFFFFFFFFFFFFFULL;
534 } else {
535 attr_time -= maxPwdAge;
538 return attr_time;
542 pull a samr_Password structutre from a result set.
544 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
546 struct samr_Password *hash = NULL;
547 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
548 if (val && (val->length >= sizeof(hash->hash))) {
549 hash = talloc(mem_ctx, struct samr_Password);
550 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
552 return hash;
556 pull an array of samr_Password structutres from a result set.
558 uint_t samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
559 const char *attr, struct samr_Password **hashes)
561 uint_t count, i;
562 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
564 *hashes = NULL;
565 if (!val) {
566 return 0;
568 count = val->length / 16;
569 if (count == 0) {
570 return 0;
573 *hashes = talloc_array(mem_ctx, struct samr_Password, count);
574 if (! *hashes) {
575 return 0;
578 for (i=0;i<count;i++) {
579 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
582 return count;
585 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct ldb_message *msg,
586 struct samr_Password **lm_pwd, struct samr_Password **nt_pwd)
588 struct samr_Password *lmPwdHash, *ntPwdHash;
589 if (nt_pwd) {
590 int num_nt;
591 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
592 if (num_nt == 0) {
593 *nt_pwd = NULL;
594 } else if (num_nt > 1) {
595 return NT_STATUS_INTERNAL_DB_CORRUPTION;
596 } else {
597 *nt_pwd = &ntPwdHash[0];
600 if (lm_pwd) {
601 /* Ensure that if we have turned off LM
602 * authentication, that we never use the LM hash, even
603 * if we store it */
604 if (lp_lanman_auth(lp_ctx)) {
605 int num_lm;
606 num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
607 if (num_lm == 0) {
608 *lm_pwd = NULL;
609 } else if (num_lm > 1) {
610 return NT_STATUS_INTERNAL_DB_CORRUPTION;
611 } else {
612 *lm_pwd = &lmPwdHash[0];
614 } else {
615 *lm_pwd = NULL;
618 return NT_STATUS_OK;
622 pull a samr_LogonHours structutre from a result set.
624 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
626 struct samr_LogonHours hours;
627 const int units_per_week = 168;
628 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
629 ZERO_STRUCT(hours);
630 hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week);
631 if (!hours.bits) {
632 return hours;
634 hours.units_per_week = units_per_week;
635 memset(hours.bits, 0xFF, units_per_week);
636 if (val) {
637 memcpy(hours.bits, val->data, MIN(val->length, units_per_week));
639 return hours;
643 pull a set of account_flags from a result set.
645 This requires that the attributes:
646 pwdLastSet
647 userAccountControl
648 be included in 'msg'
650 uint32_t samdb_result_acct_flags(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
651 struct ldb_message *msg, struct ldb_dn *domain_dn)
653 uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
654 uint32_t acct_flags = ds_uf2acb(userAccountControl);
655 NTTIME must_change_time;
656 NTTIME now;
658 must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx,
659 domain_dn, msg);
661 /* Test account expire time */
662 unix_to_nt_time(&now, time(NULL));
663 /* check for expired password */
664 if (must_change_time < now) {
665 acct_flags |= ACB_PW_EXPIRED;
667 return acct_flags;
670 struct lsa_BinaryString samdb_result_parameters(TALLOC_CTX *mem_ctx,
671 struct ldb_message *msg,
672 const char *attr)
674 struct lsa_BinaryString s;
675 const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
677 ZERO_STRUCT(s);
679 if (!val) {
680 return s;
683 s.array = talloc_array(mem_ctx, uint16_t, val->length/2);
684 if (!s.array) {
685 return s;
687 s.length = s.size = val->length/2;
688 memcpy(s.array, val->data, val->length);
690 return s;
693 /* Find an attribute, with a particular value */
695 /* The current callers of this function expect a very specific
696 * behaviour: In particular, objectClass subclass equivilance is not
697 * wanted. This means that we should not lookup the schema for the
698 * comparison function */
699 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
700 const struct ldb_message *msg,
701 const char *name, const char *value)
703 int i;
704 struct ldb_message_element *el = ldb_msg_find_element(msg, name);
706 if (!el) {
707 return NULL;
710 for (i=0;i<el->num_values;i++) {
711 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
712 return el;
716 return NULL;
719 int samdb_find_or_add_value(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
721 if (samdb_find_attribute(ldb, msg, name, set_value) == NULL) {
722 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
724 return LDB_SUCCESS;
727 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
729 struct ldb_message_element *el;
731 el = ldb_msg_find_element(msg, name);
732 if (el) {
733 return LDB_SUCCESS;
736 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
742 add a string element to a message
744 int samdb_msg_add_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
745 const char *attr_name, const char *str)
747 char *s = talloc_strdup(mem_ctx, str);
748 char *a = talloc_strdup(mem_ctx, attr_name);
749 if (s == NULL || a == NULL) {
750 return LDB_ERR_OPERATIONS_ERROR;
752 return ldb_msg_add_string(msg, a, s);
756 add a dom_sid element to a message
758 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
759 const char *attr_name, struct dom_sid *sid)
761 struct ldb_val v;
762 enum ndr_err_code ndr_err;
764 ndr_err = ndr_push_struct_blob(&v, mem_ctx,
765 lp_iconv_convenience(ldb_get_opaque(sam_ldb, "loadparm")),
766 sid,
767 (ndr_push_flags_fn_t)ndr_push_dom_sid);
768 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
769 return -1;
771 return ldb_msg_add_value(msg, attr_name, &v, NULL);
776 add a delete element operation to a message
778 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
779 const char *attr_name)
781 /* we use an empty replace rather than a delete, as it allows for
782 samdb_replace() to be used everywhere */
783 return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
787 add a add attribute value to a message
789 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
790 const char *attr_name, const char *value)
792 struct ldb_message_element *el;
793 char *a, *v;
794 int ret;
795 a = talloc_strdup(mem_ctx, attr_name);
796 if (a == NULL)
797 return -1;
798 v = talloc_strdup(mem_ctx, value);
799 if (v == NULL)
800 return -1;
801 ret = ldb_msg_add_string(msg, a, v);
802 if (ret != 0)
803 return ret;
804 el = ldb_msg_find_element(msg, a);
805 if (el == NULL)
806 return -1;
807 el->flags = LDB_FLAG_MOD_ADD;
808 return 0;
812 add a delete attribute value to a message
814 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
815 const char *attr_name, const char *value)
817 struct ldb_message_element *el;
818 char *a, *v;
819 int ret;
820 a = talloc_strdup(mem_ctx, attr_name);
821 if (a == NULL)
822 return -1;
823 v = talloc_strdup(mem_ctx, value);
824 if (v == NULL)
825 return -1;
826 ret = ldb_msg_add_string(msg, a, v);
827 if (ret != 0)
828 return ret;
829 el = ldb_msg_find_element(msg, a);
830 if (el == NULL)
831 return -1;
832 el->flags = LDB_FLAG_MOD_DELETE;
833 return 0;
837 add a int element to a message
839 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
840 const char *attr_name, int v)
842 const char *s = talloc_asprintf(mem_ctx, "%d", v);
843 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
847 add a uint_t element to a message
849 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
850 const char *attr_name, uint_t v)
852 const char *s = talloc_asprintf(mem_ctx, "%u", v);
853 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
857 add a (signed) int64_t element to a message
859 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
860 const char *attr_name, int64_t v)
862 const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
863 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
867 add a uint64_t element to a message
869 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
870 const char *attr_name, uint64_t v)
872 const char *s = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)v);
873 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
877 add a samr_Password element to a message
879 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
880 const char *attr_name, struct samr_Password *hash)
882 struct ldb_val val;
883 val.data = talloc_memdup(mem_ctx, hash->hash, 16);
884 if (!val.data) {
885 return -1;
887 val.length = 16;
888 return ldb_msg_add_value(msg, attr_name, &val, NULL);
892 add a samr_Password array to a message
894 int samdb_msg_add_hashes(TALLOC_CTX *mem_ctx, struct ldb_message *msg,
895 const char *attr_name, struct samr_Password *hashes, uint_t count)
897 struct ldb_val val;
898 int i;
899 val.data = talloc_array_size(mem_ctx, 16, count);
900 val.length = count*16;
901 if (!val.data) {
902 return -1;
904 for (i=0;i<count;i++) {
905 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
907 return ldb_msg_add_value(msg, attr_name, &val, NULL);
911 add a acct_flags element to a message
913 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
914 const char *attr_name, uint32_t v)
916 return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
920 add a logon_hours element to a message
922 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
923 const char *attr_name, struct samr_LogonHours *hours)
925 struct ldb_val val;
926 val.length = hours->units_per_week / 8;
927 val.data = hours->bits;
928 return ldb_msg_add_value(msg, attr_name, &val, NULL);
932 add a parameters element to a message
934 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
935 const char *attr_name, struct lsa_BinaryString *parameters)
937 struct ldb_val val;
938 val.length = parameters->length * 2;
939 val.data = (uint8_t *)parameters->array;
940 return ldb_msg_add_value(msg, attr_name, &val, NULL);
943 add a general value element to a message
945 int samdb_msg_add_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
946 const char *attr_name, const struct ldb_val *val)
948 return ldb_msg_add_value(msg, attr_name, val, NULL);
952 sets a general value element to a message
954 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
955 const char *attr_name, const struct ldb_val *val)
957 struct ldb_message_element *el;
959 el = ldb_msg_find_element(msg, attr_name);
960 if (el) {
961 el->num_values = 0;
963 return ldb_msg_add_value(msg, attr_name, val, NULL);
967 set a string element in a message
969 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
970 const char *attr_name, const char *str)
972 struct ldb_message_element *el;
974 el = ldb_msg_find_element(msg, attr_name);
975 if (el) {
976 el->num_values = 0;
978 return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, str);
982 replace elements in a record
984 int samdb_replace(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg)
986 int i;
988 /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
989 for (i=0;i<msg->num_elements;i++) {
990 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
993 /* modify the samdb record */
994 return ldb_modify(sam_ldb, msg);
998 return a default security descriptor
1000 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1002 struct security_descriptor *sd;
1004 sd = security_descriptor_initialise(mem_ctx);
1006 return sd;
1009 struct ldb_dn *samdb_base_dn(struct ldb_context *sam_ctx)
1011 return ldb_get_default_basedn(sam_ctx);
1014 struct ldb_dn *samdb_config_dn(struct ldb_context *sam_ctx)
1016 return ldb_get_config_basedn(sam_ctx);
1019 struct ldb_dn *samdb_schema_dn(struct ldb_context *sam_ctx)
1021 return ldb_get_schema_basedn(sam_ctx);
1024 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1026 struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1027 struct ldb_dn *aggregate_dn;
1028 if (!schema_dn) {
1029 return NULL;
1032 aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1033 if (!aggregate_dn) {
1034 return NULL;
1036 if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1037 return NULL;
1039 return aggregate_dn;
1042 struct ldb_dn *samdb_root_dn(struct ldb_context *sam_ctx)
1044 return ldb_get_root_basedn(sam_ctx);
1047 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1049 struct ldb_dn *new_dn;
1051 new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1052 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1053 talloc_free(new_dn);
1054 return NULL;
1056 return new_dn;
1059 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1061 struct ldb_dn *new_dn;
1063 new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1064 if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1065 talloc_free(new_dn);
1066 return NULL;
1068 return new_dn;
1072 work out the domain sid for the current open ldb
1074 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1076 TALLOC_CTX *tmp_ctx;
1077 const struct dom_sid *domain_sid;
1078 const char *attrs[] = {
1079 "objectSid",
1080 NULL
1082 struct ldb_result *res;
1083 int ret;
1085 /* see if we have a cached copy */
1086 domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1087 if (domain_sid) {
1088 return domain_sid;
1091 tmp_ctx = talloc_new(ldb);
1092 if (tmp_ctx == NULL) {
1093 goto failed;
1096 ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1098 if (ret != LDB_SUCCESS) {
1099 goto failed;
1102 if (res->count != 1) {
1103 goto failed;
1106 domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1107 if (domain_sid == NULL) {
1108 goto failed;
1111 /* cache the domain_sid in the ldb */
1112 if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1113 goto failed;
1116 talloc_steal(ldb, domain_sid);
1117 talloc_free(tmp_ctx);
1119 return domain_sid;
1121 failed:
1122 DEBUG(1,("Failed to find domain_sid for open ldb\n"));
1123 talloc_free(tmp_ctx);
1124 return NULL;
1127 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1129 TALLOC_CTX *tmp_ctx;
1130 struct dom_sid *dom_sid_new;
1131 struct dom_sid *dom_sid_old;
1133 /* see if we have a cached copy */
1134 dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1135 "cache.domain_sid"), struct dom_sid);
1137 tmp_ctx = talloc_new(ldb);
1138 if (tmp_ctx == NULL) {
1139 goto failed;
1142 dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1143 if (!dom_sid_new) {
1144 goto failed;
1147 /* cache the domain_sid in the ldb */
1148 if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1149 goto failed;
1152 talloc_steal(ldb, dom_sid_new);
1153 talloc_free(tmp_ctx);
1154 talloc_free(dom_sid_old);
1156 return true;
1158 failed:
1159 DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1160 talloc_free(tmp_ctx);
1161 return false;
1164 /* Obtain the short name of the flexible single master operator
1165 * (FSMO), such as the PDC Emulator */
1166 const char *samdb_result_fsmo_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
1167 const char *attr)
1169 /* Format is cn=NTDS Settings,cn=<NETBIOS name of FSMO>,.... */
1170 struct ldb_dn *fsmo_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
1171 const struct ldb_val *val = ldb_dn_get_component_val(fsmo_dn, 1);
1172 const char *name = ldb_dn_get_component_name(fsmo_dn, 1);
1174 if (!name || (ldb_attr_cmp(name, "cn") != 0)) {
1175 /* Ensure this matches the format. This gives us a
1176 * bit more confidence that a 'cn' value will be a
1177 * ascii string */
1178 return NULL;
1180 if (val) {
1181 return (char *)val->data;
1183 return NULL;
1187 work out the ntds settings dn for the current open ldb
1189 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1191 TALLOC_CTX *tmp_ctx;
1192 const char *root_attrs[] = { "dsServiceName", NULL };
1193 int ret;
1194 struct ldb_result *root_res;
1195 struct ldb_dn *settings_dn;
1197 /* see if we have a cached copy */
1198 settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "cache.settings_dn");
1199 if (settings_dn) {
1200 return settings_dn;
1203 tmp_ctx = talloc_new(ldb);
1204 if (tmp_ctx == NULL) {
1205 goto failed;
1208 ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1209 if (ret) {
1210 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1211 ldb_errstring(ldb)));
1212 goto failed;
1215 if (root_res->count != 1) {
1216 goto failed;
1219 settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1221 /* cache the domain_sid in the ldb */
1222 if (ldb_set_opaque(ldb, "cache.settings_dn", settings_dn) != LDB_SUCCESS) {
1223 goto failed;
1226 talloc_steal(ldb, settings_dn);
1227 talloc_free(tmp_ctx);
1229 return settings_dn;
1231 failed:
1232 DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1233 talloc_free(tmp_ctx);
1234 return NULL;
1238 work out the ntds settings invocationId for the current open ldb
1240 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1242 TALLOC_CTX *tmp_ctx;
1243 const char *attrs[] = { "invocationId", NULL };
1244 int ret;
1245 struct ldb_result *res;
1246 struct GUID *invocation_id;
1248 /* see if we have a cached copy */
1249 invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1250 if (invocation_id) {
1251 return invocation_id;
1254 tmp_ctx = talloc_new(ldb);
1255 if (tmp_ctx == NULL) {
1256 goto failed;
1259 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1260 if (ret) {
1261 goto failed;
1264 if (res->count != 1) {
1265 goto failed;
1268 invocation_id = talloc(tmp_ctx, struct GUID);
1269 if (!invocation_id) {
1270 goto failed;
1273 *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1275 /* cache the domain_sid in the ldb */
1276 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1277 goto failed;
1280 talloc_steal(ldb, invocation_id);
1281 talloc_free(tmp_ctx);
1283 return invocation_id;
1285 failed:
1286 DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1287 talloc_free(tmp_ctx);
1288 return NULL;
1291 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1293 TALLOC_CTX *tmp_ctx;
1294 struct GUID *invocation_id_new;
1295 struct GUID *invocation_id_old;
1297 /* see if we have a cached copy */
1298 invocation_id_old = (struct GUID *)ldb_get_opaque(ldb,
1299 "cache.invocation_id");
1301 tmp_ctx = talloc_new(ldb);
1302 if (tmp_ctx == NULL) {
1303 goto failed;
1306 invocation_id_new = talloc(tmp_ctx, struct GUID);
1307 if (!invocation_id_new) {
1308 goto failed;
1311 *invocation_id_new = *invocation_id_in;
1313 /* cache the domain_sid in the ldb */
1314 if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1315 goto failed;
1318 talloc_steal(ldb, invocation_id_new);
1319 talloc_free(tmp_ctx);
1320 talloc_free(invocation_id_old);
1322 return true;
1324 failed:
1325 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1326 talloc_free(tmp_ctx);
1327 return false;
1331 work out the ntds settings objectGUID for the current open ldb
1333 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1335 TALLOC_CTX *tmp_ctx;
1336 const char *attrs[] = { "objectGUID", NULL };
1337 int ret;
1338 struct ldb_result *res;
1339 struct GUID *ntds_guid;
1341 /* see if we have a cached copy */
1342 ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1343 if (ntds_guid) {
1344 return ntds_guid;
1347 tmp_ctx = talloc_new(ldb);
1348 if (tmp_ctx == NULL) {
1349 goto failed;
1352 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1353 if (ret) {
1354 goto failed;
1357 if (res->count != 1) {
1358 goto failed;
1361 ntds_guid = talloc(tmp_ctx, struct GUID);
1362 if (!ntds_guid) {
1363 goto failed;
1366 *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1368 /* cache the domain_sid in the ldb */
1369 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1370 goto failed;
1373 talloc_steal(ldb, ntds_guid);
1374 talloc_free(tmp_ctx);
1376 return ntds_guid;
1378 failed:
1379 DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1380 talloc_free(tmp_ctx);
1381 return NULL;
1384 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1386 TALLOC_CTX *tmp_ctx;
1387 struct GUID *ntds_guid_new;
1388 struct GUID *ntds_guid_old;
1390 /* see if we have a cached copy */
1391 ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1393 tmp_ctx = talloc_new(ldb);
1394 if (tmp_ctx == NULL) {
1395 goto failed;
1398 ntds_guid_new = talloc(tmp_ctx, struct GUID);
1399 if (!ntds_guid_new) {
1400 goto failed;
1403 *ntds_guid_new = *ntds_guid_in;
1405 /* cache the domain_sid in the ldb */
1406 if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1407 goto failed;
1410 talloc_steal(ldb, ntds_guid_new);
1411 talloc_free(tmp_ctx);
1412 talloc_free(ntds_guid_old);
1414 return true;
1416 failed:
1417 DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1418 talloc_free(tmp_ctx);
1419 return false;
1423 work out the server dn for the current open ldb
1425 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1427 return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1431 work out the server dn for the current open ldb
1433 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1435 struct ldb_dn *server_dn;
1436 struct ldb_dn *server_site_dn;
1438 server_dn = samdb_server_dn(ldb, mem_ctx);
1439 if (!server_dn) return NULL;
1441 server_site_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1443 talloc_free(server_dn);
1444 return server_site_dn;
1447 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1449 const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb, mem_ctx));
1451 if (val != NULL)
1452 return (const char *) val->data;
1453 else
1454 return NULL;
1458 work out if we are the PDC for the domain of the current open ldb
1460 bool samdb_is_pdc(struct ldb_context *ldb)
1462 const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1463 int ret;
1464 struct ldb_result *dom_res;
1465 TALLOC_CTX *tmp_ctx;
1466 bool is_pdc;
1467 struct ldb_dn *pdc;
1469 tmp_ctx = talloc_new(ldb);
1470 if (tmp_ctx == NULL) {
1471 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1472 return false;
1475 ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1476 if (ret) {
1477 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n",
1478 ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
1479 ldb_errstring(ldb)));
1480 goto failed;
1482 if (dom_res->count != 1) {
1483 goto failed;
1486 pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1488 if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1489 is_pdc = true;
1490 } else {
1491 is_pdc = false;
1494 talloc_free(tmp_ctx);
1496 return is_pdc;
1498 failed:
1499 DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1500 talloc_free(tmp_ctx);
1501 return false;
1505 work out if we are a Global Catalog server for the domain of the current open ldb
1507 bool samdb_is_gc(struct ldb_context *ldb)
1509 const char *attrs[] = { "options", NULL };
1510 int ret, options;
1511 struct ldb_result *res;
1512 TALLOC_CTX *tmp_ctx;
1514 tmp_ctx = talloc_new(ldb);
1515 if (tmp_ctx == NULL) {
1516 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1517 return false;
1520 /* Query cn=ntds settings,.... */
1521 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1522 if (ret) {
1523 talloc_free(tmp_ctx);
1524 return false;
1526 if (res->count != 1) {
1527 talloc_free(tmp_ctx);
1528 return false;
1531 options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1532 talloc_free(tmp_ctx);
1534 /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1535 if (options & 0x000000001) {
1536 return true;
1538 return false;
1541 /* Find a domain object in the parents of a particular DN. */
1542 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1543 struct ldb_dn **parent_dn, const char **errstring)
1545 TALLOC_CTX *local_ctx;
1546 struct ldb_dn *sdn = dn;
1547 struct ldb_result *res = NULL;
1548 int ret = 0;
1549 const char *attrs[] = { NULL };
1551 local_ctx = talloc_new(mem_ctx);
1552 if (local_ctx == NULL) return LDB_ERR_OPERATIONS_ERROR;
1554 while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1555 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1556 "(|(objectClass=domain)(objectClass=builtinDomain))");
1557 if (ret == LDB_SUCCESS) {
1558 if (res->count == 1) {
1559 break;
1561 } else {
1562 break;
1566 if (ret != LDB_SUCCESS) {
1567 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1568 ldb_dn_get_linearized(dn),
1569 ldb_dn_get_linearized(sdn),
1570 ldb_errstring(ldb));
1571 talloc_free(local_ctx);
1572 return ret;
1574 if (res->count != 1) {
1575 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1576 ldb_dn_get_linearized(dn));
1577 DEBUG(0,(__location__ ": %s\n", *errstring));
1578 talloc_free(local_ctx);
1579 return LDB_ERR_CONSTRAINT_VIOLATION;
1582 *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1583 talloc_free(local_ctx);
1584 return ret;
1589 * Performs checks on a user password (plaintext UNIX format - attribute
1590 * "password"). The remaining parameters have to be extracted from the domain
1591 * object in the AD.
1593 * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1595 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1596 const uint32_t pwdProperties,
1597 const uint32_t minPwdLength)
1599 /* checks if the "minPwdLength" property is satisfied */
1600 if (minPwdLength > password->length)
1601 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1603 /* checks the password complexity */
1604 if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1605 && (password->data != NULL)
1606 && (!check_password_quality((const char *) password->data)))
1607 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1609 return SAMR_VALIDATION_STATUS_SUCCESS;
1613 * Sets the user password using plaintext UTF16 (attribute "new_password") or
1614 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1615 * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1616 * gives some more informations if the changed failed.
1618 * The caller should have a LDB transaction wrapping this.
1620 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
1621 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1622 * NT_STATUS_PASSWORD_RESTRICTION
1624 NTSTATUS samdb_set_password(struct ldb_context *ctx, TALLOC_CTX *mem_ctx,
1625 struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1626 struct ldb_message *mod,
1627 const DATA_BLOB *new_password,
1628 struct samr_Password *param_lmNewHash,
1629 struct samr_Password *param_ntNewHash,
1630 bool user_change,
1631 enum samPwdChangeReason *reject_reason,
1632 struct samr_DomInfo1 **_dominfo)
1634 const char * const user_attrs[] = { "userAccountControl",
1635 "lmPwdHistory",
1636 "ntPwdHistory",
1637 "dBCSPwd", "unicodePwd",
1638 "objectSid",
1639 "pwdLastSet", NULL };
1640 const char * const domain_attrs[] = { "minPwdLength", "pwdProperties",
1641 "pwdHistoryLength",
1642 "maxPwdAge", "minPwdAge", NULL };
1643 NTTIME pwdLastSet;
1644 uint32_t minPwdLength, pwdProperties, pwdHistoryLength;
1645 int64_t maxPwdAge, minPwdAge;
1646 uint32_t userAccountControl;
1647 struct samr_Password *sambaLMPwdHistory, *sambaNTPwdHistory,
1648 *lmPwdHash, *ntPwdHash, *lmNewHash, *ntNewHash;
1649 struct samr_Password local_lmNewHash, local_ntNewHash;
1650 int sambaLMPwdHistory_len, sambaNTPwdHistory_len;
1651 struct dom_sid *domain_sid;
1652 struct ldb_message **res;
1653 bool restrictions;
1654 int count;
1655 time_t now = time(NULL);
1656 NTTIME now_nt;
1657 int i;
1659 /* we need to know the time to compute password age */
1660 unix_to_nt_time(&now_nt, now);
1662 /* pull all the user parameters */
1663 count = gendb_search_dn(ctx, mem_ctx, user_dn, &res, user_attrs);
1664 if (count != 1) {
1665 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1667 userAccountControl = samdb_result_uint(res[0], "userAccountControl", 0);
1668 sambaLMPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1669 "lmPwdHistory", &sambaLMPwdHistory);
1670 sambaNTPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1671 "ntPwdHistory", &sambaNTPwdHistory);
1672 lmPwdHash = samdb_result_hash(mem_ctx, res[0], "dBCSPwd");
1673 ntPwdHash = samdb_result_hash(mem_ctx, res[0], "unicodePwd");
1674 pwdLastSet = samdb_result_uint64(res[0], "pwdLastSet", 0);
1676 /* Copy parameters */
1677 lmNewHash = param_lmNewHash;
1678 ntNewHash = param_ntNewHash;
1680 /* Only non-trust accounts have restrictions (possibly this
1681 * test is the wrong way around, but I like to be restrictive
1682 * if possible */
1683 restrictions = !(userAccountControl & (UF_INTERDOMAIN_TRUST_ACCOUNT
1684 |UF_WORKSTATION_TRUST_ACCOUNT
1685 |UF_SERVER_TRUST_ACCOUNT));
1687 if (domain_dn != NULL) {
1688 /* pull the domain parameters */
1689 count = gendb_search_dn(ctx, mem_ctx, domain_dn, &res,
1690 domain_attrs);
1691 if (count != 1) {
1692 DEBUG(2, ("samdb_set_password: Domain DN %s is invalid, for user %s\n",
1693 ldb_dn_get_linearized(domain_dn),
1694 ldb_dn_get_linearized(user_dn)));
1695 return NT_STATUS_NO_SUCH_DOMAIN;
1697 } else {
1698 /* work out the domain sid, and pull the domain from there */
1699 domain_sid = samdb_result_sid_prefix(mem_ctx, res[0],
1700 "objectSid");
1701 if (domain_sid == NULL) {
1702 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1705 count = gendb_search(ctx, mem_ctx, NULL, &res, domain_attrs,
1706 "(objectSid=%s)",
1707 ldap_encode_ndr_dom_sid(mem_ctx, domain_sid));
1708 if (count != 1) {
1709 DEBUG(2, ("samdb_set_password: Could not find domain to match SID: %s, for user %s\n",
1710 dom_sid_string(mem_ctx, domain_sid),
1711 ldb_dn_get_linearized(user_dn)));
1712 return NT_STATUS_NO_SUCH_DOMAIN;
1716 minPwdLength = samdb_result_uint(res[0], "minPwdLength", 0);
1717 pwdProperties = samdb_result_uint(res[0], "pwdProperties", 0);
1718 pwdHistoryLength = samdb_result_uint(res[0], "pwdHistoryLength", 0);
1719 maxPwdAge = samdb_result_int64(res[0], "maxPwdAge", 0);
1720 minPwdAge = samdb_result_int64(res[0], "minPwdAge", 0);
1722 if ((userAccountControl & UF_PASSWD_NOTREQD) != 0) {
1723 /* see [MS-ADTS] 2.2.15 */
1724 minPwdLength = 0;
1727 if (_dominfo != NULL) {
1728 struct samr_DomInfo1 *dominfo;
1729 /* on failure we need to fill in the reject reasons */
1730 dominfo = talloc(mem_ctx, struct samr_DomInfo1);
1731 if (dominfo == NULL) {
1732 return NT_STATUS_NO_MEMORY;
1734 dominfo->min_password_length = minPwdLength;
1735 dominfo->password_properties = pwdProperties;
1736 dominfo->password_history_length = pwdHistoryLength;
1737 dominfo->max_password_age = maxPwdAge;
1738 dominfo->min_password_age = minPwdAge;
1739 *_dominfo = dominfo;
1742 if ((restrictions != 0) && (new_password != 0)) {
1743 char *new_pass;
1745 /* checks if the "minPwdLength" property is satisfied */
1746 if ((restrictions != 0)
1747 && (minPwdLength > utf16_len_n(
1748 new_password->data, new_password->length)/2)) {
1749 if (reject_reason) {
1750 *reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
1752 return NT_STATUS_PASSWORD_RESTRICTION;
1755 /* Create the NT hash */
1756 mdfour(local_ntNewHash.hash, new_password->data,
1757 new_password->length);
1759 ntNewHash = &local_ntNewHash;
1761 /* Only check complexity if we can convert it at all. Assuming unconvertable passwords are 'strong' */
1762 if (convert_string_talloc_convenience(mem_ctx,
1763 lp_iconv_convenience(ldb_get_opaque(ctx, "loadparm")),
1764 CH_UTF16, CH_UNIX,
1765 new_password->data, new_password->length,
1766 (void **)&new_pass, NULL, false)) {
1768 /* checks the password complexity */
1769 if ((restrictions != 0)
1770 && ((pwdProperties
1771 & DOMAIN_PASSWORD_COMPLEX) != 0)
1772 && (!check_password_quality(new_pass))) {
1773 if (reject_reason) {
1774 *reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
1776 return NT_STATUS_PASSWORD_RESTRICTION;
1779 /* compute the new lm hashes (for checking history - case insenitivly!) */
1780 if (E_deshash(new_pass, local_lmNewHash.hash)) {
1781 lmNewHash = &local_lmNewHash;
1786 if ((restrictions != 0) && user_change) {
1787 /* are all password changes disallowed? */
1788 if ((pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) != 0) {
1789 if (reject_reason) {
1790 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1792 return NT_STATUS_PASSWORD_RESTRICTION;
1795 /* can this user change the password? */
1796 if ((userAccountControl & UF_PASSWD_CANT_CHANGE) != 0) {
1797 if (reject_reason) {
1798 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1800 return NT_STATUS_PASSWORD_RESTRICTION;
1803 /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
1804 if (pwdLastSet - minPwdAge > now_nt) {
1805 if (reject_reason) {
1806 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1808 return NT_STATUS_PASSWORD_RESTRICTION;
1811 /* check the immediately past password */
1812 if (pwdHistoryLength > 0) {
1813 if (lmNewHash && lmPwdHash && memcmp(lmNewHash->hash,
1814 lmPwdHash->hash, 16) == 0) {
1815 if (reject_reason) {
1816 *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1818 return NT_STATUS_PASSWORD_RESTRICTION;
1820 if (ntNewHash && ntPwdHash && memcmp(ntNewHash->hash,
1821 ntPwdHash->hash, 16) == 0) {
1822 if (reject_reason) {
1823 *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1825 return NT_STATUS_PASSWORD_RESTRICTION;
1829 /* check the password history */
1830 sambaLMPwdHistory_len = MIN(sambaLMPwdHistory_len,
1831 pwdHistoryLength);
1832 sambaNTPwdHistory_len = MIN(sambaNTPwdHistory_len,
1833 pwdHistoryLength);
1835 for (i=0; lmNewHash && i<sambaLMPwdHistory_len;i++) {
1836 if (memcmp(lmNewHash->hash, sambaLMPwdHistory[i].hash,
1837 16) == 0) {
1838 if (reject_reason) {
1839 *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1841 return NT_STATUS_PASSWORD_RESTRICTION;
1844 for (i=0; ntNewHash && i<sambaNTPwdHistory_len;i++) {
1845 if (memcmp(ntNewHash->hash, sambaNTPwdHistory[i].hash,
1846 16) == 0) {
1847 if (reject_reason) {
1848 *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1850 return NT_STATUS_PASSWORD_RESTRICTION;
1855 #define CHECK_RET(x) do { if (x != 0) return NT_STATUS_NO_MEMORY; } while(0)
1857 /* the password is acceptable. Start forming the new fields */
1858 if (new_password != NULL) {
1859 /* if we know the cleartext UTF16 password, then set it.
1860 * Modules in ldb will set all the appropriate
1861 * hashes */
1862 CHECK_RET(ldb_msg_add_value(mod, "clearTextPassword", new_password, NULL));
1863 } else {
1864 /* We don't have the cleartext, so delete the old one
1865 * and set what we have of the hashes */
1866 CHECK_RET(samdb_msg_add_delete(ctx, mem_ctx, mod, "clearTextPassword"));
1868 if (lmNewHash) {
1869 CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "dBCSPwd", lmNewHash));
1870 } else {
1871 CHECK_RET(samdb_msg_add_delete(ctx, mem_ctx, mod, "dBCSPwd"));
1874 if (ntNewHash) {
1875 CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "unicodePwd", ntNewHash));
1876 } else {
1877 CHECK_RET(samdb_msg_add_delete(ctx, mem_ctx, mod, "unicodePwd"));
1881 if (reject_reason) {
1882 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1884 return NT_STATUS_OK;
1889 * Sets the user password using plaintext UTF16 (attribute "new_password") or
1890 * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1891 * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1892 * gives some more informations if the changed failed.
1894 * This wrapper function for "samdb_set_password" takes a SID as input rather
1895 * than a user DN.
1897 * This call encapsulates a new LDB transaction for changing the password;
1898 * therefore the user hasn't to start a new one.
1900 * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
1901 * NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1902 * NT_STATUS_PASSWORD_RESTRICTION
1904 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1905 const struct dom_sid *user_sid,
1906 const DATA_BLOB *new_password,
1907 struct samr_Password *lmNewHash,
1908 struct samr_Password *ntNewHash,
1909 bool user_change,
1910 enum samPwdChangeReason *reject_reason,
1911 struct samr_DomInfo1 **_dominfo)
1913 NTSTATUS nt_status;
1914 struct ldb_dn *user_dn;
1915 struct ldb_message *msg;
1916 int ret;
1918 ret = ldb_transaction_start(ldb);
1919 if (ret != LDB_SUCCESS) {
1920 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
1921 return NT_STATUS_TRANSACTION_ABORTED;
1924 user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
1925 "(&(objectSid=%s)(objectClass=user))",
1926 ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
1927 if (!user_dn) {
1928 ldb_transaction_cancel(ldb);
1929 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
1930 dom_sid_string(mem_ctx, user_sid)));
1931 return NT_STATUS_NO_SUCH_USER;
1934 msg = ldb_msg_new(mem_ctx);
1935 if (msg == NULL) {
1936 ldb_transaction_cancel(ldb);
1937 talloc_free(user_dn);
1938 return NT_STATUS_NO_MEMORY;
1941 msg->dn = ldb_dn_copy(msg, user_dn);
1942 if (!msg->dn) {
1943 ldb_transaction_cancel(ldb);
1944 talloc_free(user_dn);
1945 talloc_free(msg);
1946 return NT_STATUS_NO_MEMORY;
1949 nt_status = samdb_set_password(ldb, mem_ctx,
1950 user_dn, NULL,
1951 msg, new_password,
1952 lmNewHash, ntNewHash,
1953 user_change,
1954 reject_reason, _dominfo);
1955 if (!NT_STATUS_IS_OK(nt_status)) {
1956 ldb_transaction_cancel(ldb);
1957 talloc_free(user_dn);
1958 talloc_free(msg);
1959 return nt_status;
1962 /* modify the samdb record */
1963 ret = samdb_replace(ldb, mem_ctx, msg);
1964 if (ret != LDB_SUCCESS) {
1965 ldb_transaction_cancel(ldb);
1966 talloc_free(user_dn);
1967 talloc_free(msg);
1968 return NT_STATUS_ACCESS_DENIED;
1971 talloc_free(msg);
1973 ret = ldb_transaction_commit(ldb);
1974 if (ret != LDB_SUCCESS) {
1975 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
1976 ldb_dn_get_linearized(user_dn),
1977 ldb_errstring(ldb)));
1978 talloc_free(user_dn);
1979 return NT_STATUS_TRANSACTION_ABORTED;
1982 talloc_free(user_dn);
1983 return NT_STATUS_OK;
1987 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
1988 struct dom_sid *sid, struct ldb_dn **ret_dn)
1990 struct ldb_message *msg;
1991 struct ldb_dn *basedn;
1992 const char *sidstr;
1993 int ret;
1995 sidstr = dom_sid_string(mem_ctx, sid);
1996 NT_STATUS_HAVE_NO_MEMORY(sidstr);
1998 /* We might have to create a ForeignSecurityPrincipal, even if this user
1999 * is in our own domain */
2001 msg = ldb_msg_new(mem_ctx);
2002 if (msg == NULL) {
2003 return NT_STATUS_NO_MEMORY;
2006 /* TODO: Hmmm. This feels wrong. How do I find the base dn to
2007 * put the ForeignSecurityPrincipals? d_state->domain_dn does
2008 * not work, this is wrong for the Builtin domain, there's no
2009 * cn=For...,cn=Builtin,dc={BASEDN}. -- vl
2012 basedn = samdb_search_dn(sam_ctx, mem_ctx, NULL,
2013 "(&(objectClass=container)(cn=ForeignSecurityPrincipals))");
2015 if (basedn == NULL) {
2016 DEBUG(0, ("Failed to find DN for "
2017 "ForeignSecurityPrincipal container\n"));
2018 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2021 /* add core elements to the ldb_message for the alias */
2022 msg->dn = ldb_dn_copy(mem_ctx, basedn);
2023 if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr))
2024 return NT_STATUS_NO_MEMORY;
2026 samdb_msg_add_string(sam_ctx, mem_ctx, msg,
2027 "objectClass",
2028 "foreignSecurityPrincipal");
2030 /* create the alias */
2031 ret = ldb_add(sam_ctx, msg);
2032 if (ret != 0) {
2033 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2034 "record %s: %s\n",
2035 ldb_dn_get_linearized(msg->dn),
2036 ldb_errstring(sam_ctx)));
2037 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2039 *ret_dn = msg->dn;
2040 return NT_STATUS_OK;
2045 Find the DN of a domain, assuming it to be a dotted.dns name
2048 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
2050 int i;
2051 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2052 const char *binary_encoded;
2053 const char **split_realm;
2054 struct ldb_dn *dn;
2056 if (!tmp_ctx) {
2057 return NULL;
2060 split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2061 if (!split_realm) {
2062 talloc_free(tmp_ctx);
2063 return NULL;
2065 dn = ldb_dn_new(mem_ctx, ldb, NULL);
2066 for (i=0; split_realm[i]; i++) {
2067 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2068 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2069 DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2070 binary_encoded, ldb_dn_get_linearized(dn)));
2071 talloc_free(tmp_ctx);
2072 return NULL;
2075 if (!ldb_dn_validate(dn)) {
2076 DEBUG(2, ("Failed to validated DN %s\n",
2077 ldb_dn_get_linearized(dn)));
2078 return NULL;
2080 return dn;
2083 Find the DN of a domain, be it the netbios or DNS name
2086 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2087 const char *domain_name)
2089 const char * const domain_ref_attrs[] = {
2090 "ncName", NULL
2092 const char * const domain_ref2_attrs[] = {
2093 NULL
2095 struct ldb_result *res_domain_ref;
2096 char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2097 /* find the domain's DN */
2098 int ret_domain = ldb_search(ldb, mem_ctx,
2099 &res_domain_ref,
2100 samdb_partitions_dn(ldb, mem_ctx),
2101 LDB_SCOPE_ONELEVEL,
2102 domain_ref_attrs,
2103 "(&(nETBIOSName=%s)(objectclass=crossRef))",
2104 escaped_domain);
2105 if (ret_domain != 0) {
2106 return NULL;
2109 if (res_domain_ref->count == 0) {
2110 ret_domain = ldb_search(ldb, mem_ctx,
2111 &res_domain_ref,
2112 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2113 LDB_SCOPE_BASE,
2114 domain_ref2_attrs,
2115 "(objectclass=domain)");
2116 if (ret_domain != 0) {
2117 return NULL;
2120 if (res_domain_ref->count == 1) {
2121 return res_domain_ref->msgs[0]->dn;
2123 return NULL;
2126 if (res_domain_ref->count > 1) {
2127 DEBUG(0,("Found %d records matching domain [%s]\n",
2128 ret_domain, domain_name));
2129 return NULL;
2132 return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2138 use a GUID to find a DN
2140 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
2141 TALLOC_CTX *mem_ctx,
2142 const char *guid_str, struct ldb_dn **dn)
2144 int ret;
2145 struct ldb_result *res;
2146 const char *attrs[] = { NULL };
2147 struct ldb_request *search_req;
2148 char *expression;
2149 struct ldb_search_options_control *options;
2151 expression = talloc_asprintf(mem_ctx, "objectGUID=%s", guid_str);
2152 if (!expression) {
2153 DEBUG(0, (__location__ ": out of memory\n"));
2154 return LDB_ERR_OPERATIONS_ERROR;
2157 res = talloc_zero(mem_ctx, struct ldb_result);
2158 if (!res) {
2159 DEBUG(0, (__location__ ": out of memory\n"));
2160 return LDB_ERR_OPERATIONS_ERROR;
2163 ret = ldb_build_search_req(&search_req, ldb, mem_ctx,
2164 ldb_get_default_basedn(ldb),
2165 LDB_SCOPE_SUBTREE,
2166 expression, attrs,
2167 NULL,
2168 res, ldb_search_default_callback,
2169 NULL);
2170 if (ret != LDB_SUCCESS) {
2171 return ret;
2174 /* we need to cope with cross-partition links, so search for
2175 the GUID over all partitions */
2176 options = talloc(search_req, struct ldb_search_options_control);
2177 if (options == NULL) {
2178 DEBUG(0, (__location__ ": out of memory\n"));
2179 return LDB_ERR_OPERATIONS_ERROR;
2181 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
2183 ret = ldb_request_add_control(search_req, LDB_CONTROL_EXTENDED_DN_OID, true, NULL);
2184 if (ret != LDB_SUCCESS) {
2185 return ret;
2188 ret = ldb_request_add_control(search_req,
2189 LDB_CONTROL_SEARCH_OPTIONS_OID,
2190 true, options);
2191 if (ret != LDB_SUCCESS) {
2192 return ret;
2195 ret = ldb_request(ldb, search_req);
2196 if (ret != LDB_SUCCESS) {
2197 return ret;
2200 ret = ldb_wait(search_req->handle, LDB_WAIT_ALL);
2201 if (ret != LDB_SUCCESS) {
2202 return ret;
2205 /* this really should be exactly 1, but there is a bug in the
2206 partitions module that can return two here with the
2207 search_options control set */
2208 if (res->count < 1) {
2209 return LDB_ERR_NO_SUCH_OBJECT;
2212 *dn = res->msgs[0]->dn;
2214 return LDB_SUCCESS;
2218 search for attrs on one DN, allowing for deleted objects
2220 int dsdb_search_dn_with_deleted(struct ldb_context *ldb,
2221 TALLOC_CTX *mem_ctx,
2222 struct ldb_result **_res,
2223 struct ldb_dn *basedn,
2224 const char * const *attrs)
2226 int ret;
2227 struct ldb_request *req;
2228 TALLOC_CTX *tmp_ctx;
2229 struct ldb_result *res;
2231 tmp_ctx = talloc_new(mem_ctx);
2233 res = talloc_zero(tmp_ctx, struct ldb_result);
2234 if (!res) {
2235 return LDB_ERR_OPERATIONS_ERROR;
2238 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2239 basedn,
2240 LDB_SCOPE_BASE,
2241 NULL,
2242 attrs,
2243 NULL,
2244 res,
2245 ldb_search_default_callback,
2246 NULL);
2247 if (ret != LDB_SUCCESS) {
2248 talloc_free(tmp_ctx);
2249 return ret;
2252 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
2253 if (ret != LDB_SUCCESS) {
2254 return ret;
2257 ret = ldb_request(ldb, req);
2258 if (ret == LDB_SUCCESS) {
2259 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2262 talloc_free(req);
2263 *_res = talloc_steal(mem_ctx, res);
2264 return ret;
2269 use a DN to find a GUID
2271 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2272 struct ldb_dn *dn, struct GUID *guid)
2274 int ret;
2275 struct ldb_result *res;
2276 const char *attrs[] = { "objectGUID", NULL };
2277 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2279 ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2280 if (ret != LDB_SUCCESS) {
2281 talloc_free(tmp_ctx);
2282 return ret;
2284 if (res->count < 1) {
2285 talloc_free(tmp_ctx);
2286 return LDB_ERR_NO_SUCH_OBJECT;
2288 *guid = samdb_result_guid(res->msgs[0], "objectGUID");
2289 talloc_free(tmp_ctx);
2290 return LDB_SUCCESS;
2296 adds the given GUID to the given ldb_message. This value is added
2297 for the given attr_name (may be either "objectGUID" or "parentGUID").
2299 int dsdb_msg_add_guid(struct ldb_message *msg,
2300 struct GUID *guid,
2301 const char *attr_name)
2303 int ret;
2304 struct ldb_val v;
2305 NTSTATUS status;
2306 TALLOC_CTX *tmp_ctx = talloc_init("dsdb_msg_add_guid");
2308 status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2309 if (!NT_STATUS_IS_OK(status)) {
2310 ret = LDB_ERR_OPERATIONS_ERROR;
2311 goto done;
2314 ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2315 if (ret != LDB_SUCCESS) {
2316 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2317 attr_name));
2318 goto done;
2321 ret = LDB_SUCCESS;
2323 done:
2324 talloc_free(tmp_ctx);
2325 return ret;
2331 use a DN to find a SID
2333 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
2334 struct ldb_dn *dn, struct dom_sid *sid)
2336 int ret;
2337 struct ldb_result *res;
2338 const char *attrs[] = { "objectSID", NULL };
2339 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2340 struct dom_sid *s;
2342 ZERO_STRUCTP(sid);
2344 ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2345 if (ret != LDB_SUCCESS) {
2346 talloc_free(tmp_ctx);
2347 return ret;
2349 if (res->count < 1) {
2350 talloc_free(tmp_ctx);
2351 return LDB_ERR_NO_SUCH_OBJECT;
2353 s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2354 if (s == NULL) {
2355 talloc_free(tmp_ctx);
2356 return LDB_ERR_NO_SUCH_OBJECT;
2358 *sid = *s;
2359 talloc_free(tmp_ctx);
2360 return LDB_SUCCESS;
2366 load a repsFromTo blob list for a given partition GUID
2367 attr must be "repsFrom" or "repsTo"
2369 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2370 const char *attr, struct repsFromToBlob **r, uint32_t *count)
2372 const char *attrs[] = { attr, NULL };
2373 struct ldb_result *res = NULL;
2374 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2375 int i;
2376 struct ldb_message_element *el;
2378 *r = NULL;
2379 *count = 0;
2381 if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2382 res->count < 1) {
2383 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2384 talloc_free(tmp_ctx);
2385 return WERR_DS_DRA_INTERNAL_ERROR;
2388 el = ldb_msg_find_element(res->msgs[0], attr);
2389 if (el == NULL) {
2390 /* it's OK to be empty */
2391 talloc_free(tmp_ctx);
2392 return WERR_OK;
2395 *count = el->num_values;
2396 *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2397 if (*r == NULL) {
2398 talloc_free(tmp_ctx);
2399 return WERR_DS_DRA_INTERNAL_ERROR;
2402 for (i=0; i<(*count); i++) {
2403 enum ndr_err_code ndr_err;
2404 ndr_err = ndr_pull_struct_blob(&el->values[i],
2405 mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2406 &(*r)[i],
2407 (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2408 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2409 talloc_free(tmp_ctx);
2410 return WERR_DS_DRA_INTERNAL_ERROR;
2414 talloc_free(tmp_ctx);
2416 return WERR_OK;
2420 save the repsFromTo blob list for a given partition GUID
2421 attr must be "repsFrom" or "repsTo"
2423 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2424 const char *attr, struct repsFromToBlob *r, uint32_t count)
2426 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2427 struct ldb_message *msg;
2428 struct ldb_message_element *el;
2429 int i;
2431 msg = ldb_msg_new(tmp_ctx);
2432 msg->dn = dn;
2433 if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2434 goto failed;
2437 el->values = talloc_array(msg, struct ldb_val, count);
2438 if (!el->values) {
2439 goto failed;
2442 for (i=0; i<count; i++) {
2443 struct ldb_val v;
2444 enum ndr_err_code ndr_err;
2446 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2447 &r[i],
2448 (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2449 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2450 goto failed;
2453 el->num_values++;
2454 el->values[i] = v;
2457 if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2458 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2459 goto failed;
2462 talloc_free(tmp_ctx);
2464 return WERR_OK;
2466 failed:
2467 talloc_free(tmp_ctx);
2468 return WERR_DS_DRA_INTERNAL_ERROR;
2473 load the uSNHighest attribute from the @REPLCHANGED object for a
2474 partition
2476 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t *uSN)
2478 struct ldb_request *req;
2479 int ret;
2480 TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2481 struct dsdb_control_current_partition *p_ctrl;
2482 struct ldb_result *res;
2484 res = talloc_zero(tmp_ctx, struct ldb_result);
2485 if (!res) {
2486 talloc_free(tmp_ctx);
2487 return LDB_ERR_OPERATIONS_ERROR;
2490 ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2491 ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2492 LDB_SCOPE_BASE,
2493 NULL, NULL,
2494 NULL,
2495 res, ldb_search_default_callback,
2496 NULL);
2497 if (ret != LDB_SUCCESS) {
2498 talloc_free(tmp_ctx);
2499 return ret;
2502 p_ctrl = talloc(req, struct dsdb_control_current_partition);
2503 if (p_ctrl == NULL) {
2504 talloc_free(res);
2505 return LDB_ERR_OPERATIONS_ERROR;
2507 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2508 p_ctrl->dn = dn;
2511 ret = ldb_request_add_control(req,
2512 DSDB_CONTROL_CURRENT_PARTITION_OID,
2513 false, p_ctrl);
2514 if (ret != LDB_SUCCESS) {
2515 talloc_free(tmp_ctx);
2516 return ret;
2519 /* Run the new request */
2520 ret = ldb_request(ldb, req);
2522 if (ret == LDB_SUCCESS) {
2523 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2526 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2527 /* it hasn't been created yet, which means
2528 an implicit value of zero */
2529 *uSN = 0;
2530 talloc_free(tmp_ctx);
2531 return LDB_SUCCESS;
2534 if (ret != LDB_SUCCESS) {
2535 talloc_free(tmp_ctx);
2536 return ret;
2539 if (res->count < 1) {
2540 *uSN = 0;
2541 } else {
2542 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2545 talloc_free(tmp_ctx);
2547 return LDB_SUCCESS;
2551 save the uSNHighest attribute in the @REPLCHANGED object for a
2552 partition
2554 int dsdb_save_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t uSN)
2556 struct ldb_request *req;
2557 struct ldb_message *msg;
2558 struct dsdb_control_current_partition *p_ctrl;
2559 int ret;
2561 msg = ldb_msg_new(ldb);
2562 if (msg == NULL) {
2563 return LDB_ERR_OPERATIONS_ERROR;
2566 msg->dn = ldb_dn_new(msg, ldb, "@REPLCHANGED");
2567 if (msg->dn == NULL) {
2568 talloc_free(msg);
2569 return LDB_ERR_OPERATIONS_ERROR;
2572 ret = ldb_msg_add_fmt(msg, "uSNHighest", "%llu", (unsigned long long)uSN);
2573 if (ret != LDB_SUCCESS) {
2574 talloc_free(msg);
2575 return ret;
2577 msg->elements[0].flags = LDB_FLAG_MOD_REPLACE;
2580 p_ctrl = talloc(msg, struct dsdb_control_current_partition);
2581 if (p_ctrl == NULL) {
2582 talloc_free(msg);
2583 return LDB_ERR_OPERATIONS_ERROR;
2585 p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2586 p_ctrl->dn = dn;
2588 ret = ldb_build_mod_req(&req, ldb, msg,
2589 msg,
2590 NULL,
2591 NULL, ldb_op_default_callback,
2592 NULL);
2593 again:
2594 if (ret != LDB_SUCCESS) {
2595 talloc_free(msg);
2596 return ret;
2599 ret = ldb_request_add_control(req,
2600 DSDB_CONTROL_CURRENT_PARTITION_OID,
2601 false, p_ctrl);
2602 if (ret != LDB_SUCCESS) {
2603 talloc_free(msg);
2604 return ret;
2607 /* Run the new request */
2608 ret = ldb_request(ldb, req);
2610 if (ret == LDB_SUCCESS) {
2611 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2613 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2614 ret = ldb_build_add_req(&req, ldb, msg,
2615 msg,
2616 NULL,
2617 NULL, ldb_op_default_callback,
2618 NULL);
2619 goto again;
2622 talloc_free(msg);
2624 return ret;
2627 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2628 const struct drsuapi_DsReplicaCursor2 *c2)
2630 return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2634 see if we are a RODC
2636 TODO: This should take a sam_ctx, and lookup the right object (with
2637 a cache)
2639 bool samdb_rodc(struct loadparm_context *lp_ctx)
2641 return lp_parm_bool(lp_ctx, NULL, "repl", "RODC", false);
2646 return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
2648 flags are DS_NTDS_OPTION_*
2650 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2652 TALLOC_CTX *tmp_ctx;
2653 const char *attrs[] = { "options", NULL };
2654 int ret;
2655 struct ldb_result *res;
2657 tmp_ctx = talloc_new(ldb);
2658 if (tmp_ctx == NULL) {
2659 goto failed;
2662 ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2663 if (ret) {
2664 goto failed;
2667 if (res->count != 1) {
2668 goto failed;
2671 *options = samdb_result_uint(res->msgs[0], "options", 0);
2673 talloc_free(tmp_ctx);
2675 return LDB_SUCCESS;
2677 failed:
2678 DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
2679 talloc_free(tmp_ctx);
2680 return LDB_ERR_NO_SUCH_OBJECT;
2684 * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
2685 * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
2687 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
2689 char **tokens, *ret;
2690 size_t i;
2692 tokens = str_list_make(mem_ctx, cn, " -_");
2693 if (tokens == NULL)
2694 return NULL;
2696 /* "tolower()" and "toupper()" should also work properly on 0x00 */
2697 tokens[0][0] = tolower(tokens[0][0]);
2698 for (i = 1; i < str_list_length((const char **)tokens); i++)
2699 tokens[i][0] = toupper(tokens[i][0]);
2701 ret = talloc_strdup(mem_ctx, tokens[0]);
2702 for (i = 1; i < str_list_length((const char **)tokens); i++)
2703 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
2705 talloc_free(tokens);
2707 return ret;
2711 return domain functional level
2712 returns DS_DOMAIN_FUNCTION_*
2714 int dsdb_functional_level(struct ldb_context *ldb)
2716 int *domainFunctionality =
2717 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
2718 if (!domainFunctionality) {
2719 DEBUG(0,(__location__ ": WARNING: domainFunctionality not setup\n"));
2720 return DS_DOMAIN_FUNCTION_2000;
2722 return *domainFunctionality;
2726 return a GUID from a extended DN structure
2728 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid)
2730 const struct ldb_val *v;
2732 v = ldb_dn_get_extended_component(dn, "GUID");
2733 if (v == NULL) {
2734 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2737 return GUID_from_ndr_blob(v, guid);