856e9401e66fce27ea7dd3c2ca693ebe6d374270
[samba.git] / source4 / dsdb / common / util.c
1 /*
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4
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
9
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.
14
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.
19
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/>.
22 */
23
24 #include "includes.h"
25 #include "events/events.h"
26 #include "ldb.h"
27 #include "ldb_module.h"
28 #include "ldb_errors.h"
29 #include "../lib/util/util_ldb.h"
30 #include "../lib/crypto/crypto.h"
31 #include "dsdb/samdb/samdb.h"
32 #include "libcli/security/security.h"
33 #include "librpc/gen_ndr/ndr_security.h"
34 #include "librpc/gen_ndr/ndr_misc.h"
35 #include "../libds/common/flags.h"
36 #include "dsdb/common/proto.h"
37 #include "libcli/ldap/ldap_ndr.h"
38 #include "param/param.h"
39 #include "libcli/auth/libcli_auth.h"
40 #include "librpc/gen_ndr/ndr_drsblobs.h"
41 #include "system/locale.h"
42 #include "system/filesys.h"
43 #include "lib/util/tsort.h"
44 #include "dsdb/common/util.h"
45 #include "lib/socket/socket.h"
46 #include "librpc/gen_ndr/irpc.h"
47 #include "libds/common/flag_mapping.h"
48 #include "lib/util/access.h"
49 #include "lib/util/sys_rw_data.h"
50 #include "libcli/util/ntstatus.h"
51 #include "lib/util/smb_strtox.h"
52 #include "auth/auth.h"
53
54 #undef strncasecmp
55 #undef strcasecmp
56
57 /*
58  * This included to allow us to handle DSDB_FLAG_REPLICATED_UPDATE in
59  * dsdb_request_add_controls()
60  */
61 #include "dsdb/samdb/ldb_modules/util.h"
62
63 /* default is 30 minutes: -1e7 * 30 * 60 */
64 #define DEFAULT_OBSERVATION_WINDOW              -18000000000
65
66 /*
67   search the sam for the specified attributes in a specific domain, filter on
68   objectSid being in domain_sid.
69 */
70 int samdb_search_domain(struct ldb_context *sam_ldb,
71                         TALLOC_CTX *mem_ctx,
72                         struct ldb_dn *basedn,
73                         struct ldb_message ***res,
74                         const char * const *attrs,
75                         const struct dom_sid *domain_sid,
76                         const char *format, ...)  _PRINTF_ATTRIBUTE(7,8)
77 {
78         va_list ap;
79         int i, count;
80
81         va_start(ap, format);
82         count = gendb_search_v(sam_ldb, mem_ctx, basedn,
83                                res, attrs, format, ap);
84         va_end(ap);
85
86         i=0;
87
88         while (i<count) {
89                 struct dom_sid *entry_sid;
90
91                 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
92
93                 if ((entry_sid == NULL) ||
94                     (!dom_sid_in_domain(domain_sid, entry_sid))) {
95                         /* Delete that entry from the result set */
96                         (*res)[i] = (*res)[count-1];
97                         count -= 1;
98                         talloc_free(entry_sid);
99                         continue;
100                 }
101                 talloc_free(entry_sid);
102                 i += 1;
103         }
104
105         return count;
106 }
107
108 /*
109   search the sam for a single string attribute in exactly 1 record
110 */
111 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
112                                   TALLOC_CTX *mem_ctx,
113                                   struct ldb_dn *basedn,
114                                   const char *attr_name,
115                                   const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
116 {
117         int count;
118         const char *attrs[2] = { NULL, NULL };
119         struct ldb_message **res = NULL;
120
121         attrs[0] = attr_name;
122
123         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
124         if (count > 1) {
125                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
126                          attr_name, format, count));
127         }
128         if (count != 1) {
129                 talloc_free(res);
130                 return NULL;
131         }
132
133         return ldb_msg_find_attr_as_string(res[0], attr_name, NULL);
134 }
135
136 /*
137   search the sam for a single string attribute in exactly 1 record
138 */
139 const char *samdb_search_string(struct ldb_context *sam_ldb,
140                                 TALLOC_CTX *mem_ctx,
141                                 struct ldb_dn *basedn,
142                                 const char *attr_name,
143                                 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
144 {
145         va_list ap;
146         const char *str;
147
148         va_start(ap, format);
149         str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
150         va_end(ap);
151
152         return str;
153 }
154
155 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
156                                TALLOC_CTX *mem_ctx,
157                                struct ldb_dn *basedn,
158                                const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
159 {
160         va_list ap;
161         struct ldb_dn *ret;
162         struct ldb_message **res = NULL;
163         int count;
164
165         va_start(ap, format);
166         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
167         va_end(ap);
168
169         if (count != 1) return NULL;
170
171         ret = talloc_steal(mem_ctx, res[0]->dn);
172         talloc_free(res);
173
174         return ret;
175 }
176
177 /*
178   search the sam for a dom_sid attribute in exactly 1 record
179 */
180 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
181                                      TALLOC_CTX *mem_ctx,
182                                      struct ldb_dn *basedn,
183                                      const char *attr_name,
184                                      const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
185 {
186         va_list ap;
187         int count;
188         struct ldb_message **res;
189         const char *attrs[2] = { NULL, NULL };
190         struct dom_sid *sid;
191
192         attrs[0] = attr_name;
193
194         va_start(ap, format);
195         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
196         va_end(ap);
197         if (count > 1) {
198                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n",
199                          attr_name, format, count));
200         }
201         if (count != 1) {
202                 talloc_free(res);
203                 return NULL;
204         }
205         sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
206         talloc_free(res);
207         return sid;
208 }
209
210 /*
211   search the sam for a single integer attribute in exactly 1 record
212 */
213 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
214                          TALLOC_CTX *mem_ctx,
215                          unsigned int default_value,
216                          struct ldb_dn *basedn,
217                          const char *attr_name,
218                          const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
219 {
220         va_list ap;
221         int count;
222         struct ldb_message **res;
223         const char *attrs[2] = { NULL, NULL };
224
225         attrs[0] = attr_name;
226
227         va_start(ap, format);
228         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
229         va_end(ap);
230
231         if (count != 1) {
232                 return default_value;
233         }
234
235         return ldb_msg_find_attr_as_uint(res[0], attr_name, default_value);
236 }
237
238 /*
239   search the sam for a single signed 64 bit integer attribute in exactly 1 record
240 */
241 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
242                            TALLOC_CTX *mem_ctx,
243                            int64_t default_value,
244                            struct ldb_dn *basedn,
245                            const char *attr_name,
246                            const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
247 {
248         va_list ap;
249         int count;
250         struct ldb_message **res;
251         const char *attrs[2] = { NULL, NULL };
252
253         attrs[0] = attr_name;
254
255         va_start(ap, format);
256         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
257         va_end(ap);
258
259         if (count != 1) {
260                 return default_value;
261         }
262
263         return ldb_msg_find_attr_as_int64(res[0], attr_name, default_value);
264 }
265
266 /*
267   search the sam for multipe records each giving a single string attribute
268   return the number of matches, or -1 on error
269 */
270 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
271                                  TALLOC_CTX *mem_ctx,
272                                  struct ldb_dn *basedn,
273                                  const char ***strs,
274                                  const char *attr_name,
275                                  const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
276 {
277         va_list ap;
278         int count, i;
279         const char *attrs[2] = { NULL, NULL };
280         struct ldb_message **res = NULL;
281
282         attrs[0] = attr_name;
283
284         va_start(ap, format);
285         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
286         va_end(ap);
287
288         if (count <= 0) {
289                 return count;
290         }
291
292         /* make sure its single valued */
293         for (i=0;i<count;i++) {
294                 if (res[i]->num_elements != 1) {
295                         DEBUG(1,("samdb: search for %s %s not single valued\n",
296                                  attr_name, format));
297                         talloc_free(res);
298                         return -1;
299                 }
300         }
301
302         *strs = talloc_array(mem_ctx, const char *, count+1);
303         if (! *strs) {
304                 talloc_free(res);
305                 return -1;
306         }
307
308         for (i=0;i<count;i++) {
309                 (*strs)[i] = ldb_msg_find_attr_as_string(res[i], attr_name, NULL);
310         }
311         (*strs)[count] = NULL;
312
313         return count;
314 }
315
316 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
317                                const char *attr, struct ldb_dn *default_value)
318 {
319         struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
320         if (!ret_dn) {
321                 return default_value;
322         }
323         return ret_dn;
324 }
325
326 /*
327   pull a rid from a objectSid in a result set.
328 */
329 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
330                                    const char *attr, uint32_t default_value)
331 {
332         struct dom_sid *sid;
333         uint32_t rid;
334
335         sid = samdb_result_dom_sid(mem_ctx, msg, attr);
336         if (sid == NULL) {
337                 return default_value;
338         }
339         rid = sid->sub_auths[sid->num_auths-1];
340         talloc_free(sid);
341         return rid;
342 }
343
344 /*
345   pull a dom_sid structure from a objectSid in a result set.
346 */
347 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
348                                      const char *attr)
349 {
350         ssize_t ret;
351         const struct ldb_val *v;
352         struct dom_sid *sid;
353         v = ldb_msg_find_ldb_val(msg, attr);
354         if (v == NULL) {
355                 return NULL;
356         }
357         sid = talloc(mem_ctx, struct dom_sid);
358         if (sid == NULL) {
359                 return NULL;
360         }
361         ret = sid_parse(v->data, v->length, sid);
362         if (ret == -1) {
363                 talloc_free(sid);
364                 return NULL;
365         }
366         return sid;
367 }
368
369
370 /**
371  * Makes an auth_SidAttr structure from a objectSid in a result set and a
372  * supplied attribute value.
373  *
374  * @param [in] mem_ctx  Talloc memory context on which to allocate the auth_SidAttr.
375  * @param [in] msg      The message from which to take the objectSid.
376  * @param [in] attr     The attribute name, usually "objectSid".
377  * @param [in] attrs    SE_GROUP_* flags to go with the SID.
378  * @returns A pointer to the auth_SidAttr structure, or NULL on failure.
379  */
380 struct auth_SidAttr *samdb_result_dom_sid_attrs(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
381                                                 const char *attr, uint32_t attrs)
382 {
383         ssize_t ret;
384         const struct ldb_val *v;
385         struct auth_SidAttr *sid;
386         v = ldb_msg_find_ldb_val(msg, attr);
387         if (v == NULL) {
388                 return NULL;
389         }
390         sid = talloc(mem_ctx, struct auth_SidAttr);
391         if (sid == NULL) {
392                 return NULL;
393         }
394         ret = sid_parse(v->data, v->length, &sid->sid);
395         if (ret == -1) {
396                 talloc_free(sid);
397                 return NULL;
398         }
399         sid->attrs = attrs;
400         return sid;
401 }
402
403 /*
404   pull a dom_sid structure from a objectSid in a result set.
405 */
406 int samdb_result_dom_sid_buf(const struct ldb_message *msg,
407                              const char *attr,
408                              struct dom_sid *sid)
409 {
410         ssize_t ret;
411         const struct ldb_val *v = NULL;
412         v = ldb_msg_find_ldb_val(msg, attr);
413         if (v == NULL) {
414                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
415         }
416         ret = sid_parse(v->data, v->length, sid);
417         if (ret == -1) {
418                 return LDB_ERR_OPERATIONS_ERROR;
419         }
420         return LDB_SUCCESS;
421 }
422
423 /*
424   pull a guid structure from a objectGUID in a result set.
425 */
426 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
427 {
428         const struct ldb_val *v;
429         struct GUID guid;
430         NTSTATUS status;
431
432         v = ldb_msg_find_ldb_val(msg, attr);
433         if (!v) return GUID_zero();
434
435         status = GUID_from_ndr_blob(v, &guid);
436         if (!NT_STATUS_IS_OK(status)) {
437                 return GUID_zero();
438         }
439
440         return guid;
441 }
442
443 /*
444   pull a sid prefix from a objectSid in a result set.
445   this is used to find the domain sid for a user
446 */
447 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
448                                         const char *attr)
449 {
450         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
451         if (!sid || sid->num_auths < 1) return NULL;
452         sid->num_auths--;
453         return sid;
454 }
455
456 /*
457   pull a NTTIME in a result set.
458 */
459 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
460                            NTTIME default_value)
461 {
462         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
463 }
464
465 /*
466  * Windows stores 0 for lastLogoff.
467  * But when a MS DC return the lastLogoff (as Logoff Time)
468  * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
469  * cause windows 2008 and newer version to fail for SMB requests
470  */
471 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
472 {
473         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
474
475         if (ret == 0)
476                 ret = 0x7FFFFFFFFFFFFFFFULL;
477
478         return ret;
479 }
480
481 /*
482  * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
483  * indicate an account doesn't expire.
484  *
485  * When Windows initially creates an account, it sets
486  * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF).  However,
487  * when changing from an account having a specific expiration date to
488  * that account never expiring, it sets accountExpires = 0.
489  *
490  * Consolidate that logic here to allow clearer logic for account expiry in
491  * the rest of the code.
492  */
493 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
494 {
495         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
496                                                  0);
497
498         if (ret == 0)
499                 ret = 0x7FFFFFFFFFFFFFFFULL;
500
501         return ret;
502 }
503
504 /*
505   construct the allow_password_change field from the PwdLastSet attribute and the
506   domain password settings
507 */
508 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb,
509                                           TALLOC_CTX *mem_ctx,
510                                           struct ldb_dn *domain_dn,
511                                           const struct ldb_message *msg,
512                                           const char *attr)
513 {
514         uint64_t attr_time = ldb_msg_find_attr_as_uint64(msg, attr, 0);
515         int64_t minPwdAge;
516
517         if (attr_time == 0) {
518                 return 0;
519         }
520
521         minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
522
523         /* yes, this is a -= not a += as minPwdAge is stored as the negative
524            of the number of 100-nano-seconds */
525         attr_time -= minPwdAge;
526
527         return attr_time;
528 }
529
530 /*
531   pull a samr_Password structutre from a result set.
532 */
533 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
534 {
535         struct samr_Password *hash = NULL;
536         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
537         if (val && (val->length >= sizeof(hash->hash))) {
538                 hash = talloc(mem_ctx, struct samr_Password);
539                 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
540         }
541         return hash;
542 }
543
544 /*
545   pull an array of samr_Password structures from a result set.
546 */
547 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
548                            const char *attr, struct samr_Password **hashes)
549 {
550         unsigned int count, i;
551         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
552
553         *hashes = NULL;
554         if (!val) {
555                 return 0;
556         }
557         count = val->length / 16;
558         if (count == 0) {
559                 return 0;
560         }
561
562         *hashes = talloc_array(mem_ctx, struct samr_Password, count);
563         if (! *hashes) {
564                 return 0;
565         }
566         talloc_keep_secret(*hashes);
567
568         for (i=0;i<count;i++) {
569                 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
570         }
571
572         return count;
573 }
574
575 NTSTATUS samdb_result_passwords_from_history(TALLOC_CTX *mem_ctx,
576                                              struct loadparm_context *lp_ctx,
577                                              const struct ldb_message *msg,
578                                              unsigned int idx,
579                                              const struct samr_Password **lm_pwd,
580                                              const struct samr_Password **nt_pwd)
581 {
582         struct samr_Password *lmPwdHash, *ntPwdHash;
583
584         if (nt_pwd) {
585                 unsigned int num_nt;
586                 num_nt = samdb_result_hashes(mem_ctx, msg, "ntPwdHistory", &ntPwdHash);
587                 if (num_nt <= idx) {
588                         *nt_pwd = NULL;
589                 } else {
590                         *nt_pwd = &ntPwdHash[idx];
591                 }
592         }
593         if (lm_pwd) {
594                 /* Ensure that if we have turned off LM
595                  * authentication, that we never use the LM hash, even
596                  * if we store it */
597                 if (lpcfg_lanman_auth(lp_ctx)) {
598                         unsigned int num_lm;
599                         num_lm = samdb_result_hashes(mem_ctx, msg, "lmPwdHistory", &lmPwdHash);
600                         if (num_lm <= idx) {
601                                 *lm_pwd = NULL;
602                         } else {
603                                 *lm_pwd = &lmPwdHash[idx];
604                         }
605                 } else {
606                         *lm_pwd = NULL;
607                 }
608         }
609         return NT_STATUS_OK;
610 }
611
612 NTSTATUS samdb_result_passwords_no_lockout(TALLOC_CTX *mem_ctx,
613                                            struct loadparm_context *lp_ctx,
614                                            const struct ldb_message *msg,
615                                            struct samr_Password **nt_pwd)
616 {
617         struct samr_Password *ntPwdHash;
618
619         if (nt_pwd) {
620                 unsigned int num_nt;
621                 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
622                 if (num_nt == 0) {
623                         *nt_pwd = NULL;
624                 } else if (num_nt > 1) {
625                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
626                 } else {
627                         *nt_pwd = &ntPwdHash[0];
628                 }
629         }
630         return NT_STATUS_OK;
631 }
632
633 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx,
634                                 struct loadparm_context *lp_ctx,
635                                 const struct ldb_message *msg,
636                                 struct samr_Password **nt_pwd)
637 {
638         uint16_t acct_flags;
639
640         acct_flags = samdb_result_acct_flags(msg,
641                                              "msDS-User-Account-Control-Computed");
642         /* Quit if the account was locked out. */
643         if (acct_flags & ACB_AUTOLOCK) {
644                 DEBUG(3,("samdb_result_passwords: Account for user %s was locked out.\n",
645                          ldb_dn_get_linearized(msg->dn)));
646                 return NT_STATUS_ACCOUNT_LOCKED_OUT;
647         }
648
649         return samdb_result_passwords_no_lockout(mem_ctx, lp_ctx, msg,
650                                                  nt_pwd);
651 }
652
653 /*
654   pull a samr_LogonHours structutre from a result set.
655 */
656 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
657 {
658         struct samr_LogonHours hours;
659         size_t units_per_week = 168;
660         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
661
662         ZERO_STRUCT(hours);
663
664         if (val) {
665                 units_per_week = val->length * 8;
666         }
667
668         hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
669         if (!hours.bits) {
670                 return hours;
671         }
672         hours.units_per_week = units_per_week;
673         memset(hours.bits, 0xFF, units_per_week/8);
674         if (val) {
675                 memcpy(hours.bits, val->data, val->length);
676         }
677
678         return hours;
679 }
680
681 /*
682   pull a set of account_flags from a result set.
683
684   Naturally, this requires that userAccountControl and
685   (if not null) the attributes 'attr' be already
686   included in msg
687 */
688 uint32_t samdb_result_acct_flags(const struct ldb_message *msg, const char *attr)
689 {
690         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
691         uint32_t attr_flags = 0;
692         uint32_t acct_flags = ds_uf2acb(userAccountControl);
693         if (attr) {
694                 attr_flags = ldb_msg_find_attr_as_uint(msg, attr, UF_ACCOUNTDISABLE);
695                 if (attr_flags == UF_ACCOUNTDISABLE) {
696                         DEBUG(0, ("Attribute %s not found, disabling account %s!\n", attr,
697                                   ldb_dn_get_linearized(msg->dn)));
698                 }
699                 acct_flags |= ds_uf2acb(attr_flags);
700         }
701
702         return acct_flags;
703 }
704
705 NTSTATUS samdb_result_parameters(TALLOC_CTX *mem_ctx,
706                                  struct ldb_message *msg,
707                                  const char *attr,
708                                  struct lsa_BinaryString *s)
709 {
710         int i;
711         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
712
713         ZERO_STRUCTP(s);
714
715         if (!val) {
716                 return NT_STATUS_OK;
717         }
718
719         if ((val->length % 2) != 0) {
720                 /*
721                  * If the on-disk data is not even in length, we know
722                  * it is corrupt, and can not be safely pushed.  We
723                  * would either truncate, send either a un-initilaised
724                  * byte or send a forced zero byte
725                  */
726                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
727         }
728
729         s->array = talloc_array(mem_ctx, uint16_t, val->length/2);
730         if (!s->array) {
731                 return NT_STATUS_NO_MEMORY;
732         }
733         s->length = s->size = val->length;
734
735         /* The on-disk format is the 'network' format, being UTF16LE (sort of) */
736         for (i = 0; i < s->length / 2; i++) {
737                 s->array[i] = SVAL(val->data, i * 2);
738         }
739
740         return NT_STATUS_OK;
741 }
742
743 /* Find an attribute, with a particular value */
744
745 /* The current callers of this function expect a very specific
746  * behaviour: In particular, objectClass subclass equivalence is not
747  * wanted.  This means that we should not lookup the schema for the
748  * comparison function */
749 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb,
750                                                  const struct ldb_message *msg,
751                                                  const char *name, const char *value)
752 {
753         unsigned int i;
754         struct ldb_message_element *el = ldb_msg_find_element(msg, name);
755
756         if (!el) {
757                 return NULL;
758         }
759
760         for (i=0;i<el->num_values;i++) {
761                 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
762                         return el;
763                 }
764         }
765
766         return NULL;
767 }
768
769 static int samdb_find_or_add_attribute_ex(struct ldb_context *ldb,
770                                           struct ldb_message *msg,
771                                           const char *name,
772                                           const char *set_value,
773                                           unsigned attr_flags,
774                                           bool *added)
775 {
776         int ret;
777         struct ldb_message_element *el;
778
779         SMB_ASSERT(attr_flags != 0);
780
781         el = ldb_msg_find_element(msg, name);
782         if (el) {
783                 if (added != NULL) {
784                         *added = false;
785                 }
786
787                 return LDB_SUCCESS;
788         }
789
790         ret = ldb_msg_add_empty(msg, name,
791                                 attr_flags,
792                                 &el);
793         if (ret != LDB_SUCCESS) {
794                 return ret;
795         }
796
797         if (set_value != NULL) {
798                 ret = ldb_msg_add_string(msg, name, set_value);
799                 if (ret != LDB_SUCCESS) {
800                         return ret;
801                 }
802         }
803
804         if (added != NULL) {
805                 *added = true;
806         }
807         return LDB_SUCCESS;
808 }
809
810 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
811 {
812         return samdb_find_or_add_attribute_ex(ldb, msg, name, set_value, LDB_FLAG_MOD_ADD, NULL);
813 }
814
815 /*
816   add a dom_sid element to a message
817 */
818 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
819                           const char *attr_name, const struct dom_sid *sid)
820 {
821         struct ldb_val v;
822         enum ndr_err_code ndr_err;
823
824         ndr_err = ndr_push_struct_blob(&v, mem_ctx,
825                                        sid,
826                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
827         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
828                 return ldb_operr(sam_ldb);
829         }
830         return ldb_msg_add_value(msg, attr_name, &v, NULL);
831 }
832
833
834 /*
835   add a delete element operation to a message
836 */
837 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
838                          const char *attr_name)
839 {
840         /* we use an empty replace rather than a delete, as it allows for
841            dsdb_replace() to be used everywhere */
842         return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
843 }
844
845 /*
846   add an add attribute value to a message or enhance an existing attribute
847   which has the same name and the add flag set.
848 */
849 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
850                          struct ldb_message *msg, const char *attr_name,
851                          const char *value)
852 {
853         struct ldb_message_element *el;
854         struct ldb_val val;
855         char *v;
856         unsigned int i;
857         bool found = false;
858         int ret;
859
860         v = talloc_strdup(mem_ctx, value);
861         if (v == NULL) {
862                 return ldb_oom(sam_ldb);
863         }
864
865         val.data = (uint8_t *) v;
866         val.length = strlen(v);
867
868         if (val.length == 0) {
869                 /* allow empty strings as non-existent attributes */
870                 return LDB_SUCCESS;
871         }
872
873         for (i = 0; i < msg->num_elements; i++) {
874                 el = &msg->elements[i];
875                 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
876                     (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
877                         found = true;
878                         break;
879                 }
880         }
881         if (!found) {
882                 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
883                                         &el);
884                 if (ret != LDB_SUCCESS) {
885                         return ret;
886                 }
887         }
888
889         ret = ldb_msg_element_add_value(msg->elements, el, &val);
890         if (ret != LDB_SUCCESS) {
891                 return ldb_oom(sam_ldb);
892         }
893
894         return LDB_SUCCESS;
895 }
896
897 /*
898   add a delete attribute value to a message or enhance an existing attribute
899   which has the same name and the delete flag set.
900 */
901 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
902                          struct ldb_message *msg, const char *attr_name,
903                          const char *value)
904 {
905         struct ldb_message_element *el;
906         struct ldb_val val;
907         char *v;
908         unsigned int i;
909         bool found = false;
910         int ret;
911
912         v = talloc_strdup(mem_ctx, value);
913         if (v == NULL) {
914                 return ldb_oom(sam_ldb);
915         }
916
917         val.data = (uint8_t *) v;
918         val.length = strlen(v);
919
920         if (val.length == 0) {
921                 /* allow empty strings as non-existent attributes */
922                 return LDB_SUCCESS;
923         }
924
925         for (i = 0; i < msg->num_elements; i++) {
926                 el = &msg->elements[i];
927                 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
928                     (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
929                         found = true;
930                         break;
931                 }
932         }
933         if (!found) {
934                 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
935                                         &el);
936                 if (ret != LDB_SUCCESS) {
937                         return ret;
938                 }
939         }
940
941         ret = ldb_msg_element_add_value(msg->elements, el, &val);
942         if (ret != LDB_SUCCESS) {
943                 return ldb_oom(sam_ldb);
944         }
945
946         return LDB_SUCCESS;
947 }
948
949 /*
950   add a int element to a message
951 */
952 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
953                        const char *attr_name, int v)
954 {
955         const char *s = talloc_asprintf(mem_ctx, "%d", v);
956         if (s == NULL) {
957                 return ldb_oom(sam_ldb);
958         }
959         return ldb_msg_add_string(msg, attr_name, s);
960 }
961
962 int samdb_msg_add_int_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
963                             const char *attr_name, int v, int flags)
964 {
965         const char *s = talloc_asprintf(mem_ctx, "%d", v);
966         if (s == NULL) {
967                 return ldb_oom(sam_ldb);
968         }
969         return ldb_msg_add_string_flags(msg, attr_name, s, flags);
970 }
971
972 /*
973  * Add an unsigned int element to a message
974  *
975  * The issue here is that we have not yet first cast to int32_t explicitly,
976  * before we cast to an signed int to printf() into the %d or cast to a
977  * int64_t before we then cast to a long long to printf into a %lld.
978  *
979  * There are *no* unsigned integers in Active Directory LDAP, even the RID
980  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
981  * (See the schema, and the syntax definitions in schema_syntax.c).
982  *
983  */
984 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
985                        const char *attr_name, unsigned int v)
986 {
987         return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
988 }
989
990 int samdb_msg_add_uint_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
991                              const char *attr_name, unsigned int v, int flags)
992 {
993         return samdb_msg_add_int_flags(sam_ldb, mem_ctx, msg, attr_name, (int)v, flags);
994 }
995
996 /*
997   add a (signed) int64_t element to a message
998 */
999 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1000                         const char *attr_name, int64_t v)
1001 {
1002         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
1003         if (s == NULL) {
1004                 return ldb_oom(sam_ldb);
1005         }
1006         return ldb_msg_add_string(msg, attr_name, s);
1007 }
1008
1009 /*
1010  * Add an unsigned int64_t (uint64_t) element to a message
1011  *
1012  * The issue here is that we have not yet first cast to int32_t explicitly,
1013  * before we cast to an signed int to printf() into the %d or cast to a
1014  * int64_t before we then cast to a long long to printf into a %lld.
1015  *
1016  * There are *no* unsigned integers in Active Directory LDAP, even the RID
1017  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1018  * (See the schema, and the syntax definitions in schema_syntax.c).
1019  *
1020  */
1021 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1022                         const char *attr_name, uint64_t v)
1023 {
1024         return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
1025 }
1026
1027 /*
1028   append a int element to a message
1029 */
1030 int samdb_msg_append_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1031                       const char *attr_name, int v, int flags)
1032 {
1033         const char *s = talloc_asprintf(mem_ctx, "%d", v);
1034         if (s == NULL) {
1035                 return ldb_oom(sam_ldb);
1036         }
1037         return ldb_msg_append_string(msg, attr_name, s, flags);
1038 }
1039
1040 /*
1041  * Append an unsigned int element to a message
1042  *
1043  * The issue here is that we have not yet first cast to int32_t explicitly,
1044  * before we cast to an signed int to printf() into the %d or cast to a
1045  * int64_t before we then cast to a long long to printf into a %lld.
1046  *
1047  * There are *no* unsigned integers in Active Directory LDAP, even the RID
1048  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1049  * (See the schema, and the syntax definitions in schema_syntax.c).
1050  *
1051  */
1052 int samdb_msg_append_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1053                           const char *attr_name, unsigned int v, int flags)
1054 {
1055         return samdb_msg_append_int(sam_ldb, mem_ctx, msg, attr_name, (int)v, flags);
1056 }
1057
1058 /*
1059   append a (signed) int64_t element to a message
1060 */
1061 int samdb_msg_append_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1062                            const char *attr_name, int64_t v, int flags)
1063 {
1064         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
1065         if (s == NULL) {
1066                 return ldb_oom(sam_ldb);
1067         }
1068         return ldb_msg_append_string(msg, attr_name, s, flags);
1069 }
1070
1071 /*
1072  * Append an unsigned int64_t (uint64_t) element to a message
1073  *
1074  * The issue here is that we have not yet first cast to int32_t explicitly,
1075  * before we cast to an signed int to printf() into the %d or cast to a
1076  * int64_t before we then cast to a long long to printf into a %lld.
1077  *
1078  * There are *no* unsigned integers in Active Directory LDAP, even the RID
1079  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1080  * (See the schema, and the syntax definitions in schema_syntax.c).
1081  *
1082  */
1083 int samdb_msg_append_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1084                             const char *attr_name, uint64_t v, int flags)
1085 {
1086         return samdb_msg_append_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v, flags);
1087 }
1088
1089 /*
1090   add a samr_Password element to a message
1091 */
1092 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1093                        const char *attr_name, const struct samr_Password *hash)
1094 {
1095         struct ldb_val val;
1096         val.data = talloc_memdup(mem_ctx, hash->hash, 16);
1097         if (!val.data) {
1098                 return ldb_oom(sam_ldb);
1099         }
1100         val.length = 16;
1101         return ldb_msg_add_value(msg, attr_name, &val, NULL);
1102 }
1103
1104 /*
1105   add a samr_Password array to a message
1106 */
1107 int samdb_msg_add_hashes(struct ldb_context *ldb,
1108                          TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1109                          const char *attr_name, struct samr_Password *hashes,
1110                          unsigned int count)
1111 {
1112         struct ldb_val val;
1113         unsigned int i;
1114         val.data = talloc_array_size(mem_ctx, 16, count);
1115         val.length = count*16;
1116         if (!val.data) {
1117                 return ldb_oom(ldb);
1118         }
1119         for (i=0;i<count;i++) {
1120                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
1121         }
1122         return ldb_msg_add_value(msg, attr_name, &val, NULL);
1123 }
1124
1125 /*
1126   add a acct_flags element to a message
1127 */
1128 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1129                              const char *attr_name, uint32_t v)
1130 {
1131         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1132 }
1133
1134 /*
1135   add a logon_hours element to a message
1136 */
1137 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1138                               const char *attr_name, struct samr_LogonHours *hours)
1139 {
1140         struct ldb_val val;
1141         val.length = hours->units_per_week / 8;
1142         val.data = hours->bits;
1143         return ldb_msg_add_value(msg, attr_name, &val, NULL);
1144 }
1145
1146 /*
1147   add a parameters element to a message
1148 */
1149 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1150                              const char *attr_name, struct lsa_BinaryString *parameters)
1151 {
1152         int i;
1153         struct ldb_val val;
1154         if ((parameters->length % 2) != 0) {
1155                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
1156         }
1157
1158         val.data = talloc_array(mem_ctx, uint8_t, parameters->length);
1159         if (val.data == NULL) {
1160                 return LDB_ERR_OPERATIONS_ERROR;
1161         }
1162         val.length = parameters->length;
1163         for (i = 0; i < parameters->length / 2; i++) {
1164                 /*
1165                  * The on-disk format needs to be in the 'network'
1166                  * format, parmeters->array is a uint16_t array of
1167                  * length parameters->length / 2
1168                  */
1169                 SSVAL(val.data, i * 2, parameters->array[i]);
1170         }
1171         return ldb_msg_add_steal_value(msg, attr_name, &val);
1172 }
1173
1174 /*
1175  * Sets an unsigned int element in a message
1176  *
1177  * The issue here is that we have not yet first cast to int32_t explicitly,
1178  * before we cast to an signed int to printf() into the %d or cast to a
1179  * int64_t before we then cast to a long long to printf into a %lld.
1180  *
1181  * There are *no* unsigned integers in Active Directory LDAP, even the RID
1182  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1183  * (See the schema, and the syntax definitions in schema_syntax.c).
1184  *
1185  */
1186 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1187                        struct ldb_message *msg, const char *attr_name,
1188                        unsigned int v)
1189 {
1190         struct ldb_message_element *el;
1191
1192         el = ldb_msg_find_element(msg, attr_name);
1193         if (el) {
1194                 el->num_values = 0;
1195         }
1196         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1197 }
1198
1199 /*
1200  * Handle ldb_request in transaction
1201  */
1202 int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1203                                  struct ldb_request *req)
1204 {
1205         int ret;
1206
1207         ret = ldb_transaction_start(sam_ldb);
1208         if (ret != LDB_SUCCESS) {
1209                 return ret;
1210         }
1211
1212         ret = ldb_request(sam_ldb, req);
1213         if (ret == LDB_SUCCESS) {
1214                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1215         }
1216
1217         if (ret == LDB_SUCCESS) {
1218                 return ldb_transaction_commit(sam_ldb);
1219         }
1220         ldb_transaction_cancel(sam_ldb);
1221
1222         return ret;
1223 }
1224
1225 /*
1226   return a default security descriptor
1227 */
1228 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1229 {
1230         struct security_descriptor *sd;
1231
1232         sd = security_descriptor_initialise(mem_ctx);
1233
1234         return sd;
1235 }
1236
1237 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1238 {
1239         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1240         struct ldb_dn *aggregate_dn;
1241         if (!schema_dn) {
1242                 return NULL;
1243         }
1244
1245         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1246         if (!aggregate_dn) {
1247                 return NULL;
1248         }
1249         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1250                 return NULL;
1251         }
1252         return aggregate_dn;
1253 }
1254
1255 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1256 {
1257         struct ldb_dn *new_dn;
1258
1259         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1260         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1261                 talloc_free(new_dn);
1262                 return NULL;
1263         }
1264         return new_dn;
1265 }
1266
1267 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1268 {
1269        struct ldb_dn *new_dn;
1270
1271        new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1272        if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1273                talloc_free(new_dn);
1274                return NULL;
1275        }
1276        return new_dn;
1277 }
1278
1279 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1280 {
1281         struct ldb_dn *new_dn;
1282
1283         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1284         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1285                 talloc_free(new_dn);
1286                 return NULL;
1287         }
1288         return new_dn;
1289 }
1290
1291 struct ldb_dn *samdb_extended_rights_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1292 {
1293         struct ldb_dn *new_dn;
1294
1295         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1296         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Extended-Rights")) {
1297                 talloc_free(new_dn);
1298                 return NULL;
1299         }
1300         return new_dn;
1301 }
1302 /*
1303   work out the domain sid for the current open ldb
1304 */
1305 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1306 {
1307         TALLOC_CTX *tmp_ctx;
1308         const struct dom_sid *domain_sid;
1309         const char *attrs[] = {
1310                 "objectSid",
1311                 NULL
1312         };
1313         struct ldb_result *res;
1314         int ret;
1315
1316         /* see if we have a cached copy */
1317         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1318         if (domain_sid) {
1319                 return domain_sid;
1320         }
1321
1322         tmp_ctx = talloc_new(ldb);
1323         if (tmp_ctx == NULL) {
1324                 goto failed;
1325         }
1326
1327         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1328
1329         if (ret != LDB_SUCCESS) {
1330                 goto failed;
1331         }
1332
1333         if (res->count != 1) {
1334                 goto failed;
1335         }
1336
1337         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1338         if (domain_sid == NULL) {
1339                 goto failed;
1340         }
1341
1342         /* cache the domain_sid in the ldb */
1343         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1344                 goto failed;
1345         }
1346
1347         talloc_steal(ldb, domain_sid);
1348         talloc_free(tmp_ctx);
1349
1350         return domain_sid;
1351
1352 failed:
1353         talloc_free(tmp_ctx);
1354         return NULL;
1355 }
1356
1357 /*
1358   get domain sid from cache
1359 */
1360 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1361 {
1362         return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1363 }
1364
1365 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1366 {
1367         TALLOC_CTX *tmp_ctx;
1368         struct dom_sid *dom_sid_new;
1369         struct dom_sid *dom_sid_old;
1370
1371         /* see if we have a cached copy */
1372         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb,
1373                                                      "cache.domain_sid"), struct dom_sid);
1374
1375         tmp_ctx = talloc_new(ldb);
1376         if (tmp_ctx == NULL) {
1377                 goto failed;
1378         }
1379
1380         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1381         if (!dom_sid_new) {
1382                 goto failed;
1383         }
1384
1385         /* cache the domain_sid in the ldb */
1386         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1387                 goto failed;
1388         }
1389
1390         talloc_steal(ldb, dom_sid_new);
1391         talloc_free(tmp_ctx);
1392         talloc_free(dom_sid_old);
1393
1394         return true;
1395
1396 failed:
1397         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1398         talloc_free(tmp_ctx);
1399         return false;
1400 }
1401
1402 /*
1403   work out the domain guid for the current open ldb
1404 */
1405 const struct GUID *samdb_domain_guid(struct ldb_context *ldb)
1406 {
1407         TALLOC_CTX *tmp_ctx = NULL;
1408         struct GUID *domain_guid = NULL;
1409         const char *attrs[] = {
1410                 "objectGUID",
1411                 NULL
1412         };
1413         struct ldb_result *res = NULL;
1414         int ret;
1415
1416         /* see if we have a cached copy */
1417         domain_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.domain_guid");
1418         if (domain_guid) {
1419                 return domain_guid;
1420         }
1421
1422         tmp_ctx = talloc_new(ldb);
1423         if (tmp_ctx == NULL) {
1424                 goto failed;
1425         }
1426
1427         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectGUID=*");
1428         if (ret != LDB_SUCCESS) {
1429                 goto failed;
1430         }
1431
1432         if (res->count != 1) {
1433                 goto failed;
1434         }
1435
1436         domain_guid = talloc(tmp_ctx, struct GUID);
1437         if (domain_guid == NULL) {
1438                 goto failed;
1439         }
1440         *domain_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1441
1442         /* cache the domain_sid in the ldb */
1443         if (ldb_set_opaque(ldb, "cache.domain_guid", domain_guid) != LDB_SUCCESS) {
1444                 goto failed;
1445         }
1446
1447         talloc_steal(ldb, domain_guid);
1448         talloc_free(tmp_ctx);
1449
1450         return domain_guid;
1451
1452 failed:
1453         talloc_free(tmp_ctx);
1454         return NULL;
1455 }
1456
1457 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1458 {
1459         TALLOC_CTX *tmp_ctx;
1460         struct ldb_dn *ntds_settings_dn_new;
1461         struct ldb_dn *ntds_settings_dn_old;
1462
1463         /* see if we have a forced copy from provision */
1464         ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb,
1465                                                               "forced.ntds_settings_dn"), struct ldb_dn);
1466
1467         tmp_ctx = talloc_new(ldb);
1468         if (tmp_ctx == NULL) {
1469                 goto failed;
1470         }
1471
1472         ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1473         if (!ntds_settings_dn_new) {
1474                 goto failed;
1475         }
1476
1477         /* set the DN in the ldb to avoid lookups during provision */
1478         if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1479                 goto failed;
1480         }
1481
1482         talloc_steal(ldb, ntds_settings_dn_new);
1483         talloc_free(tmp_ctx);
1484         talloc_free(ntds_settings_dn_old);
1485
1486         return true;
1487
1488 failed:
1489         DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1490         talloc_free(tmp_ctx);
1491         return false;
1492 }
1493
1494 /*
1495   work out the ntds settings dn for the current open ldb
1496 */
1497 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1498 {
1499         TALLOC_CTX *tmp_ctx;
1500         const char *root_attrs[] = { "dsServiceName", NULL };
1501         int ret;
1502         struct ldb_result *root_res;
1503         struct ldb_dn *settings_dn;
1504
1505         /* see if we have a cached copy */
1506         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1507         if (settings_dn) {
1508                 return ldb_dn_copy(mem_ctx, settings_dn);
1509         }
1510
1511         tmp_ctx = talloc_new(mem_ctx);
1512         if (tmp_ctx == NULL) {
1513                 goto failed;
1514         }
1515
1516         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1517         if (ret != LDB_SUCCESS) {
1518                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n",
1519                          ldb_errstring(ldb)));
1520                 goto failed;
1521         }
1522
1523         if (root_res->count != 1) {
1524                 goto failed;
1525         }
1526
1527         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1528
1529         /* note that we do not cache the DN here, as that would mean
1530          * we could not handle server renames at runtime. Only
1531          * provision sets up forced.ntds_settings_dn */
1532
1533         talloc_steal(mem_ctx, settings_dn);
1534         talloc_free(tmp_ctx);
1535
1536         return settings_dn;
1537
1538 failed:
1539         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1540         talloc_free(tmp_ctx);
1541         return NULL;
1542 }
1543
1544 /*
1545   work out the ntds settings invocationID/objectGUID for the current open ldb
1546 */
1547 static const struct GUID *samdb_ntds_GUID(struct ldb_context *ldb,
1548                                           const char *attribute,
1549                                           const char *cache_name)
1550 {
1551         TALLOC_CTX *tmp_ctx;
1552         const char *attrs[] = { attribute, NULL };
1553         int ret;
1554         struct ldb_result *res;
1555         struct GUID *ntds_guid;
1556         struct ldb_dn *ntds_settings_dn = NULL;
1557         const char *errstr = NULL;
1558
1559         /* see if we have a cached copy */
1560         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, cache_name);
1561         if (ntds_guid != NULL) {
1562                 return ntds_guid;
1563         }
1564
1565         tmp_ctx = talloc_new(ldb);
1566         if (tmp_ctx == NULL) {
1567                 goto failed;
1568         }
1569
1570         ntds_settings_dn = samdb_ntds_settings_dn(ldb, tmp_ctx);
1571         if (ntds_settings_dn == NULL) {
1572                 errstr = "samdb_ntds_settings_dn() returned NULL";
1573                 goto failed;
1574         }
1575
1576         ret = ldb_search(ldb, tmp_ctx, &res, ntds_settings_dn,
1577                          LDB_SCOPE_BASE, attrs, NULL);
1578         if (ret) {
1579                 errstr = ldb_errstring(ldb);
1580                 goto failed;
1581         }
1582
1583         if (res->count != 1) {
1584                 errstr = "incorrect number of results from base search";
1585                 goto failed;
1586         }
1587
1588         ntds_guid = talloc(tmp_ctx, struct GUID);
1589         if (ntds_guid == NULL) {
1590                 goto failed;
1591         }
1592
1593         *ntds_guid = samdb_result_guid(res->msgs[0], attribute);
1594
1595         if (GUID_all_zero(ntds_guid)) {
1596                 if (ldb_msg_find_ldb_val(res->msgs[0], attribute)) {
1597                         errstr = "failed to find the GUID attribute";
1598                 } else {
1599                         errstr = "failed to parse the GUID";
1600                 }
1601                 goto failed;
1602         }
1603
1604         /* cache the domain_sid in the ldb */
1605         if (ldb_set_opaque(ldb, cache_name, ntds_guid) != LDB_SUCCESS) {
1606                 errstr = "ldb_set_opaque() failed";
1607                 goto failed;
1608         }
1609
1610         talloc_steal(ldb, ntds_guid);
1611         talloc_free(tmp_ctx);
1612
1613         return ntds_guid;
1614
1615 failed:
1616         DBG_WARNING("Failed to find our own NTDS Settings %s in the ldb: %s!\n",
1617                     attribute, errstr);
1618         talloc_free(tmp_ctx);
1619         return NULL;
1620 }
1621
1622 /*
1623   work out the ntds settings objectGUID for the current open ldb
1624 */
1625 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1626 {
1627         return samdb_ntds_GUID(ldb, "objectGUID", "cache.ntds_guid");
1628 }
1629
1630 /*
1631   work out the ntds settings invocationId for the current open ldb
1632 */
1633 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1634 {
1635         return samdb_ntds_GUID(ldb, "invocationId", "cache.invocation_id");
1636 }
1637
1638 static bool samdb_set_ntds_GUID(struct ldb_context *ldb,
1639                                 const struct GUID *ntds_guid_in,
1640                                 const char *attribute,
1641                                 const char *cache_name)
1642 {
1643         TALLOC_CTX *tmp_ctx;
1644         struct GUID *ntds_guid_new;
1645         struct GUID *ntds_guid_old;
1646
1647         /* see if we have a cached copy */
1648         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, cache_name);
1649
1650         tmp_ctx = talloc_new(ldb);
1651         if (tmp_ctx == NULL) {
1652                 goto failed;
1653         }
1654
1655         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1656         if (!ntds_guid_new) {
1657                 goto failed;
1658         }
1659
1660         *ntds_guid_new = *ntds_guid_in;
1661
1662         /* cache the domain_sid in the ldb */
1663         if (ldb_set_opaque(ldb, cache_name, ntds_guid_new) != LDB_SUCCESS) {
1664                 goto failed;
1665         }
1666
1667         talloc_steal(ldb, ntds_guid_new);
1668         talloc_free(tmp_ctx);
1669         talloc_free(ntds_guid_old);
1670
1671         return true;
1672
1673 failed:
1674         DBG_WARNING("Failed to set our own cached %s in the ldb!\n",
1675                     attribute);
1676         talloc_free(tmp_ctx);
1677         return false;
1678 }
1679
1680 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1681 {
1682         return samdb_set_ntds_GUID(ldb,
1683                                    ntds_guid_in,
1684                                    "objectGUID",
1685                                    "cache.ntds_guid");
1686 }
1687
1688 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1689 {
1690         return samdb_set_ntds_GUID(ldb,
1691                                    invocation_id_in,
1692                                    "invocationId",
1693                                    "cache.invocation_id");
1694 }
1695
1696 /*
1697   work out the server dn for the current open ldb
1698 */
1699 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1700 {
1701         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1702         struct ldb_dn *dn;
1703         if (!tmp_ctx) {
1704                 return NULL;
1705         }
1706         dn = ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb, tmp_ctx));
1707         talloc_free(tmp_ctx);
1708         return dn;
1709
1710 }
1711
1712 /*
1713   work out the server dn for the current open ldb
1714 */
1715 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1716 {
1717         struct ldb_dn *server_dn;
1718         struct ldb_dn *servers_dn;
1719         struct ldb_dn *server_site_dn;
1720
1721         /* TODO: there must be a saner way to do this!! */
1722         server_dn = samdb_server_dn(ldb, mem_ctx);
1723         if (!server_dn) return NULL;
1724
1725         servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1726         talloc_free(server_dn);
1727         if (!servers_dn) return NULL;
1728
1729         server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1730         talloc_free(servers_dn);
1731
1732         return server_site_dn;
1733 }
1734
1735 /*
1736   find the site name from a computers DN record
1737  */
1738 int samdb_find_site_for_computer(struct ldb_context *ldb,
1739                                  TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1740                                  const char **site_name)
1741 {
1742         int ret;
1743         struct ldb_dn *dn;
1744         const struct ldb_val *rdn_val;
1745
1746         *site_name = NULL;
1747
1748         ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1749         if (ret != LDB_SUCCESS) {
1750                 return ret;
1751         }
1752
1753         if (!ldb_dn_remove_child_components(dn, 2)) {
1754                 talloc_free(dn);
1755                 return LDB_ERR_INVALID_DN_SYNTAX;
1756         }
1757
1758         rdn_val = ldb_dn_get_rdn_val(dn);
1759         if (rdn_val == NULL) {
1760                 return LDB_ERR_OPERATIONS_ERROR;
1761         }
1762
1763         (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1764         talloc_free(dn);
1765         if (!*site_name) {
1766                 return LDB_ERR_OPERATIONS_ERROR;
1767         }
1768         return LDB_SUCCESS;
1769 }
1770
1771 /*
1772   find the NTDS GUID from a computers DN record
1773  */
1774 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1775                                      struct GUID *ntds_guid)
1776 {
1777         int ret;
1778         struct ldb_dn *dn;
1779
1780         *ntds_guid = GUID_zero();
1781
1782         ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1783         if (ret != LDB_SUCCESS) {
1784                 return ret;
1785         }
1786
1787         if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1788                 talloc_free(dn);
1789                 return LDB_ERR_OPERATIONS_ERROR;
1790         }
1791
1792         ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1793         talloc_free(dn);
1794         return ret;
1795 }
1796
1797 /*
1798   find a 'reference' DN that points at another object
1799   (eg. serverReference, rIDManagerReference etc)
1800  */
1801 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1802                        const char *attribute, struct ldb_dn **dn)
1803 {
1804         const char *attrs[2];
1805         struct ldb_result *res;
1806         int ret;
1807
1808         attrs[0] = attribute;
1809         attrs[1] = NULL;
1810
1811         ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY|DSDB_SEARCH_SHOW_EXTENDED_DN, NULL);
1812         if (ret != LDB_SUCCESS) {
1813                 ldb_asprintf_errstring(ldb, "Cannot find DN %s to get attribute %s for reference dn: %s",
1814                                        ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb));
1815                 return ret;
1816         }
1817
1818         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1819         if (!*dn) {
1820                 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1821                         ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1822                                                ldb_dn_get_linearized(base));
1823                 } else {
1824                         ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1825                                                ldb_dn_get_linearized(base));
1826                 }
1827                 talloc_free(res);
1828                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1829         }
1830
1831         talloc_free(res);
1832         return LDB_SUCCESS;
1833 }
1834
1835 /*
1836   find if a DN (must have GUID component!) is our ntdsDsa
1837  */
1838 int samdb_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *dn, bool *is_ntdsa)
1839 {
1840         NTSTATUS status;
1841         struct GUID dn_guid;
1842         const struct GUID *our_ntds_guid;
1843         status = dsdb_get_extended_dn_guid(dn, &dn_guid, "GUID");
1844         if (!NT_STATUS_IS_OK(status)) {
1845                 return LDB_ERR_OPERATIONS_ERROR;
1846         }
1847
1848         our_ntds_guid = samdb_ntds_objectGUID(ldb);
1849         if (!our_ntds_guid) {
1850                 DEBUG(0, ("Failed to find our NTDS Settings GUID for comparison with %s - %s\n", ldb_dn_get_linearized(dn), ldb_errstring(ldb)));
1851                 return LDB_ERR_OPERATIONS_ERROR;
1852         }
1853
1854         *is_ntdsa = GUID_equal(&dn_guid, our_ntds_guid);
1855         return LDB_SUCCESS;
1856 }
1857
1858 /*
1859   find a 'reference' DN that points at another object and indicate if it is our ntdsDsa
1860  */
1861 int samdb_reference_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *base,
1862                                     const char *attribute, bool *is_ntdsa)
1863 {
1864         int ret;
1865         struct ldb_dn *referenced_dn;
1866         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1867         if (tmp_ctx == NULL) {
1868                 return LDB_ERR_OPERATIONS_ERROR;
1869         }
1870         ret = samdb_reference_dn(ldb, tmp_ctx, base, attribute, &referenced_dn);
1871         if (ret != LDB_SUCCESS) {
1872                 DEBUG(0, ("Failed to find object %s for attribute %s - %s\n", ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb)));
1873                 return ret;
1874         }
1875
1876         ret = samdb_dn_is_our_ntdsa(ldb, referenced_dn, is_ntdsa);
1877
1878         talloc_free(tmp_ctx);
1879         return ret;
1880 }
1881
1882 /*
1883   find our machine account via the serverReference attribute in the
1884   server DN
1885  */
1886 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1887 {
1888         struct ldb_dn *server_dn;
1889         int ret;
1890
1891         server_dn = samdb_server_dn(ldb, mem_ctx);
1892         if (server_dn == NULL) {
1893                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
1894         }
1895
1896         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1897         talloc_free(server_dn);
1898
1899         return ret;
1900 }
1901
1902 /*
1903   find the RID Manager$ DN via the rIDManagerReference attribute in the
1904   base DN
1905  */
1906 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1907 {
1908         return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1909                                   "rIDManagerReference", dn);
1910 }
1911
1912 /*
1913   find the RID Set DN via the rIDSetReferences attribute in our
1914   machine account DN
1915  */
1916 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1917 {
1918         struct ldb_dn *server_ref_dn = NULL;
1919         int ret;
1920
1921         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1922         if (ret != LDB_SUCCESS) {
1923                 return ret;
1924         }
1925         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1926         talloc_free(server_ref_dn);
1927         return ret;
1928 }
1929
1930 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1931 {
1932         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1933                                                                             mem_ctx));
1934
1935         if (val == NULL) {
1936                 return NULL;
1937         }
1938
1939         return (const char *) val->data;
1940 }
1941
1942 /*
1943  * Finds the client site by using the client's IP address.
1944  * The "subnet_name" returns the name of the subnet if parameter != NULL
1945  *
1946  * Has a Windows-based fallback to provide the only site available, or an empty
1947  * string if there are multiple sites.
1948  */
1949 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1950                                    const char *ip_address, char **subnet_name,
1951                                    bool fallback)
1952 {
1953         const char *attrs[] = { "cn", "siteObject", NULL };
1954         struct ldb_dn *sites_container_dn = NULL;
1955         struct ldb_dn *subnets_dn = NULL;
1956         struct ldb_dn *sites_dn = NULL;
1957         struct ldb_result *res = NULL;
1958         const struct ldb_val *val = NULL;
1959         const char *site_name = NULL;
1960         const char *l_subnet_name = NULL;
1961         const char *allow_list[2] = { NULL, NULL };
1962         unsigned int i, count;
1963         int ret;
1964
1965         /*
1966          * if we don't have a client ip e.g. ncalrpc
1967          * the server site is the client site
1968          */
1969         if (ip_address == NULL) {
1970                 return samdb_server_site_name(ldb, mem_ctx);
1971         }
1972
1973         sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1974         if (sites_container_dn == NULL) {
1975                 goto exit;
1976         }
1977
1978         subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1979         if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1980                 goto exit;
1981         }
1982
1983         ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1984                          attrs, NULL);
1985         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1986                 count = 0;
1987         } else if (ret != LDB_SUCCESS) {
1988                 goto exit;
1989         } else {
1990                 count = res->count;
1991         }
1992
1993         for (i = 0; i < count; i++) {
1994                 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1995                                                             NULL);
1996
1997                 allow_list[0] = l_subnet_name;
1998
1999                 if (allow_access_nolog(NULL, allow_list, "", ip_address)) {
2000                         sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
2001                                                            res->msgs[i],
2002                                                            "siteObject");
2003                         if (sites_dn == NULL) {
2004                                 /* No reference, maybe another subnet matches */
2005                                 continue;
2006                         }
2007
2008                         /* "val" cannot be NULL here since "sites_dn" != NULL */
2009                         val = ldb_dn_get_rdn_val(sites_dn);
2010                         site_name = talloc_strdup(mem_ctx,
2011                                                   (const char *) val->data);
2012
2013                         TALLOC_FREE(sites_dn);
2014
2015                         break;
2016                 }
2017         }
2018
2019         if (site_name == NULL && fallback) {
2020                 /* This is the Windows Server fallback rule: when no subnet
2021                  * exists and we have only one site available then use it (it
2022                  * is for sure the same as our server site). If more sites do
2023                  * exist then we don't know which one to use and set the site
2024                  * name to "". */
2025                 size_t cnt = 0;
2026                 ret = dsdb_domain_count(
2027                         ldb,
2028                         &cnt,
2029                         sites_container_dn,
2030                         NULL,
2031                         LDB_SCOPE_SUBTREE,
2032                         "(objectClass=site)");
2033                 if (ret != LDB_SUCCESS) {
2034                         goto exit;
2035                 }
2036                 if (cnt == 1) {
2037                         site_name = samdb_server_site_name(ldb, mem_ctx);
2038                 } else {
2039                         site_name = talloc_strdup(mem_ctx, "");
2040                 }
2041                 l_subnet_name = NULL;
2042         }
2043
2044         if (subnet_name != NULL) {
2045                 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
2046         }
2047
2048 exit:
2049         TALLOC_FREE(sites_container_dn);
2050         TALLOC_FREE(subnets_dn);
2051         TALLOC_FREE(res);
2052
2053         return site_name;
2054 }
2055
2056 /*
2057   work out if we are the PDC for the domain of the current open ldb
2058 */
2059 bool samdb_is_pdc(struct ldb_context *ldb)
2060 {
2061         int ret;
2062         bool is_pdc;
2063
2064         ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner",
2065                                               &is_pdc);
2066         if (ret != LDB_SUCCESS) {
2067                 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n",
2068                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)),
2069                          ldb_errstring(ldb)));
2070                 return false;
2071         }
2072
2073         return is_pdc;
2074 }
2075
2076 /*
2077   work out if we are a Global Catalog server for the domain of the current open ldb
2078 */
2079 bool samdb_is_gc(struct ldb_context *ldb)
2080 {
2081         uint32_t options = 0;
2082         if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
2083                 return false;
2084         }
2085         return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
2086 }
2087
2088 /* Find a domain object in the parents of a particular DN.  */
2089 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2090                                    struct ldb_dn **parent_dn, const char **errstring)
2091 {
2092         TALLOC_CTX *local_ctx;
2093         struct ldb_dn *sdn = dn;
2094         struct ldb_result *res = NULL;
2095         int ret = LDB_SUCCESS;
2096         const char *attrs[] = { NULL };
2097
2098         local_ctx = talloc_new(mem_ctx);
2099         if (local_ctx == NULL) return ldb_oom(ldb);
2100
2101         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
2102                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
2103                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
2104                 if (ret == LDB_SUCCESS) {
2105                         if (res->count == 1) {
2106                                 break;
2107                         }
2108                 } else {
2109                         break;
2110                 }
2111         }
2112
2113         if (ret != LDB_SUCCESS) {
2114                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
2115                                              ldb_dn_get_linearized(dn),
2116                                              ldb_dn_get_linearized(sdn),
2117                                              ldb_errstring(ldb));
2118                 talloc_free(local_ctx);
2119                 return ret;
2120         }
2121         /* should never be true with 'ret=LDB_SUCCESS', here to satisfy clang */
2122         if (res == NULL) {
2123                 talloc_free(local_ctx);
2124                 return LDB_ERR_OTHER;
2125         }
2126         if (res->count != 1) {
2127                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
2128                                              ldb_dn_get_linearized(dn));
2129                 DEBUG(0,(__location__ ": %s\n", *errstring));
2130                 talloc_free(local_ctx);
2131                 return LDB_ERR_CONSTRAINT_VIOLATION;
2132         }
2133
2134         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2135         talloc_free(local_ctx);
2136         return ret;
2137 }
2138
2139 static void pwd_timeout_debug(struct tevent_context *unused1,
2140                               struct tevent_timer *unused2,
2141                               struct timeval unused3,
2142                               void *unused4)
2143 {
2144         DEBUG(0, ("WARNING: check_password_complexity: password script "
2145                   "took more than 1 second to run\n"));
2146 }
2147
2148
2149 /*
2150  * Performs checks on a user password (plaintext UNIX format - attribute
2151  * "password"). The remaining parameters have to be extracted from the domain
2152  * object in the AD.
2153  *
2154  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
2155  */
2156 enum samr_ValidationStatus samdb_check_password(TALLOC_CTX *mem_ctx,
2157                                                 struct loadparm_context *lp_ctx,
2158                                                 const char *account_name,
2159                                                 const char *user_principal_name,
2160                                                 const char *full_name,
2161                                                 const DATA_BLOB *utf8_blob,
2162                                                 const uint32_t pwdProperties,
2163                                                 const uint32_t minPwdLength)
2164 {
2165         const struct loadparm_substitution *lp_sub =
2166                 lpcfg_noop_substitution();
2167         char *password_script = NULL;
2168         const char *utf8_pw = (const char *)utf8_blob->data;
2169
2170         /*
2171          * This looks strange because it is.
2172          *
2173          * The check for the number of characters in the password
2174          * should clearly not be against the byte length, or else a
2175          * single UTF8 character would count for more than one.
2176          *
2177          * We have chosen to use the number of 16-bit units that the
2178          * password encodes to as the measure of length.  This is not
2179          * the same as the number of codepoints, if a password
2180          * contains a character beyond the Basic Multilingual Plane
2181          * (above 65535) it will count for more than one "character".
2182          */
2183
2184         size_t password_characters_roughly = strlen_m(utf8_pw);
2185
2186         /* checks if the "minPwdLength" property is satisfied */
2187         if (minPwdLength > password_characters_roughly) {
2188                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2189         }
2190
2191         /* We might not be asked to check the password complexity */
2192         if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
2193                 return SAMR_VALIDATION_STATUS_SUCCESS;
2194         }
2195
2196         if (password_characters_roughly == 0) {
2197                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2198         }
2199
2200         password_script = lpcfg_check_password_script(lp_ctx, lp_sub, mem_ctx);
2201         if (password_script != NULL && *password_script != '\0') {
2202                 int check_ret = 0;
2203                 int error = 0;
2204                 ssize_t nwritten = 0;
2205                 struct tevent_context *event_ctx = NULL;
2206                 struct tevent_req *req = NULL;
2207                 int cps_stdin = -1;
2208                 const char * const cmd[4] = {
2209                         "/bin/sh", "-c",
2210                         password_script,
2211                         NULL
2212                 };
2213
2214                 event_ctx = tevent_context_init(mem_ctx);
2215                 if (event_ctx == NULL) {
2216                         TALLOC_FREE(password_script);
2217                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2218                 }
2219
2220                 /* Gives a warning after 1 second, terminates after 10 */
2221                 tevent_add_timer(event_ctx, event_ctx,
2222                                  tevent_timeval_current_ofs(1, 0),
2223                                  pwd_timeout_debug, NULL);
2224
2225                 check_ret = setenv("SAMBA_CPS_ACCOUNT_NAME", account_name, 1);
2226                 if (check_ret != 0) {
2227                         TALLOC_FREE(password_script);
2228                         TALLOC_FREE(event_ctx);
2229                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2230                 }
2231                 if (user_principal_name != NULL) {
2232                         check_ret = setenv("SAMBA_CPS_USER_PRINCIPAL_NAME",
2233                                            user_principal_name, 1);
2234                 } else {
2235                         unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2236                 }
2237                 if (check_ret != 0) {
2238                         TALLOC_FREE(password_script);
2239                         TALLOC_FREE(event_ctx);
2240                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2241                 }
2242                 if (full_name != NULL) {
2243                         check_ret = setenv("SAMBA_CPS_FULL_NAME", full_name, 1);
2244                 } else {
2245                         unsetenv("SAMBA_CPS_FULL_NAME");
2246                 }
2247                 if (check_ret != 0) {
2248                         TALLOC_FREE(password_script);
2249                         TALLOC_FREE(event_ctx);
2250                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2251                 }
2252
2253                 req = samba_runcmd_send(event_ctx, event_ctx,
2254                                         tevent_timeval_current_ofs(10, 0),
2255                                         100, 100, cmd, NULL);
2256                 unsetenv("SAMBA_CPS_ACCOUNT_NAME");
2257                 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2258                 unsetenv("SAMBA_CPS_FULL_NAME");
2259                 if (req == NULL) {
2260                         TALLOC_FREE(password_script);
2261                         TALLOC_FREE(event_ctx);
2262                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2263                 }
2264
2265                 cps_stdin = samba_runcmd_export_stdin(req);
2266
2267                 nwritten = write_data(
2268                         cps_stdin, utf8_blob->data, utf8_blob->length);
2269                 if (nwritten == -1) {
2270                         close(cps_stdin);
2271                         TALLOC_FREE(password_script);
2272                         TALLOC_FREE(event_ctx);
2273                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2274                 }
2275
2276                 close(cps_stdin);
2277
2278                 if (!tevent_req_poll(req, event_ctx)) {
2279                         TALLOC_FREE(password_script);
2280                         TALLOC_FREE(event_ctx);
2281                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2282                 }
2283
2284                 check_ret = samba_runcmd_recv(req, &error);
2285                 TALLOC_FREE(event_ctx);
2286
2287                 if (error == ETIMEDOUT) {
2288                         DEBUG(0, ("check_password_complexity: check password script took too long!\n"));
2289                         TALLOC_FREE(password_script);
2290                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2291                 }
2292                 DEBUG(5,("check_password_complexity: check password script (%s) "
2293                          "returned [%d]\n", password_script, check_ret));
2294
2295                 if (check_ret != 0) {
2296                         DEBUG(1,("check_password_complexity: "
2297                                  "check password script said new password is not good "
2298                                  "enough!\n"));
2299                         TALLOC_FREE(password_script);
2300                         return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2301                 }
2302
2303                 TALLOC_FREE(password_script);
2304                 return SAMR_VALIDATION_STATUS_SUCCESS;
2305         }
2306
2307         TALLOC_FREE(password_script);
2308
2309         /*
2310          * Here are the standard AD password quality rules, which we
2311          * run after the script.
2312          */
2313
2314         if (!check_password_quality(utf8_pw)) {
2315                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2316         }
2317
2318         return SAMR_VALIDATION_STATUS_SUCCESS;
2319 }
2320
2321 /*
2322  * Callback for "samdb_set_password" password change
2323  */
2324 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2325 {
2326         int ret;
2327
2328         if (!ares) {
2329                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2330         }
2331
2332         if (ares->error != LDB_SUCCESS) {
2333                 ret = ares->error;
2334                 req->context = talloc_steal(req,
2335                                             ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2336                 talloc_free(ares);
2337                 return ldb_request_done(req, ret);
2338         }
2339
2340         if (ares->type != LDB_REPLY_DONE) {
2341                 talloc_free(ares);
2342                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2343         }
2344
2345         req->context = talloc_steal(req,
2346                                     ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2347         talloc_free(ares);
2348         return ldb_request_done(req, LDB_SUCCESS);
2349 }
2350
2351 /*
2352  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2353  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2354  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2355  * user change or not. The "rejectReason" gives some more information if the
2356  * change failed.
2357  *
2358  * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2359  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2360  *   NT_STATUS_ACCESS_DENIED, NT_STATUS_ACCOUNT_LOCKED_OUT, NT_STATUS_NO_MEMORY
2361  */
2362 static NTSTATUS samdb_set_password_internal(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2363                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2364                             const DATA_BLOB *new_password,
2365                             const struct samr_Password *ntNewHash,
2366                             enum dsdb_password_checked old_password_checked,
2367                             enum samPwdChangeReason *reject_reason,
2368                             struct samr_DomInfo1 **_dominfo,
2369                             bool permit_interdomain_trust)
2370 {
2371         struct ldb_message *msg;
2372         struct ldb_message_element *el;
2373         struct ldb_request *req;
2374         struct dsdb_control_password_change_status *pwd_stat = NULL;
2375         int ret;
2376         bool hash_values = false;
2377         NTSTATUS status = NT_STATUS_OK;
2378
2379 #define CHECK_RET(x) \
2380         if (x != LDB_SUCCESS) { \
2381                 talloc_free(msg); \
2382                 return NT_STATUS_NO_MEMORY; \
2383         }
2384
2385         msg = ldb_msg_new(mem_ctx);
2386         if (msg == NULL) {
2387                 return NT_STATUS_NO_MEMORY;
2388         }
2389         msg->dn = user_dn;
2390         if ((new_password != NULL)
2391                         && ((ntNewHash == NULL))) {
2392                 /* we have the password as plaintext UTF16 */
2393                 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2394                                             new_password, NULL));
2395                 el = ldb_msg_find_element(msg, "clearTextPassword");
2396                 el->flags = LDB_FLAG_MOD_REPLACE;
2397         } else if ((new_password == NULL)
2398                         && ((ntNewHash != NULL))) {
2399                 /* we have a password as NT hash */
2400                 if (ntNewHash != NULL) {
2401                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2402                                 "unicodePwd", ntNewHash));
2403                         el = ldb_msg_find_element(msg, "unicodePwd");
2404                         el->flags = LDB_FLAG_MOD_REPLACE;
2405                 }
2406                 hash_values = true;
2407         } else {
2408                 /* the password wasn't specified correctly */
2409                 talloc_free(msg);
2410                 return NT_STATUS_INVALID_PARAMETER;
2411         }
2412
2413         /* build modify request */
2414         ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2415                                 samdb_set_password_callback, NULL);
2416         if (ret != LDB_SUCCESS) {
2417                 talloc_free(msg);
2418                 return NT_STATUS_NO_MEMORY;
2419         }
2420
2421         /* A password change operation */
2422         if (old_password_checked == DSDB_PASSWORD_CHECKED_AND_CORRECT) {
2423                 struct dsdb_control_password_change *change;
2424
2425                 change = talloc(req, struct dsdb_control_password_change);
2426                 if (change == NULL) {
2427                         talloc_free(req);
2428                         talloc_free(msg);
2429                         return NT_STATUS_NO_MEMORY;
2430                 }
2431
2432                 change->old_password_checked = old_password_checked;
2433
2434                 ret = ldb_request_add_control(req,
2435                                               DSDB_CONTROL_PASSWORD_CHANGE_OLD_PW_CHECKED_OID,
2436                                               true, change);
2437                 if (ret != LDB_SUCCESS) {
2438                         talloc_free(req);
2439                         talloc_free(msg);
2440                         return NT_STATUS_NO_MEMORY;
2441                 }
2442         }
2443         if (hash_values) {
2444                 ret = ldb_request_add_control(req,
2445                                               DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2446                                               true, NULL);
2447                 if (ret != LDB_SUCCESS) {
2448                         talloc_free(req);
2449                         talloc_free(msg);
2450                         return NT_STATUS_NO_MEMORY;
2451                 }
2452         }
2453         if (permit_interdomain_trust) {
2454                 ret = ldb_request_add_control(req,
2455                                               DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
2456                                               false, NULL);
2457                 if (ret != LDB_SUCCESS) {
2458                         talloc_free(req);
2459                         talloc_free(msg);
2460                         return NT_STATUS_NO_MEMORY;
2461                 }
2462         }
2463         ret = ldb_request_add_control(req,
2464                                       DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2465                                       true, NULL);
2466         if (ret != LDB_SUCCESS) {
2467                 talloc_free(req);
2468                 talloc_free(msg);
2469                 return NT_STATUS_NO_MEMORY;
2470         }
2471
2472         ret = ldb_request(ldb, req);
2473         if (ret == LDB_SUCCESS) {
2474                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2475         }
2476
2477         if (req->context != NULL) {
2478                 struct ldb_control *control = talloc_get_type_abort(req->context,
2479                                                                     struct ldb_control);
2480                 pwd_stat = talloc_get_type_abort(control->data,
2481                                                  struct dsdb_control_password_change_status);
2482                 talloc_steal(mem_ctx, pwd_stat);
2483         }
2484
2485         talloc_free(req);
2486         talloc_free(msg);
2487
2488         /* Sets the domain info (if requested) */
2489         if (_dominfo != NULL) {
2490                 struct samr_DomInfo1 *dominfo;
2491
2492                 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2493                 if (dominfo == NULL) {
2494                         return NT_STATUS_NO_MEMORY;
2495                 }
2496
2497                 if (pwd_stat != NULL) {
2498                         dominfo->min_password_length     = pwd_stat->domain_data.minPwdLength;
2499                         dominfo->password_properties     = pwd_stat->domain_data.pwdProperties;
2500                         dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2501                         dominfo->max_password_age        = pwd_stat->domain_data.maxPwdAge;
2502                         dominfo->min_password_age        = pwd_stat->domain_data.minPwdAge;
2503                 }
2504
2505                 *_dominfo = dominfo;
2506         }
2507
2508         if (reject_reason != NULL) {
2509                 if (pwd_stat != NULL) {
2510                         *reject_reason = pwd_stat->reject_reason;
2511                 } else {
2512                         *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2513                 }
2514         }
2515
2516         if (pwd_stat != NULL) {
2517                 talloc_free(pwd_stat);
2518         }
2519
2520         if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2521                 const char *errmsg = ldb_errstring(ldb);
2522                 char *endptr = NULL;
2523                 WERROR werr = WERR_GEN_FAILURE;
2524                 status = NT_STATUS_UNSUCCESSFUL;
2525                 if (errmsg != NULL) {
2526                         werr = W_ERROR(strtol(errmsg, &endptr, 16));
2527                         DBG_WARNING("%s\n", errmsg);
2528                 }
2529                 if (endptr != errmsg) {
2530                         if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2531                                 status = NT_STATUS_WRONG_PASSWORD;
2532                         }
2533                         if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2534                                 status = NT_STATUS_PASSWORD_RESTRICTION;
2535                         }
2536                         if (W_ERROR_EQUAL(werr, WERR_ACCOUNT_LOCKED_OUT)) {
2537                                 status = NT_STATUS_ACCOUNT_LOCKED_OUT;
2538                         }
2539                 }
2540         } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2541                 /* don't let the caller know if an account doesn't exist */
2542                 status = NT_STATUS_WRONG_PASSWORD;
2543         } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2544                 status = NT_STATUS_ACCESS_DENIED;
2545         } else if (ret != LDB_SUCCESS) {
2546                 DEBUG(1, ("Failed to set password on %s: %s\n",
2547                           ldb_dn_get_linearized(user_dn),
2548                           ldb_errstring(ldb)));
2549                 status = NT_STATUS_UNSUCCESSFUL;
2550         }
2551
2552         return status;
2553 }
2554
2555 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2556                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2557                             const DATA_BLOB *new_password,
2558                             const struct samr_Password *ntNewHash,
2559                             enum dsdb_password_checked old_password_checked,
2560                             enum samPwdChangeReason *reject_reason,
2561                             struct samr_DomInfo1 **_dominfo)
2562 {
2563         return samdb_set_password_internal(ldb, mem_ctx,
2564                             user_dn, domain_dn,
2565                             new_password,
2566                             ntNewHash,
2567                             old_password_checked,
2568                             reject_reason, _dominfo,
2569                             false); /* reject trusts */
2570 }
2571
2572 /*
2573  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2574  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2575  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2576  * user change or not. The "rejectReason" gives some more information if the
2577  * change failed.
2578  *
2579  * This wrapper function for "samdb_set_password" takes a SID as input rather
2580  * than a user DN.
2581  *
2582  * This call encapsulates a new LDB transaction for changing the password;
2583  * therefore the user hasn't to start a new one.
2584  *
2585  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2586  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2587  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2588  *   NT_STATUS_ACCESS_DENIED, NT_STATUS_ACCOUNT_LOCKED_OUT, NT_STATUS_NO_MEMORY
2589  *   NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2590  */
2591 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2592                                 const struct dom_sid *user_sid,
2593                                 const uint32_t *new_version, /* optional for trusts */
2594                                 const DATA_BLOB *new_password,
2595                                 const struct samr_Password *ntNewHash,
2596                                 enum dsdb_password_checked old_password_checked,
2597                                 enum samPwdChangeReason *reject_reason,
2598                                 struct samr_DomInfo1 **_dominfo)
2599 {
2600         TALLOC_CTX *frame = talloc_stackframe();
2601         NTSTATUS nt_status;
2602         static const char * const attrs[] = {
2603                 "userAccountControl",
2604                 "sAMAccountName",
2605                 NULL
2606         };
2607         struct ldb_message *user_msg = NULL;
2608         int ret;
2609         uint32_t uac = 0;
2610
2611         ret = ldb_transaction_start(ldb);
2612         if (ret != LDB_SUCCESS) {
2613                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2614                 TALLOC_FREE(frame);
2615                 return NT_STATUS_TRANSACTION_ABORTED;
2616         }
2617
2618         ret = dsdb_search_one(ldb, frame, &user_msg, ldb_get_default_basedn(ldb),
2619                               LDB_SCOPE_SUBTREE, attrs, 0,
2620                               "(&(objectSid=%s)(objectClass=user))",
2621                               ldap_encode_ndr_dom_sid(frame, user_sid));
2622         if (ret != LDB_SUCCESS) {
2623                 ldb_transaction_cancel(ldb);
2624                 DEBUG(3, ("samdb_set_password_sid: SID[%s] not found in samdb %s - %s, "
2625                           "returning NO_SUCH_USER\n",
2626                           dom_sid_string(frame, user_sid),
2627                           ldb_strerror(ret), ldb_errstring(ldb)));
2628                 TALLOC_FREE(frame);
2629                 return NT_STATUS_NO_SUCH_USER;
2630         }
2631
2632         uac = ldb_msg_find_attr_as_uint(user_msg, "userAccountControl", 0);
2633         if (!(uac & UF_ACCOUNT_TYPE_MASK)) {
2634                 ldb_transaction_cancel(ldb);
2635                 DEBUG(1, ("samdb_set_password_sid: invalid "
2636                           "userAccountControl[0x%08X] for SID[%s] DN[%s], "
2637                           "returning NO_SUCH_USER\n",
2638                           (unsigned)uac, dom_sid_string(frame, user_sid),
2639                           ldb_dn_get_linearized(user_msg->dn)));
2640                 TALLOC_FREE(frame);
2641                 return NT_STATUS_NO_SUCH_USER;
2642         }
2643
2644         if (uac & UF_INTERDOMAIN_TRUST_ACCOUNT) {
2645                 static const char * const tdo_attrs[] = {
2646                         "trustAuthIncoming",
2647                         "trustDirection",
2648                         NULL
2649                 };
2650                 struct ldb_message *tdo_msg = NULL;
2651                 const char *account_name = NULL;
2652                 uint32_t trust_direction;
2653                 uint32_t i;
2654                 const struct ldb_val *old_val = NULL;
2655                 struct trustAuthInOutBlob old_blob = {
2656                         .count = 0,
2657                 };
2658                 uint32_t old_version = 0;
2659                 struct AuthenticationInformation *old_version_a = NULL;
2660                 uint32_t _new_version = 0;
2661                 struct trustAuthInOutBlob new_blob = {
2662                         .count = 0,
2663                 };
2664                 struct ldb_val new_val = {
2665                         .length = 0,
2666                 };
2667                 struct timeval tv = timeval_current();
2668                 NTTIME now = timeval_to_nttime(&tv);
2669                 enum ndr_err_code ndr_err;
2670
2671                 if (new_password == NULL && ntNewHash == NULL) {
2672                         ldb_transaction_cancel(ldb);
2673                         DEBUG(1, ("samdb_set_password_sid: "
2674                                   "no new password provided "
2675                                   "sAMAccountName for SID[%s] DN[%s], "
2676                                   "returning INVALID_PARAMETER\n",
2677                                   dom_sid_string(frame, user_sid),
2678                                   ldb_dn_get_linearized(user_msg->dn)));
2679                         TALLOC_FREE(frame);
2680                         return NT_STATUS_INVALID_PARAMETER;
2681                 }
2682
2683                 if (new_password != NULL && ntNewHash != NULL) {
2684                         ldb_transaction_cancel(ldb);
2685                         DEBUG(1, ("samdb_set_password_sid: "
2686                                   "two new passwords provided "
2687                                   "sAMAccountName for SID[%s] DN[%s], "
2688                                   "returning INVALID_PARAMETER\n",
2689                                   dom_sid_string(frame, user_sid),
2690                                   ldb_dn_get_linearized(user_msg->dn)));
2691                         TALLOC_FREE(frame);
2692                         return NT_STATUS_INVALID_PARAMETER;
2693                 }
2694
2695                 if (new_password != NULL && (new_password->length % 2)) {
2696                         ldb_transaction_cancel(ldb);
2697                         DEBUG(2, ("samdb_set_password_sid: "
2698                                   "invalid utf16 length (%zu) "
2699                                   "sAMAccountName for SID[%s] DN[%s], "
2700                                   "returning WRONG_PASSWORD\n",
2701                                   new_password->length,
2702                                   dom_sid_string(frame, user_sid),
2703                                   ldb_dn_get_linearized(user_msg->dn)));
2704                         TALLOC_FREE(frame);
2705                         return NT_STATUS_WRONG_PASSWORD;
2706                 }
2707
2708                 if (new_password != NULL && new_password->length >= 500) {
2709                         ldb_transaction_cancel(ldb);
2710                         DEBUG(2, ("samdb_set_password_sid: "
2711                                   "utf16 password too long (%zu) "
2712                                   "sAMAccountName for SID[%s] DN[%s], "
2713                                   "returning WRONG_PASSWORD\n",
2714                                   new_password->length,
2715                                   dom_sid_string(frame, user_sid),
2716                                   ldb_dn_get_linearized(user_msg->dn)));
2717                         TALLOC_FREE(frame);
2718                         return NT_STATUS_WRONG_PASSWORD;
2719                 }
2720
2721                 account_name = ldb_msg_find_attr_as_string(user_msg,
2722                                                         "sAMAccountName", NULL);
2723                 if (account_name == NULL) {
2724                         ldb_transaction_cancel(ldb);
2725                         DEBUG(1, ("samdb_set_password_sid: missing "
2726                                   "sAMAccountName for SID[%s] DN[%s], "
2727                                   "returning NO_SUCH_USER\n",
2728                                   dom_sid_string(frame, user_sid),
2729                                   ldb_dn_get_linearized(user_msg->dn)));
2730                         TALLOC_FREE(frame);
2731                         return NT_STATUS_NO_SUCH_USER;
2732                 }
2733
2734                 nt_status = dsdb_trust_search_tdo_by_type(ldb,
2735                                                           SEC_CHAN_DOMAIN,
2736                                                           account_name,
2737                                                           tdo_attrs,
2738                                                           frame, &tdo_msg);
2739                 if (!NT_STATUS_IS_OK(nt_status)) {
2740                         ldb_transaction_cancel(ldb);
2741                         DEBUG(1, ("samdb_set_password_sid: dsdb_trust_search_tdo "
2742                                   "failed(%s) for sAMAccountName[%s] SID[%s] DN[%s], "
2743                                   "returning INTERNAL_DB_CORRUPTION\n",
2744                                   nt_errstr(nt_status), account_name,
2745                                   dom_sid_string(frame, user_sid),
2746                                   ldb_dn_get_linearized(user_msg->dn)));
2747                         TALLOC_FREE(frame);
2748                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
2749                 }
2750
2751                 trust_direction = ldb_msg_find_attr_as_int(tdo_msg,
2752                                                            "trustDirection", 0);
2753                 if (!(trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {
2754                         ldb_transaction_cancel(ldb);
2755                         DEBUG(1, ("samdb_set_password_sid: direction[0x%08X] is "
2756                                   "not inbound for sAMAccountName[%s] "
2757                                   "DN[%s] TDO[%s], "
2758                                   "returning INTERNAL_DB_CORRUPTION\n",
2759                                   (unsigned)trust_direction,
2760                                   account_name,
2761                                   ldb_dn_get_linearized(user_msg->dn),
2762                                   ldb_dn_get_linearized(tdo_msg->dn)));
2763                         TALLOC_FREE(frame);
2764                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
2765                 }
2766
2767                 old_val = ldb_msg_find_ldb_val(tdo_msg, "trustAuthIncoming");
2768                 if (old_val != NULL) {
2769                         ndr_err = ndr_pull_struct_blob(old_val, frame, &old_blob,
2770                                         (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2771                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2772                                 ldb_transaction_cancel(ldb);
2773                                 DEBUG(1, ("samdb_set_password_sid: "
2774                                           "failed(%s) to parse "
2775                                           "trustAuthOutgoing sAMAccountName[%s] "
2776                                           "DN[%s] TDO[%s], "
2777                                           "returning INTERNAL_DB_CORRUPTION\n",
2778                                           ndr_map_error2string(ndr_err),
2779                                           account_name,
2780                                           ldb_dn_get_linearized(user_msg->dn),
2781                                           ldb_dn_get_linearized(tdo_msg->dn)));
2782
2783                                 TALLOC_FREE(frame);
2784                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2785                         }
2786                 }
2787
2788                 for (i = old_blob.current.count; i > 0; i--) {
2789                         struct AuthenticationInformation *a =
2790                                 &old_blob.current.array[i - 1];
2791
2792                         switch (a->AuthType) {
2793                         case TRUST_AUTH_TYPE_NONE:
2794                                 if (i == old_blob.current.count) {
2795                                         /*
2796                                          * remove TRUST_AUTH_TYPE_NONE at the
2797                                          * end
2798                                          */
2799                                         old_blob.current.count--;
2800                                 }
2801                                 break;
2802
2803                         case TRUST_AUTH_TYPE_VERSION:
2804                                 old_version_a = a;
2805                                 old_version = a->AuthInfo.version.version;
2806                                 break;
2807
2808                         case TRUST_AUTH_TYPE_CLEAR:
2809                                 break;
2810
2811                         case TRUST_AUTH_TYPE_NT4OWF:
2812                                 break;
2813                         }
2814                 }
2815
2816                 if (new_version == NULL) {
2817                         _new_version = 0;
2818                         new_version = &_new_version;
2819                 }
2820
2821                 if (old_version_a != NULL && *new_version != (old_version + 1)) {
2822                         old_version_a->LastUpdateTime = now;
2823                         old_version_a->AuthType = TRUST_AUTH_TYPE_NONE;
2824                 }
2825
2826                 new_blob.count = MAX(old_blob.current.count, 2);
2827                 new_blob.current.array = talloc_zero_array(frame,
2828                                                 struct AuthenticationInformation,
2829                                                 new_blob.count);
2830                 if (new_blob.current.array == NULL) {
2831                         ldb_transaction_cancel(ldb);
2832                         TALLOC_FREE(frame);
2833                         return NT_STATUS_NO_MEMORY;
2834                 }
2835                 new_blob.previous.array = talloc_zero_array(frame,
2836                                                 struct AuthenticationInformation,
2837                                                 new_blob.count);
2838                 if (new_blob.current.array == NULL) {
2839                         ldb_transaction_cancel(ldb);
2840                         TALLOC_FREE(frame);
2841                         return NT_STATUS_NO_MEMORY;
2842                 }
2843
2844                 for (i = 0; i < old_blob.current.count; i++) {
2845                         struct AuthenticationInformation *o =
2846                                 &old_blob.current.array[i];
2847                         struct AuthenticationInformation *p =
2848                                 &new_blob.previous.array[i];
2849
2850                         *p = *o;
2851                         new_blob.previous.count++;
2852                 }
2853                 for (; i < new_blob.count; i++) {
2854                         struct AuthenticationInformation *pi =
2855                                 &new_blob.previous.array[i];
2856
2857                         if (i == 0) {
2858                                 /*
2859                                  * new_blob.previous is still empty so
2860                                  * we'll do new_blob.previous = new_blob.current
2861                                  * below.
2862                                  */
2863                                 break;
2864                         }
2865
2866                         pi->LastUpdateTime = now;
2867                         pi->AuthType = TRUST_AUTH_TYPE_NONE;
2868                         new_blob.previous.count++;
2869                 }
2870
2871                 for (i = 0; i < new_blob.count; i++) {
2872                         struct AuthenticationInformation *ci =
2873                                 &new_blob.current.array[i];
2874
2875                         ci->LastUpdateTime = now;
2876                         switch (i) {
2877                         case 0:
2878                                 if (ntNewHash != NULL) {
2879                                         ci->AuthType = TRUST_AUTH_TYPE_NT4OWF;
2880                                         ci->AuthInfo.nt4owf.password = *ntNewHash;
2881                                         break;
2882                                 }
2883
2884                                 ci->AuthType = TRUST_AUTH_TYPE_CLEAR;
2885                                 ci->AuthInfo.clear.size = new_password->length;
2886                                 ci->AuthInfo.clear.password = new_password->data;
2887                                 break;
2888                         case 1:
2889                                 ci->AuthType = TRUST_AUTH_TYPE_VERSION;
2890                                 ci->AuthInfo.version.version = *new_version;
2891                                 break;
2892                         default:
2893                                 ci->AuthType = TRUST_AUTH_TYPE_NONE;
2894                                 break;
2895                         }
2896
2897                         new_blob.current.count++;
2898                 }
2899
2900                 if (new_blob.previous.count == 0) {
2901                         TALLOC_FREE(new_blob.previous.array);
2902                         new_blob.previous = new_blob.current;
2903                 }
2904
2905                 ndr_err = ndr_push_struct_blob(&new_val, frame, &new_blob,
2906                                 (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2907                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2908                         ldb_transaction_cancel(ldb);
2909                         DEBUG(1, ("samdb_set_password_sid: "
2910                                   "failed(%s) to generate "
2911                                   "trustAuthOutgoing sAMAccountName[%s] "
2912                                   "DN[%s] TDO[%s], "
2913                                   "returning UNSUCCESSFUL\n",
2914                                   ndr_map_error2string(ndr_err),
2915                                   account_name,
2916                                   ldb_dn_get_linearized(user_msg->dn),
2917                                   ldb_dn_get_linearized(tdo_msg->dn)));
2918                         TALLOC_FREE(frame);
2919                         return NT_STATUS_UNSUCCESSFUL;
2920                 }
2921
2922                 tdo_msg->num_elements = 0;
2923                 TALLOC_FREE(tdo_msg->elements);
2924
2925                 ret = ldb_msg_append_value(tdo_msg, "trustAuthIncoming",
2926                                            &new_val, LDB_FLAG_MOD_REPLACE);
2927                 if (ret != LDB_SUCCESS) {
2928                         ldb_transaction_cancel(ldb);
2929                         TALLOC_FREE(frame);
2930                         return NT_STATUS_NO_MEMORY;
2931                 }
2932
2933                 ret = ldb_modify(ldb, tdo_msg);
2934                 if (ret != LDB_SUCCESS) {
2935                         nt_status = dsdb_ldb_err_to_ntstatus(ret);
2936                         ldb_transaction_cancel(ldb);
2937                         DEBUG(1, ("samdb_set_password_sid: "
2938                                   "failed to replace "
2939                                   "trustAuthOutgoing sAMAccountName[%s] "
2940                                   "DN[%s] TDO[%s], "
2941                                   "%s - %s\n",
2942                                   account_name,
2943                                   ldb_dn_get_linearized(user_msg->dn),
2944                                   ldb_dn_get_linearized(tdo_msg->dn),
2945                                   nt_errstr(nt_status), ldb_errstring(ldb)));
2946                         TALLOC_FREE(frame);
2947                         return nt_status;
2948                 }
2949         }
2950
2951         nt_status = samdb_set_password_internal(ldb, mem_ctx,
2952                                                 user_msg->dn, NULL,
2953                                                 new_password,
2954                                                 ntNewHash,
2955                                                 old_password_checked,
2956                                                 reject_reason, _dominfo,
2957                                                 true); /* permit trusts */
2958         if (!NT_STATUS_IS_OK(nt_status)) {
2959                 ldb_transaction_cancel(ldb);
2960                 TALLOC_FREE(frame);
2961                 return nt_status;
2962         }
2963
2964         ret = ldb_transaction_commit(ldb);
2965         if (ret != LDB_SUCCESS) {
2966                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2967                          ldb_dn_get_linearized(user_msg->dn),
2968                          ldb_errstring(ldb)));
2969                 TALLOC_FREE(frame);
2970                 return NT_STATUS_TRANSACTION_ABORTED;
2971         }
2972
2973         TALLOC_FREE(frame);
2974         return NT_STATUS_OK;
2975 }
2976
2977
2978 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
2979                                                  struct dom_sid *sid, struct ldb_dn **ret_dn)
2980 {
2981         struct ldb_message *msg;
2982         struct ldb_dn *basedn = NULL;
2983         char *sidstr;
2984         int ret;
2985
2986         sidstr = dom_sid_string(mem_ctx, sid);
2987         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2988
2989         /* We might have to create a ForeignSecurityPrincipal, even if this user
2990          * is in our own domain */
2991
2992         msg = ldb_msg_new(sidstr);
2993         if (msg == NULL) {
2994                 talloc_free(sidstr);
2995                 return NT_STATUS_NO_MEMORY;
2996         }
2997
2998         ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2999                                 ldb_get_default_basedn(sam_ctx),
3000                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
3001                                 &basedn);
3002         if (ret != LDB_SUCCESS) {
3003                 DEBUG(0, ("Failed to find DN for "
3004                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
3005                 talloc_free(sidstr);
3006                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
3007         }
3008
3009         /* add core elements to the ldb_message for the alias */
3010         msg->dn = basedn;
3011         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
3012                 talloc_free(sidstr);
3013                 return NT_STATUS_NO_MEMORY;
3014         }
3015
3016         ret = ldb_msg_add_string(msg, "objectClass",
3017                                  "foreignSecurityPrincipal");
3018         if (ret != LDB_SUCCESS) {
3019                 talloc_free(sidstr);
3020                 return NT_STATUS_NO_MEMORY;
3021         }
3022
3023         /* create the alias */
3024         ret = ldb_add(sam_ctx, msg);
3025         if (ret != LDB_SUCCESS) {
3026                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
3027                          "record %s: %s\n",
3028                          ldb_dn_get_linearized(msg->dn),
3029                          ldb_errstring(sam_ctx)));
3030                 talloc_free(sidstr);
3031                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
3032         }
3033
3034         *ret_dn = talloc_steal(mem_ctx, msg->dn);
3035         talloc_free(sidstr);
3036
3037         return NT_STATUS_OK;
3038 }
3039
3040
3041 /*
3042   Find the DN of a domain, assuming it to be a dotted.dns name
3043 */
3044
3045 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain)
3046 {
3047         unsigned int i;
3048         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3049         const char *binary_encoded;
3050         const char * const *split_realm;
3051         struct ldb_dn *dn;
3052
3053         if (!tmp_ctx) {
3054                 return NULL;
3055         }
3056
3057         split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
3058         if (!split_realm) {
3059                 talloc_free(tmp_ctx);
3060                 return NULL;
3061         }
3062         dn = ldb_dn_new(mem_ctx, ldb, NULL);
3063         for (i=0; split_realm[i]; i++) {
3064                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
3065                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
3066                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
3067                                   binary_encoded, ldb_dn_get_linearized(dn)));
3068                         talloc_free(tmp_ctx);
3069                         return NULL;
3070                 }
3071         }
3072         if (!ldb_dn_validate(dn)) {
3073                 DEBUG(2, ("Failed to validated DN %s\n",
3074                           ldb_dn_get_linearized(dn)));
3075                 talloc_free(tmp_ctx);
3076                 return NULL;
3077         }
3078         talloc_free(tmp_ctx);
3079         return dn;
3080 }
3081
3082
3083 /*
3084   Find the DNS equivalent of a DN, in dotted DNS form
3085 */
3086 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
3087 {
3088         int i, num_components = ldb_dn_get_comp_num(dn);
3089         char *dns_name = talloc_strdup(mem_ctx, "");
3090         if (dns_name == NULL) {
3091                 return NULL;
3092         }
3093
3094         for (i=0; i<num_components; i++) {
3095                 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
3096                 char *s;
3097                 if (v == NULL) {
3098                         talloc_free(dns_name);
3099                         return NULL;
3100                 }
3101                 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
3102                                                   (int)v->length, (int)v->length, (char *)v->data);
3103                 if (s == NULL) {
3104                         talloc_free(dns_name);
3105                         return NULL;
3106                 }
3107                 dns_name = s;
3108         }
3109
3110         /* remove the last '.' */
3111         if (dns_name[0] != 0) {
3112                 dns_name[strlen(dns_name)-1] = 0;
3113         }
3114
3115         return dns_name;
3116 }
3117
3118 /*
3119   Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
3120   name is based on the forest DNS name
3121 */
3122 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
3123                                 TALLOC_CTX *mem_ctx,
3124                                 const struct GUID *ntds_guid)
3125 {
3126         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3127         const char *guid_str;
3128         struct ldb_dn *forest_dn;
3129         const char *dnsforest;
3130         char *ret;
3131
3132         guid_str = GUID_string(tmp_ctx, ntds_guid);
3133         if (guid_str == NULL) {
3134                 talloc_free(tmp_ctx);
3135                 return NULL;
3136         }
3137         forest_dn = ldb_get_root_basedn(samdb);
3138         if (forest_dn == NULL) {
3139                 talloc_free(tmp_ctx);
3140                 return NULL;
3141         }
3142         dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
3143         if (dnsforest == NULL) {
3144                 talloc_free(tmp_ctx);
3145                 return NULL;
3146         }
3147         ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
3148         talloc_free(tmp_ctx);
3149         return ret;
3150 }
3151
3152
3153 /*
3154   Find the DN of a domain, be it the netbios or DNS name
3155 */
3156 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
3157                                   const char *domain_name)
3158 {
3159         const char * const domain_ref_attrs[] = {
3160                 "ncName", NULL
3161         };
3162         const char * const domain_ref2_attrs[] = {
3163                 NULL
3164         };
3165         struct ldb_result *res_domain_ref;
3166         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
3167         /* find the domain's DN */
3168         int ret_domain = ldb_search(ldb, mem_ctx,
3169                                             &res_domain_ref,
3170                                             samdb_partitions_dn(ldb, mem_ctx),
3171                                             LDB_SCOPE_ONELEVEL,
3172                                             domain_ref_attrs,
3173                                             "(&(nETBIOSName=%s)(objectclass=crossRef))",
3174                                             escaped_domain);
3175         if (ret_domain != LDB_SUCCESS) {
3176                 return NULL;
3177         }
3178
3179         if (res_domain_ref->count == 0) {
3180                 ret_domain = ldb_search(ldb, mem_ctx,
3181                                                 &res_domain_ref,
3182                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
3183                                                 LDB_SCOPE_BASE,
3184                                                 domain_ref2_attrs,
3185                                                 "(objectclass=domain)");
3186                 if (ret_domain != LDB_SUCCESS) {
3187                         return NULL;
3188                 }
3189
3190                 if (res_domain_ref->count == 1) {
3191                         return res_domain_ref->msgs[0]->dn;
3192                 }
3193                 return NULL;
3194         }
3195
3196         if (res_domain_ref->count > 1) {
3197                 DEBUG(0,("Found %d records matching domain [%s]\n",
3198                          ret_domain, domain_name));
3199                 return NULL;
3200         }
3201
3202         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
3203
3204 }
3205
3206
3207 /*
3208   use a GUID to find a DN
3209  */
3210 int dsdb_find_dn_by_guid(struct ldb_context *ldb,
3211                          TALLOC_CTX *mem_ctx,
3212                          const struct GUID *guid,
3213                          uint32_t dsdb_flags,
3214                          struct ldb_dn **dn)
3215 {
3216         int ret;
3217         struct ldb_result *res;
3218         const char *attrs[] = { NULL };
3219         struct GUID_txt_buf buf;
3220         char *guid_str = GUID_buf_string(guid, &buf);
3221
3222         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3223                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3224                           DSDB_SEARCH_SHOW_EXTENDED_DN |
3225                           DSDB_SEARCH_ONE_ONLY | dsdb_flags,
3226                           "objectGUID=%s", guid_str);
3227         if (ret != LDB_SUCCESS) {
3228                 return ret;
3229         }
3230
3231         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3232         talloc_free(res);
3233
3234         return LDB_SUCCESS;
3235 }
3236
3237 /*
3238   use a DN to find a GUID with a given attribute name
3239  */
3240 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
3241                               struct ldb_dn *dn, const char *attribute,
3242                               struct GUID *guid)
3243 {
3244         int ret;
3245         struct ldb_result *res = NULL;
3246         const char *attrs[2];
3247         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3248
3249         attrs[0] = attribute;
3250         attrs[1] = NULL;
3251
3252         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3253                              DSDB_SEARCH_SHOW_DELETED |
3254                              DSDB_SEARCH_SHOW_RECYCLED);
3255         if (ret != LDB_SUCCESS) {
3256                 talloc_free(tmp_ctx);
3257                 return ret;
3258         }
3259         /* satisfy clang */
3260         if (res == NULL) {
3261                 talloc_free(tmp_ctx);
3262                 return LDB_ERR_OTHER;
3263         }
3264         if (res->count < 1) {
3265                 talloc_free(tmp_ctx);
3266                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3267         }
3268         *guid = samdb_result_guid(res->msgs[0], attribute);
3269         talloc_free(tmp_ctx);
3270         return LDB_SUCCESS;
3271 }
3272
3273 /*
3274   use a DN to find a GUID
3275  */
3276 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
3277                          struct ldb_dn *dn, struct GUID *guid)
3278 {
3279         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
3280 }
3281
3282
3283
3284 /*
3285  adds the given GUID to the given ldb_message. This value is added
3286  for the given attr_name (may be either "objectGUID" or "parentGUID").
3287  This function is used in processing 'add' requests.
3288  */
3289 int dsdb_msg_add_guid(struct ldb_message *msg,
3290                 struct GUID *guid,
3291                 const char *attr_name)
3292 {
3293         int ret;
3294         struct ldb_val v;
3295         NTSTATUS status;
3296         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
3297
3298         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
3299         if (!NT_STATUS_IS_OK(status)) {
3300                 ret = LDB_ERR_OPERATIONS_ERROR;
3301                 goto done;
3302         }
3303
3304         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
3305         if (ret != LDB_SUCCESS) {
3306                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
3307                                          attr_name));
3308                 goto done;
3309         }
3310
3311         ret = LDB_SUCCESS;
3312
3313 done:
3314         talloc_free(tmp_ctx);
3315         return ret;
3316
3317 }
3318
3319
3320 /*
3321   use a DN to find a SID
3322  */
3323 int dsdb_find_sid_by_dn(struct ldb_context *ldb,
3324                         struct ldb_dn *dn, struct dom_sid *sid)
3325 {
3326         int ret;
3327         struct ldb_result *res = NULL;
3328         const char *attrs[] = { "objectSid", NULL };
3329         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3330         struct dom_sid *s;
3331
3332         ZERO_STRUCTP(sid);
3333
3334         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3335                              DSDB_SEARCH_SHOW_DELETED |
3336                              DSDB_SEARCH_SHOW_RECYCLED);
3337         if (ret != LDB_SUCCESS) {
3338                 talloc_free(tmp_ctx);
3339                 return ret;
3340         }
3341         if (res == NULL) {
3342                 talloc_free(tmp_ctx);
3343                 return LDB_ERR_OTHER;
3344         }
3345         if (res->count < 1) {
3346                 talloc_free(tmp_ctx);
3347                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3348         }
3349         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
3350         if (s == NULL) {
3351                 talloc_free(tmp_ctx);
3352                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3353         }
3354         *sid = *s;
3355         talloc_free(tmp_ctx);
3356         return LDB_SUCCESS;
3357 }
3358
3359 /*
3360   use a SID to find a DN
3361  */
3362 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
3363                         TALLOC_CTX *mem_ctx,
3364                         struct dom_sid *sid, struct ldb_dn **dn)
3365 {
3366         int ret;
3367         struct ldb_result *res;
3368         const char *attrs[] = { NULL };
3369         char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
3370
3371         if (!sid_str) {
3372                 return ldb_operr(ldb);
3373         }
3374
3375         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3376                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3377                           DSDB_SEARCH_SHOW_EXTENDED_DN |
3378                           DSDB_SEARCH_ONE_ONLY,
3379                           "objectSid=%s", sid_str);
3380         talloc_free(sid_str);
3381         if (ret != LDB_SUCCESS) {
3382                 return ret;
3383         }
3384
3385         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3386         talloc_free(res);
3387
3388         return LDB_SUCCESS;
3389 }
3390
3391 /*
3392   load a repsFromTo blob list for a given partition GUID
3393   attr must be "repsFrom" or "repsTo"
3394  */
3395 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3396                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
3397 {
3398         const char *attrs[] = { attr, NULL };
3399         struct ldb_result *res = NULL;
3400         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3401         unsigned int i;
3402         struct ldb_message_element *el;
3403         int ret;
3404
3405         *r = NULL;
3406         *count = 0;
3407
3408         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
3409         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3410                 /* partition hasn't been replicated yet */
3411                 return WERR_OK;
3412         }
3413         if (ret != LDB_SUCCESS) {
3414                 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
3415                 talloc_free(tmp_ctx);
3416                 return WERR_DS_DRA_INTERNAL_ERROR;
3417         }
3418
3419         /* satisfy clang */
3420         if (res == NULL) {
3421                 talloc_free(tmp_ctx);
3422                 return WERR_DS_DRA_INTERNAL_ERROR;
3423         }
3424         el = ldb_msg_find_element(res->msgs[0], attr);
3425         if (el == NULL) {
3426                 /* it's OK to be empty */
3427                 talloc_free(tmp_ctx);
3428                 return WERR_OK;
3429         }
3430
3431         *count = el->num_values;
3432         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
3433         if (*r == NULL) {
3434                 talloc_free(tmp_ctx);
3435                 return WERR_DS_DRA_INTERNAL_ERROR;
3436         }
3437
3438         for (i=0; i<(*count); i++) {
3439                 enum ndr_err_code ndr_err;
3440                 ndr_err = ndr_pull_struct_blob(&el->values[i],
3441                                                mem_ctx,
3442                                                &(*r)[i],
3443                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3444                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3445                         talloc_free(tmp_ctx);
3446                         return WERR_DS_DRA_INTERNAL_ERROR;
3447                 }
3448         }
3449
3450         talloc_free(tmp_ctx);
3451
3452         return WERR_OK;
3453 }
3454
3455 /*
3456   save the repsFromTo blob list for a given partition GUID
3457   attr must be "repsFrom" or "repsTo"
3458  */
3459 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3460                      const char *attr, struct repsFromToBlob *r, uint32_t count)
3461 {
3462         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3463         struct ldb_message *msg;
3464         struct ldb_message_element *el;
3465         unsigned int i;
3466
3467         msg = ldb_msg_new(tmp_ctx);
3468         msg->dn = dn;
3469         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
3470                 goto failed;
3471         }
3472
3473         el->values = talloc_array(msg, struct ldb_val, count);
3474         if (!el->values) {
3475                 goto failed;
3476         }
3477
3478         for (i=0; i<count; i++) {
3479                 struct ldb_val v;
3480                 enum ndr_err_code ndr_err;
3481
3482                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx,
3483                                                &r[i],
3484                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3485                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3486                         goto failed;
3487                 }
3488
3489                 el->num_values++;
3490                 el->values[i] = v;
3491         }
3492
3493         if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
3494                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
3495                 goto failed;
3496         }
3497
3498         talloc_free(tmp_ctx);
3499
3500         return WERR_OK;
3501
3502 failed:
3503         talloc_free(tmp_ctx);
3504         return WERR_DS_DRA_INTERNAL_ERROR;
3505 }
3506
3507
3508 /*
3509   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
3510   object for a partition
3511  */
3512 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
3513                                 uint64_t *uSN, uint64_t *urgent_uSN)
3514 {
3515         struct ldb_request *req;
3516         int ret;
3517         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3518         struct dsdb_control_current_partition *p_ctrl;
3519         struct ldb_result *res;
3520
3521         res = talloc_zero(tmp_ctx, struct ldb_result);
3522         if (!res) {
3523                 talloc_free(tmp_ctx);
3524                 return ldb_oom(ldb);
3525         }
3526
3527         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3528                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
3529                                    LDB_SCOPE_BASE,
3530                                    NULL, NULL,
3531                                    NULL,
3532                                    res, ldb_search_default_callback,
3533                                    NULL);
3534         if (ret != LDB_SUCCESS) {
3535                 talloc_free(tmp_ctx);
3536                 return ret;
3537         }
3538
3539         p_ctrl = talloc(req, struct dsdb_control_current_partition);
3540         if (p_ctrl == NULL) {
3541                 talloc_free(tmp_ctx);
3542                 return ldb_oom(ldb);
3543         }
3544         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
3545         p_ctrl->dn = dn;
3546
3547         ret = ldb_request_add_control(req,
3548                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
3549                                       false, p_ctrl);
3550         if (ret != LDB_SUCCESS) {
3551                 talloc_free(tmp_ctx);
3552                 return ret;
3553         }
3554
3555         /* Run the new request */
3556         ret = ldb_request(ldb, req);
3557
3558         if (ret == LDB_SUCCESS) {
3559                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3560         }
3561
3562         if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
3563                 /* it hasn't been created yet, which means
3564                    an implicit value of zero */
3565                 *uSN = 0;
3566                 talloc_free(tmp_ctx);
3567                 return LDB_SUCCESS;
3568         }
3569
3570         if (ret != LDB_SUCCESS) {
3571                 talloc_free(tmp_ctx);
3572                 return ret;
3573         }
3574
3575         if (res->count < 1) {
3576                 *uSN = 0;
3577                 if (urgent_uSN) {
3578                         *urgent_uSN = 0;
3579                 }
3580         } else {
3581                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
3582                 if (urgent_uSN) {
3583                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
3584                 }
3585         }
3586
3587         talloc_free(tmp_ctx);
3588
3589         return LDB_SUCCESS;
3590 }
3591
3592 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
3593                                                    const struct drsuapi_DsReplicaCursor2 *c2)
3594 {
3595         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3596 }
3597
3598 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
3599                                     const struct drsuapi_DsReplicaCursor *c2)
3600 {
3601         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3602 }
3603
3604 /*
3605  * Return the NTDS object for a GUID, confirming it is in the
3606  * configuration partition and a nTDSDSA object
3607  */
3608 int samdb_get_ntds_obj_by_guid(TALLOC_CTX *mem_ctx,
3609                                struct ldb_context *sam_ctx,
3610                                const struct GUID *objectGUID,
3611                                const char **attrs,
3612                                struct ldb_message **msg)
3613 {
3614         int ret;
3615         struct ldb_result *res;
3616         struct GUID_txt_buf guid_buf;
3617         char *guid_str = GUID_buf_string(objectGUID, &guid_buf);
3618         struct ldb_dn *config_dn = NULL;
3619
3620         config_dn = ldb_get_config_basedn(sam_ctx);
3621         if (config_dn == NULL) {
3622                 return ldb_operr(sam_ctx);
3623         }
3624
3625         ret = dsdb_search(sam_ctx,
3626                           mem_ctx,
3627                           &res,
3628                           config_dn,
3629                           LDB_SCOPE_SUBTREE,
3630                           attrs,
3631                           DSDB_SEARCH_ONE_ONLY,
3632                           "(&(objectGUID=%s)(objectClass=nTDSDSA))",
3633                           guid_str);
3634         if (ret != LDB_SUCCESS) {
3635                 return ret;
3636         }
3637         if (msg) {
3638                 *msg = talloc_steal(mem_ctx, res->msgs[0]);
3639         }
3640         TALLOC_FREE(res);
3641         return ret;
3642 }
3643
3644
3645 /*
3646   see if a computer identified by its objectGUID is a RODC
3647 */
3648 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
3649 {
3650         /* 1) find the DN for this servers NTDSDSA object
3651            2) search for the msDS-isRODC attribute
3652            3) if not present then not a RODC
3653            4) if present and TRUE then is a RODC
3654         */
3655         const char *attrs[] = { "msDS-isRODC", NULL };
3656         int ret;
3657         struct ldb_message *msg;
3658         TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
3659
3660         ret = samdb_get_ntds_obj_by_guid(tmp_ctx,
3661                                          sam_ctx,
3662                                          objectGUID,
3663                                          attrs, &msg);
3664
3665         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3666                 *is_rodc = false;
3667                 talloc_free(tmp_ctx);
3668                 return LDB_SUCCESS;
3669         }
3670
3671         if (ret != LDB_SUCCESS) {
3672                 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
3673                          GUID_string(tmp_ctx, objectGUID)));
3674                 *is_rodc = false;
3675                 talloc_free(tmp_ctx);
3676                 return ret;
3677         }
3678
3679         ret = ldb_msg_find_attr_as_bool(msg, "msDS-isRODC", 0);
3680         *is_rodc = (ret == 1);
3681
3682         talloc_free(tmp_ctx);
3683         return LDB_SUCCESS;
3684 }
3685
3686
3687 /*
3688   see if we are a RODC
3689 */
3690 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
3691 {
3692         const struct GUID *objectGUID;
3693         int ret;
3694         bool *cached;
3695
3696         /* see if we have a cached copy */
3697         cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
3698         if (cached) {
3699                 *am_rodc = *cached;
3700                 return LDB_SUCCESS;
3701         }
3702
3703         objectGUID = samdb_ntds_objectGUID(sam_ctx);
3704         if (!objectGUID) {
3705                 return ldb_operr(sam_ctx);
3706         }
3707
3708         ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
3709         if (ret != LDB_SUCCESS) {
3710                 return ret;
3711         }
3712
3713         cached = talloc(sam_ctx, bool);
3714         if (cached == NULL) {
3715                 return ldb_oom(sam_ctx);
3716         }
3717         *cached = *am_rodc;
3718
3719         ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
3720         if (ret != LDB_SUCCESS) {
3721                 talloc_free(cached);
3722                 return ldb_operr(sam_ctx);
3723         }
3724
3725         return LDB_SUCCESS;
3726 }
3727
3728 int samdb_dns_host_name(struct ldb_context *sam_ctx, const char **host_name)
3729 {
3730         const char *_host_name = NULL;
3731         const char *attrs[] = { "dnsHostName", NULL };
3732         TALLOC_CTX *tmp_ctx = NULL;
3733         int ret;
3734         struct ldb_result *res = NULL;
3735
3736         _host_name = (const char *)ldb_get_opaque(sam_ctx, "cache.dns_host_name");
3737         if (_host_name != NULL) {
3738                 *host_name = _host_name;
3739                 return LDB_SUCCESS;
3740         }
3741
3742         tmp_ctx = talloc_new(sam_ctx);
3743
3744         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, NULL, attrs, 0);
3745
3746         if (res == NULL || res->count != 1 || ret != LDB_SUCCESS) {
3747                 DEBUG(0, ("Failed to get rootDSE for dnsHostName: %s",
3748                           ldb_errstring(sam_ctx)));
3749                 TALLOC_FREE(tmp_ctx);
3750                 return ret;
3751         }
3752
3753         _host_name = ldb_msg_find_attr_as_string(res->msgs[0],
3754                                                  "dnsHostName",
3755                                                  NULL);
3756         if (_host_name == NULL) {
3757                 DEBUG(0, ("Failed to get dnsHostName from rootDSE"));
3758                 TALLOC_FREE(tmp_ctx);
3759                 return LDB_ERR_OPERATIONS_ERROR;
3760         }
3761         ret = ldb_set_opaque(sam_ctx, "cache.dns_host_name",
3762                              discard_const_p(char *, _host_name));
3763         if (ret != LDB_SUCCESS) {
3764                 TALLOC_FREE(tmp_ctx);
3765                 return ldb_operr(sam_ctx);
3766         }
3767
3768         *host_name = talloc_steal(sam_ctx, _host_name);
3769
3770         TALLOC_FREE(tmp_ctx);
3771         return LDB_SUCCESS;
3772 }
3773
3774 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3775 {
3776         TALLOC_CTX *tmp_ctx;
3777         bool *cached;
3778
3779         tmp_ctx = talloc_new(ldb);
3780         if (tmp_ctx == NULL) {
3781                 goto failed;
3782         }
3783
3784         cached = talloc(tmp_ctx, bool);
3785         if (!cached) {
3786                 goto failed;
3787         }
3788
3789         *cached = am_rodc;
3790         if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3791                 goto failed;
3792         }
3793
3794         talloc_steal(ldb, cached);
3795         talloc_free(tmp_ctx);
3796         return true;
3797
3798 failed:
3799         DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3800         talloc_free(tmp_ctx);
3801         return false;
3802 }
3803
3804
3805 /*
3806  * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3807  * flags are DS_NTDSSETTINGS_OPT_*
3808  */
3809 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3810                                         uint32_t *options)
3811 {
3812         int rc;
3813         TALLOC_CTX *tmp_ctx;
3814         struct ldb_result *res;
3815         struct ldb_dn *site_dn;
3816         const char *attrs[] = { "options", NULL };
3817
3818         tmp_ctx = talloc_new(ldb_ctx);
3819         if (tmp_ctx == NULL)
3820                 goto failed;
3821
3822         /* Retrieve the site dn for the ldb that we
3823          * have open.  This is our local site.
3824          */
3825         site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3826         if (site_dn == NULL)
3827                 goto failed;
3828
3829         /* Perform a one level (child) search from the local
3830          * site distinguided name.   We're looking for the
3831          * "options" attribute within the nTDSSiteSettings
3832          * object
3833          */
3834         rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3835                         LDB_SCOPE_ONELEVEL, attrs,
3836                         "objectClass=nTDSSiteSettings");
3837
3838         if (rc != LDB_SUCCESS || res->count != 1)
3839                 goto failed;
3840
3841         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3842
3843         talloc_free(tmp_ctx);
3844
3845         return LDB_SUCCESS;
3846
3847 failed:
3848         DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3849         talloc_free(tmp_ctx);
3850         return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
3851 }
3852
3853 /*
3854   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1
3855
3856   flags are DS_NTDS_OPTION_*
3857 */
3858 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3859 {
3860         TALLOC_CTX *tmp_ctx;
3861         const char *attrs[] = { "options", NULL };
3862         int ret;
3863         struct ldb_result *res;
3864
3865         tmp_ctx = talloc_new(ldb);
3866         if (tmp_ctx == NULL) {
3867                 goto failed;
3868         }
3869
3870         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3871         if (ret != LDB_SUCCESS) {
3872                 goto failed;
3873         }
3874
3875         if (res->count != 1) {
3876                 goto failed;
3877         }
3878
3879         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3880
3881         talloc_free(tmp_ctx);
3882
3883         return LDB_SUCCESS;
3884
3885 failed:
3886         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3887         talloc_free(tmp_ctx);
3888         return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3889 }
3890
3891 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3892 {
3893         const char *attrs[] = { "objectCategory", NULL };
3894         int ret;
3895         struct ldb_result *res;
3896
3897         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3898         if (ret != LDB_SUCCESS) {
3899                 goto failed;
3900         }
3901
3902         if (res->count != 1) {
3903                 goto failed;
3904         }
3905
3906         return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3907
3908 failed:
3909         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3910         return NULL;
3911 }
3912
3913 /*
3914  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3915  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3916  */
3917 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3918 {
3919         char **tokens, *ret;
3920         size_t i;
3921
3922         tokens = str_list_make(mem_ctx, cn, " -_");
3923         if (tokens == NULL || tokens[0] == NULL) {
3924                 return NULL;
3925         }
3926
3927         /* "tolower()" and "toupper()" should also work properly on 0x00 */
3928         tokens[0][0] = tolower(tokens[0][0]);
3929         for (i = 1; tokens[i] != NULL; i++)
3930                 tokens[i][0] = toupper(tokens[i][0]);
3931
3932         ret = talloc_strdup(mem_ctx, tokens[0]);
3933         for (i = 1; tokens[i] != NULL; i++)
3934                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3935
3936         talloc_free(tokens);
3937
3938         return ret;
3939 }
3940
3941 /*
3942  * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3943  */
3944 int dsdb_functional_level(struct ldb_context *ldb)
3945 {
3946         int *domainFunctionality =
3947                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3948         if (!domainFunctionality) {
3949                 /* this is expected during initial provision */
3950                 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3951                 return DS_DOMAIN_FUNCTION_2000;
3952         }
3953         return *domainFunctionality;
3954 }
3955
3956 /*
3957  * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3958  */
3959 int dsdb_forest_functional_level(struct ldb_context *ldb)
3960 {
3961         int *forestFunctionality =
3962                 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3963         if (!forestFunctionality) {
3964                 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3965                 return DS_DOMAIN_FUNCTION_2000;
3966         }
3967         return *forestFunctionality;
3968 }
3969
3970 /*
3971  * This detects and returns the DC functional level (DS_DOMAIN_FUNCTION_*)
3972  */
3973 int dsdb_dc_functional_level(struct ldb_context *ldb)
3974 {
3975         int *dcFunctionality =
3976                 talloc_get_type(ldb_get_opaque(ldb, "domainControllerFunctionality"), int);
3977         if (!dcFunctionality) {
3978                 /* this is expected during initial provision */
3979                 DEBUG(4,(__location__ ": WARNING: domainControllerFunctionality not setup\n"));
3980                 return DS_DOMAIN_FUNCTION_2008_R2;
3981         }
3982         return *dcFunctionality;
3983 }
3984
3985 /*
3986   set a GUID in an extended DN structure
3987  */
3988 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3989 {
3990         struct ldb_val v;
3991         NTSTATUS status;
3992         int ret;
3993
3994         status = GUID_to_ndr_blob(guid, dn, &v);
3995         if (!NT_STATUS_IS_OK(status)) {
3996                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3997         }
3998
3999         ret = ldb_dn_set_extended_component(dn, component_name, &v);
4000         data_blob_free(&v);
4001         return ret;
4002 }
4003
4004 /*
4005   return a GUID from a extended DN structure
4006  */
4007 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
4008 {
4009         const struct ldb_val *v;
4010
4011         v = ldb_dn_get_extended_component(dn, component_name);
4012         if (v == NULL) {
4013                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4014         }
4015
4016         return GUID_from_ndr_blob(v, guid);
4017 }
4018
4019 /*
4020   return a uint64_t from a extended DN structure
4021  */
4022 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
4023 {
4024         const struct ldb_val *v;
4025         int error = 0;
4026
4027         v = ldb_dn_get_extended_component(dn, component_name);
4028         if (v == NULL) {
4029                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4030         }
4031
4032         /* Just check we don't allow the caller to fill our stack */
4033         if (v->length >= 64) {
4034                 return NT_STATUS_INVALID_PARAMETER;
4035         } else {
4036                 char s[v->length+1];
4037                 memcpy(s, v->data, v->length);
4038                 s[v->length] = 0;
4039
4040                 *val = smb_strtoull(s, NULL, 0, &error, SMB_STR_STANDARD);
4041                 if (error != 0) {
4042                         return NT_STATUS_INVALID_PARAMETER;
4043                 }
4044         }
4045         return NT_STATUS_OK;
4046 }
4047
4048 /*
4049   return a NTTIME from a extended DN structure
4050  */
4051 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
4052 {
4053         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
4054 }
4055
4056 /*
4057   return a uint32_t from a extended DN structure
4058  */
4059 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
4060 {
4061         const struct ldb_val *v;
4062         int error = 0;
4063
4064         v = ldb_dn_get_extended_component(dn, component_name);
4065         if (v == NULL) {
4066                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4067         }
4068
4069         /* Just check we don't allow the caller to fill our stack */
4070         if (v->length >= 32) {
4071                 return NT_STATUS_INVALID_PARAMETER;
4072         } else {
4073                 char s[v->length + 1];
4074                 memcpy(s, v->data, v->length);
4075                 s[v->length] = 0;
4076                 *val = smb_strtoul(s, NULL, 0, &error, SMB_STR_STANDARD);
4077                 if (error != 0) {
4078                         return NT_STATUS_INVALID_PARAMETER;
4079                 }
4080         }
4081
4082         return NT_STATUS_OK;
4083 }
4084
4085 /*
4086   return a dom_sid from a extended DN structure
4087  */
4088 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
4089 {
4090         const struct ldb_val *sid_blob;
4091         enum ndr_err_code ndr_err;
4092
4093         sid_blob = ldb_dn_get_extended_component(dn, component_name);
4094         if (!sid_blob) {
4095                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4096         }
4097
4098         ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
4099                                                    (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
4100         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4101                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
4102                 return status;
4103         }
4104
4105         return NT_STATUS_OK;
4106 }
4107
4108
4109 /*
4110   return RMD_FLAGS directly from a ldb_dn
4111   returns 0 if not found
4112  */
4113 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
4114 {
4115         uint32_t rmd_flags = 0;
4116         NTSTATUS status = dsdb_get_extended_dn_uint32(dn, &rmd_flags,
4117                                                       "RMD_FLAGS");
4118         if (NT_STATUS_IS_OK(status)) {
4119                 return rmd_flags;
4120         }
4121         return 0;
4122 }
4123
4124 /*
4125   return RMD_FLAGS directly from a ldb_val for a DN
4126   returns 0 if RMD_FLAGS is not found
4127  */
4128 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
4129 {
4130         const char *p;
4131         uint32_t flags;
4132         char *end;
4133         int error = 0;
4134
4135         if (val->length < 13) {
4136                 return 0;
4137         }
4138         p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
4139         if (!p) {
4140                 return 0;
4141         }
4142         flags = smb_strtoul(p+11, &end, 10, &error, SMB_STR_STANDARD);
4143         if (!end || *end != '>' || error != 0) {
4144                 /* it must end in a > */
4145                 return 0;
4146         }
4147         return flags;
4148 }
4149
4150 /*
4151   return true if a ldb_val containing a DN in storage form is deleted
4152  */
4153 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
4154 {
4155         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
4156 }
4157
4158 /*
4159   return true if a ldb_val containing a DN in storage form is
4160   in the upgraded w2k3 linked attribute format
4161  */
4162 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
4163 {
4164         return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
4165 }
4166
4167 /*
4168   return a DN for a wellknown GUID
4169  */
4170 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
4171                       struct ldb_dn *nc_root, const char *wk_guid,
4172                       struct ldb_dn **wkguid_dn)
4173 {
4174         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4175         const char *attrs[] = { NULL };
4176         int ret;
4177         struct ldb_dn *dn;
4178         struct ldb_result *res = NULL;
4179
4180         /* construct the magic WKGUID DN */
4181         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
4182                             wk_guid, ldb_dn_get_linearized(nc_root));
4183         if (!wkguid_dn) {
4184                 talloc_free(tmp_ctx);
4185                 return ldb_operr(samdb);
4186         }
4187
4188         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
4189                              DSDB_SEARCH_SHOW_DELETED |
4190                              DSDB_SEARCH_SHOW_RECYCLED);
4191         if (ret != LDB_SUCCESS) {
4192                 talloc_free(tmp_ctx);
4193                 return ret;
4194         }
4195         /* fix clang warning */
4196         if (res == NULL){
4197                 talloc_free(tmp_ctx);
4198                 return LDB_ERR_OTHER;
4199         }
4200
4201         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
4202         talloc_free(tmp_ctx);
4203         return LDB_SUCCESS;
4204 }
4205
4206
4207 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
4208 {
4209         return ldb_dn_compare(*dn1, *dn2);
4210 }
4211
4212 /*
4213   find a NC root given a DN within the NC by reading the rootDSE namingContexts
4214  */
4215 static int dsdb_find_nc_root_string_based(struct ldb_context *samdb,
4216                                           TALLOC_CTX *mem_ctx,
4217                                           struct ldb_dn *dn,
4218                                           struct ldb_dn **nc_root)
4219 {
4220         const char *root_attrs[] = { "namingContexts", NULL };
4221         TALLOC_CTX *tmp_ctx;
4222         int ret;
4223         struct ldb_message_element *el;
4224         struct ldb_result *root_res;
4225         unsigned int i;
4226         struct ldb_dn **nc_dns;
4227
4228         tmp_ctx = talloc_new(samdb);
4229         if (tmp_ctx == NULL) {
4230                 return ldb_oom(samdb);
4231         }
4232
4233         ret = ldb_search(samdb, tmp_ctx, &root_res,
4234                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
4235         if (ret != LDB_SUCCESS || root_res->count == 0) {
4236                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
4237                 talloc_free(tmp_ctx);
4238                 return ret;
4239         }
4240
4241         el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
4242         if ((el == NULL) || (el->num_values < 3)) {
4243                 struct ldb_message *tmp_msg;
4244
4245                 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list.\n"));
4246
4247                 /* This generates a temporary list of NCs in order to let the
4248                  * provisioning work. */
4249                 tmp_msg = ldb_msg_new(tmp_ctx);
4250                 if (tmp_msg == NULL) {
4251                         talloc_free(tmp_ctx);
4252                         return ldb_oom(samdb);
4253                 }
4254                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4255                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
4256                 if (ret != LDB_SUCCESS) {
4257                         talloc_free(tmp_ctx);
4258                         return ret;
4259                 }
4260                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4261                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
4262                 if (ret != LDB_SUCCESS) {
4263                         talloc_free(tmp_ctx);
4264                         return ret;
4265                 }
4266                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4267                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
4268                 if (ret != LDB_SUCCESS) {
4269                         talloc_free(tmp_ctx);
4270                         return ret;
4271                 }
4272                 el = &tmp_msg->elements[0];
4273         }
4274
4275        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
4276        if (!nc_dns) {
4277                talloc_free(tmp_ctx);
4278                return ldb_oom(samdb);
4279        }
4280
4281        for (i=0; i<el->num_values; i++) {
4282                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
4283                if (nc_dns[i] == NULL) {
4284                        talloc_free(tmp_ctx);
4285                        return ldb_operr(samdb);
4286                }
4287        }
4288
4289        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
4290
4291        for (i=0; i<el->num_values; i++) {
4292                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
4293                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
4294                        talloc_free(tmp_ctx);
4295                        return LDB_SUCCESS;
4296                }
4297        }
4298
4299        talloc_free(tmp_ctx);
4300        return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4301 }
4302
4303 struct dsdb_get_partition_and_dn {
4304         TALLOC_CTX *mem_ctx;
4305         unsigned int count;
4306         struct ldb_dn *dn;
4307         struct ldb_dn *partition_dn;
4308         bool want_partition_dn;
4309 };
4310
4311 static int dsdb_get_partition_and_dn(struct ldb_request *req,
4312                                      struct ldb_reply *ares)
4313 {
4314         int ret;
4315         struct dsdb_get_partition_and_dn *context = req->context;
4316         struct ldb_control *partition_ctrl = NULL;
4317         struct dsdb_control_current_partition *partition = NULL;
4318
4319         if (!ares) {
4320                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
4321         }
4322         if (ares->error != LDB_SUCCESS
4323             && ares->error != LDB_ERR_NO_SUCH_OBJECT) {
4324                 return ldb_request_done(req, ares->error);
4325         }
4326
4327         switch (ares->type) {
4328         case LDB_REPLY_ENTRY:
4329                 if (context->count != 0) {
4330                         return ldb_request_done(req,
4331                                                 LDB_ERR_CONSTRAINT_VIOLATION);
4332                 }
4333                 context->count++;
4334
4335                 context->dn = talloc_steal(context->mem_ctx,
4336                                            ares->message->dn);
4337                 break;
4338
4339         case LDB_REPLY_REFERRAL:
4340                 talloc_free(ares);
4341                 return ldb_request_done(req, LDB_SUCCESS);
4342
4343         case LDB_REPLY_DONE:
4344                 partition_ctrl
4345                         = ldb_reply_get_control(ares,
4346                                                 DSDB_CONTROL_CURRENT_PARTITION_OID);
4347                 if (!context->want_partition_dn ||
4348                         partition_ctrl == NULL) {
4349                         ret = ares->error;
4350                         talloc_free(ares);
4351
4352                         return ldb_request_done(req, ret);
4353                 }
4354
4355                 partition
4356                         = talloc_get_type_abort(partition_ctrl->data,
4357                                                 struct dsdb_control_current_partition);
4358                 context->partition_dn
4359                         = ldb_dn_copy(context->mem_ctx, partition->dn);
4360                 if (context->partition_dn == NULL) {
4361                         return ldb_request_done(req,
4362                                                 LDB_ERR_OPERATIONS_ERROR);
4363                 }
4364
4365                 ret = ares->error;
4366                 talloc_free(ares);
4367
4368                 return ldb_request_done(req, ret);
4369         }
4370
4371         talloc_free(ares);
4372         return LDB_SUCCESS;
4373 }
4374
4375 /*
4376   find a NC root given a DN within the NC
4377  */
4378 int dsdb_normalise_dn_and_find_nc_root(struct ldb_context *samdb,
4379                                        TALLOC_CTX *mem_ctx,
4380                                        struct ldb_dn *dn,
4381                                        struct ldb_dn **normalised_dn,
4382                                        struct ldb_dn **nc_root)
4383 {
4384         TALLOC_CTX *tmp_ctx;
4385         int ret;
4386         struct ldb_request *req;
4387         struct ldb_result *res;
4388         struct ldb_dn *search_dn = dn;
4389         static const char * attrs[] = { NULL };
4390         bool has_extended = ldb_dn_has_extended(dn);
4391         bool has_normal_components = ldb_dn_get_comp_num(dn) >= 1;
4392         struct dsdb_get_partition_and_dn context = {
4393                 .mem_ctx = mem_ctx,
4394                 .want_partition_dn = nc_root != NULL
4395         };
4396
4397         if (!has_extended && !has_normal_components) {
4398                 return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT,
4399                                  "Request for NC root for rootDSE (\"\") deined.");
4400         }
4401
4402         tmp_ctx = talloc_new(samdb);
4403         if (tmp_ctx == NULL) {
4404                 return ldb_oom(samdb);
4405         }
4406
4407         res = talloc_zero(tmp_ctx, struct ldb_result);
4408         if (res == NULL) {
4409                 talloc_free(tmp_ctx);
4410                 return ldb_oom(samdb);
4411         }
4412
4413         if (has_extended && has_normal_components) {
4414                 bool minimise_ok;
4415                 search_dn = ldb_dn_copy(tmp_ctx, dn);
4416                 if (search_dn == NULL) {
4417                         talloc_free(tmp_ctx);
4418                         return ldb_oom(samdb);
4419                 }
4420                 minimise_ok = ldb_dn_minimise(search_dn);
4421                 if (!minimise_ok) {
4422                         talloc_free(tmp_ctx);
4423                         return ldb_operr(samdb);
4424                 }
4425         }
4426
4427         ret = ldb_build_search_req(&req, samdb, tmp_ctx,
4428                                    search_dn,
4429                                    LDB_SCOPE_BASE,
4430                                    NULL,
4431                                    attrs,
4432                                    NULL,
4433                                    &context,
4434                                    dsdb_get_partition_and_dn,
4435                                    NULL);
4436         if (ret != LDB_SUCCESS) {
4437                 talloc_free(tmp_ctx);
4438                 return ret;
4439         }
4440
4441         ret = ldb_request_add_control(req,
4442                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
4443                                       false, NULL);
4444         if (ret != LDB_SUCCESS) {
4445                 talloc_free(tmp_ctx);
4446                 return ret;
4447         }
4448
4449         ret = dsdb_request_add_controls(req,
4450                                         DSDB_SEARCH_SHOW_RECYCLED|
4451                                         DSDB_SEARCH_SHOW_DELETED|
4452                                         DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT);
4453         if (ret != LDB_SUCCESS) {
4454                 talloc_free(tmp_ctx);
4455                 return ret;
4456         }
4457
4458         ret = ldb_request(samdb, req);
4459         if (ret == LDB_SUCCESS) {
4460                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4461         }
4462
4463         /*
4464          * This could be a new DN, not in the DB, which is OK.  If we
4465          * don't need the normalised DN, we can continue.
4466          *
4467          * We may be told the partition it would be in in the search
4468          * reply control, or if not we can do a string-based match.
4469          */
4470
4471         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
4472                 if (normalised_dn != NULL) {
4473                         talloc_free(tmp_ctx);
4474                         return ret;
4475                 }
4476                 ret = LDB_SUCCESS;
4477                 ldb_reset_err_string(samdb);
4478         } else if (ret != LDB_SUCCESS) {
4479                 talloc_free(tmp_ctx);
4480                 return ret;
4481         }
4482
4483         if (normalised_dn != NULL) {
4484                 if (context.count != 1) {
4485                         /* No results */
4486                         ldb_asprintf_errstring(samdb,
4487                                                "Request for NC root for %s failed to return any results.",
4488                                                ldb_dn_get_linearized(dn));
4489                         return LDB_ERR_NO_SUCH_OBJECT;
4490                 }
4491                 *normalised_dn = context.dn;
4492         }
4493
4494         /*
4495          * If the user did not need to find the nc_root,
4496          * we are done
4497          */
4498         if (nc_root == NULL) {
4499                 talloc_free(tmp_ctx);
4500                 return ret;
4501         }
4502
4503         /*
4504          * When we are working locally, both for the case were
4505          * we find the DN, and the case where we fail, we get
4506          * back via controls the partition it was in or should
4507          * have been in, to return to the client
4508          */
4509         if (context.partition_dn != NULL) {
4510                 (*nc_root) = context.partition_dn;
4511
4512                 talloc_free(tmp_ctx);
4513                 return ret;
4514         }
4515
4516         /*
4517          * This is a remote operation, which is a little harder as we
4518          * have a work out the nc_root from the list of NCs. If we did
4519          * at least resolve the DN to a string, get that now, it makes
4520          * the string-based match below possible for a GUID-based
4521          * input over remote LDAP.
4522          */
4523         if (context.dn) {
4524                 dn = context.dn;
4525         } else if (has_extended && !has_normal_components) {
4526                 ldb_asprintf_errstring(samdb,
4527                                        "Cannot determine NC root "
4528                                        "for a not-found bare extended DN %s.",
4529                                        ldb_dn_get_extended_linearized(tmp_ctx, dn, 1));
4530                 talloc_free(tmp_ctx);
4531                 return LDB_ERR_NO_SUCH_OBJECT;
4532         }
4533
4534         /*
4535          * Either we are working aginast a remote LDAP
4536          * server or the object doesn't exist locally.
4537          *
4538          * This means any GUID that was present in the DN
4539          * therefore could not be evaluated, so do a
4540          * string-based match instead.
4541          */
4542         talloc_free(tmp_ctx);
4543         return dsdb_find_nc_root_string_based(samdb,
4544                                               mem_ctx,
4545                                               dn,
4546                                               nc_root);
4547 }
4548
4549 /*
4550   find a NC root given a DN within the NC
4551  */
4552 int dsdb_find_nc_root(struct ldb_context *samdb,
4553                       TALLOC_CTX *mem_ctx,
4554                       struct ldb_dn *dn,
4555                       struct ldb_dn **nc_root)
4556 {
4557         return dsdb_normalise_dn_and_find_nc_root(samdb,
4558                                                   mem_ctx,
4559                                                   dn,
4560                                                   NULL,
4561                                                   nc_root);
4562 }
4563
4564 /*
4565   find the deleted objects DN for any object, by looking for the NC
4566   root, then looking up the wellknown GUID
4567  */
4568 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
4569                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
4570                                 struct ldb_dn **do_dn)
4571 {
4572         struct ldb_dn *nc_root;
4573         int ret;
4574
4575         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
4576         if (ret != LDB_SUCCESS) {
4577                 return ret;
4578         }
4579
4580         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
4581         talloc_free(nc_root);
4582         return ret;
4583 }
4584
4585 /*
4586   return the tombstoneLifetime, in days
4587  */
4588 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
4589 {
4590         struct ldb_dn *dn;
4591         dn = ldb_get_config_basedn(ldb);
4592         if (!dn) {
4593                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4594         }
4595         dn = ldb_dn_copy(ldb, dn);
4596         if (!dn) {
4597                 return ldb_operr(ldb);
4598         }
4599         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
4600          be a wellknown GUID for this */
4601         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
4602                 talloc_free(dn);
4603                 return ldb_operr(ldb);
4604         }
4605
4606         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
4607         talloc_free(dn);
4608         return LDB_SUCCESS;
4609 }
4610
4611 /*
4612   compare a ldb_val to a string case insensitively
4613  */
4614 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
4615 {
4616         size_t len = strlen(s);
4617         int ret;
4618         if (len > v->length) return 1;
4619         ret = strncasecmp(s, (const char *)v->data, v->length);
4620         if (ret != 0) return ret;
4621         if (v->length > len && v->data[len] != 0) {
4622                 return -1;
4623         }
4624         return 0;
4625 }
4626
4627
4628 /*
4629   load the UDV for a partition in v2 format
4630   The list is returned sorted, and with our local cursor added
4631  */
4632 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4633                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
4634 {
4635         static const char *attrs[] = { "replUpToDateVector", NULL };
4636         struct ldb_result *r = NULL;
4637         const struct ldb_val *ouv_value;
4638         unsigned int i;
4639         int ret;
4640         uint64_t highest_usn = 0;
4641         const struct GUID *our_invocation_id;
4642         static const struct timeval tv1970;
4643         NTTIME nt1970 = timeval_to_nttime(&tv1970);
4644
4645         ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
4646         if (ret != LDB_SUCCESS) {
4647                 return ret;
4648         }
4649         /* fix clang warning */
4650         if (r == NULL) {
4651                 return LDB_ERR_OTHER;
4652         }
4653         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
4654         if (ouv_value) {
4655                 enum ndr_err_code ndr_err;
4656                 struct replUpToDateVectorBlob ouv;
4657
4658                 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
4659                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
4660                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4661                         talloc_free(r);
4662                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4663                 }
4664                 if (ouv.version != 2) {
4665                         /* we always store as version 2, and
4666                          * replUpToDateVector is not replicated
4667                          */
4668                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4669                 }
4670
4671                 *count = ouv.ctr.ctr2.count;
4672                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
4673         } else {
4674                 *count = 0;
4675                 *cursors = NULL;
4676         }
4677
4678         talloc_free(r);
4679
4680         our_invocation_id = samdb_ntds_invocation_id(samdb);
4681         if (!our_invocation_id) {
4682                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
4683                 talloc_free(*cursors);
4684                 return ldb_operr(samdb);
4685         }
4686
4687         ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
4688         if (ret != LDB_SUCCESS) {
4689                 /* nothing to add - this can happen after a vampire */
4690                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4691                 return LDB_SUCCESS;
4692         }
4693
4694         for (i=0; i<*count; i++) {
4695                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
4696                         (*cursors)[i].highest_usn = highest_usn;
4697                         (*cursors)[i].last_sync_success = nt1970;
4698                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4699                         return LDB_SUCCESS;
4700                 }
4701         }
4702
4703         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
4704         if (! *cursors) {
4705                 return ldb_oom(samdb);
4706         }
4707
4708         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
4709         (*cursors)[*count].highest_usn = highest_usn;
4710         (*cursors)[*count].last_sync_success = nt1970;
4711         (*count)++;
4712
4713         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4714
4715         return LDB_SUCCESS;
4716 }
4717
4718 /*
4719   load the UDV for a partition in version 1 format
4720   The list is returned sorted, and with our local cursor added
4721  */
4722 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4723                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
4724 {
4725         struct drsuapi_DsReplicaCursor2 *v2 = NULL;
4726         uint32_t i;
4727         int ret;
4728
4729         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
4730         if (ret != LDB_SUCCESS) {
4731                 return ret;
4732         }
4733
4734         if (*count == 0) {
4735                 talloc_free(v2);
4736                 *cursors = NULL;
4737                 return LDB_SUCCESS;
4738         }
4739
4740         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
4741         if (*cursors == NULL) {
4742                 talloc_free(v2);
4743                 return ldb_oom(samdb);
4744         }
4745
4746         for (i=0; i<*count; i++) {
4747                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
4748                 (*cursors)[i].highest_usn = v2[i].highest_usn;
4749         }
4750         talloc_free(v2);
4751         return LDB_SUCCESS;
4752 }
4753
4754 /*
4755   add a set of controls to a ldb_request structure based on a set of
4756   flags. See util.h for a list of available flags
4757  */
4758 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
4759 {
4760         int ret;
4761         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
4762                 struct ldb_search_options_control *options;
4763                 /* Using the phantom root control allows us to search all partitions */
4764                 options = talloc(req, struct ldb_search_options_control);
4765                 if (options == NULL) {
4766                         return LDB_ERR_OPERATIONS_ERROR;
4767                 }
4768                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
4769
4770                 ret = ldb_request_add_control(req,
4771                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
4772                                               true, options);
4773                 if (ret != LDB_SUCCESS) {
4774                         return ret;
4775                 }
4776         }
4777
4778         if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
4779                 ret = ldb_request_add_control(req,
4780                                               DSDB_CONTROL_NO_GLOBAL_CATALOG,
4781                                               false, NULL);
4782                 if (ret != LDB_SUCCESS) {
4783                         return ret;
4784                 }
4785         }
4786
4787         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
4788                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
4789                 if (ret != LDB_SUCCESS) {
4790                         return ret;
4791                 }
4792         }
4793
4794         if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
4795                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
4796                 if (ret != LDB_SUCCESS) {
4797                         return ret;
4798                 }
4799         }
4800
4801         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
4802                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
4803                 if (ret != LDB_SUCCESS) {
4804                         return ret;
4805                 }
4806         }
4807
4808         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
4809                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
4810                 if (!extended_ctrl) {
4811                         return LDB_ERR_OPERATIONS_ERROR;
4812                 }
4813                 extended_ctrl->type = 1;
4814
4815                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
4816                 if (ret != LDB_SUCCESS) {
4817                         return ret;
4818                 }
4819         }
4820
4821         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
4822                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
4823                 if (ret != LDB_SUCCESS) {
4824                         return ret;
4825                 }
4826         }
4827
4828         if (dsdb_flags & DSDB_MODIFY_RELAX) {
4829                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
4830                 if (ret != LDB_SUCCESS) {
4831                         return ret;
4832                 }
4833         }
4834
4835         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
4836                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
4837                 if (ret != LDB_SUCCESS) {
4838                         return ret;
4839                 }
4840         }
4841
4842         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
4843                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
4844                 if (ret != LDB_SUCCESS) {
4845                         return ret;
4846                 }
4847         }
4848
4849         if (dsdb_flags & DSDB_TREE_DELETE) {
4850                 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
4851                 if (ret != LDB_SUCCESS) {
4852                         return ret;
4853                 }
4854         }
4855
4856         if (dsdb_flags & DSDB_PROVISION) {
4857                 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
4858                 if (ret != LDB_SUCCESS) {
4859                         return ret;
4860                 }
4861         }
4862
4863         /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
4864         if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
4865                 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
4866                 if (ret != LDB_SUCCESS) {
4867                         return ret;
4868                 }
4869         }
4870
4871         if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
4872                 /*
4873                  * This must not be critical, as it will only be
4874                  * handled (and need to be handled) if the other
4875                  * attributes in the request bring password_hash into
4876                  * action
4877                  */
4878                 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
4879                 if (ret != LDB_SUCCESS) {
4880                         return ret;
4881                 }
4882         }
4883
4884         if (dsdb_flags & DSDB_REPLMD_VANISH_LINKS) {
4885                 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLMD_VANISH_LINKS, true, NULL);
4886                 if (ret != LDB_SUCCESS) {
4887                         return ret;
4888                 }
4889         }
4890
4891         if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
4892                 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
4893                 if (ret != LDB_SUCCESS) {
4894                         return ret;
4895                 }
4896         }
4897
4898         if (dsdb_flags & DSDB_FLAG_REPLICATED_UPDATE) {
4899                 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
4900                 if (ret != LDB_SUCCESS) {
4901                         return ret;
4902                 }
4903         }
4904
4905         if (dsdb_flags & DSDB_FLAG_FORCE_ALLOW_VALIDATED_DNS_HOSTNAME_SPN_WRITE) {
4906                 ret = ldb_request_add_control(req, DSDB_CONTROL_FORCE_ALLOW_VALIDATED_DNS_HOSTNAME_SPN_WRITE_OID, true, NULL);
4907                 if (ret != LDB_SUCCESS) {
4908                         return ret;
4909                 }
4910         }
4911
4912         if (dsdb_flags & DSDB_MARK_REQ_UNTRUSTED) {
4913                 ldb_req_mark_untrusted(req);
4914         }
4915
4916         return LDB_SUCCESS;
4917 }
4918
4919 /*
4920    returns true if a control with the specified "oid" exists
4921 */
4922 bool dsdb_request_has_control(struct ldb_request *req, const char *oid)
4923 {
4924         return (ldb_request_get_control(req, oid) != NULL);
4925 }
4926
4927 /*
4928   an add with a set of controls
4929 */
4930 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
4931              uint32_t dsdb_flags)
4932 {
4933         struct ldb_request *req;
4934         int ret;
4935
4936         ret = ldb_build_add_req(&req, ldb, ldb,
4937                                 message,
4938                                 NULL,
4939                                 NULL,
4940                                 ldb_op_default_callback,
4941                                 NULL);
4942
4943         if (ret != LDB_SUCCESS) return ret;
4944
4945         ret = dsdb_request_add_controls(req, dsdb_flags);
4946         if (ret != LDB_SUCCESS) {
4947                 talloc_free(req);
4948                 return ret;
4949         }
4950
4951         ret = dsdb_autotransaction_request(ldb, req);
4952
4953         talloc_free(req);
4954         return ret;
4955 }
4956
4957 /*
4958   a modify with a set of controls
4959 */
4960 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
4961                 uint32_t dsdb_flags)
4962 {
4963         struct ldb_request *req;
4964         int ret;
4965
4966         ret = ldb_build_mod_req(&req, ldb, ldb,
4967                                 message,
4968                                 NULL,
4969                                 NULL,
4970                                 ldb_op_default_callback,
4971                                 NULL);
4972
4973         if (ret != LDB_SUCCESS) return ret;
4974
4975         ret = dsdb_request_add_controls(req, dsdb_flags);
4976         if (ret != LDB_SUCCESS) {
4977                 talloc_free(req);
4978                 return ret;
4979         }
4980
4981         ret = dsdb_autotransaction_request(ldb, req);
4982
4983         talloc_free(req);
4984         return ret;
4985 }
4986
4987 /*
4988   a delete with a set of flags
4989 */
4990 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
4991                 uint32_t dsdb_flags)
4992 {
4993         struct ldb_request *req;
4994         int ret;
4995
4996         ret = ldb_build_del_req(&req, ldb, ldb,
4997                                 dn,
4998                                 NULL,
4999                                 NULL,
5000                                 ldb_op_default_callback,
5001                                 NULL);
5002
5003         if (ret != LDB_SUCCESS) return ret;
5004
5005         ret = dsdb_request_add_controls(req, dsdb_flags);
5006         if (ret != LDB_SUCCESS) {
5007                 talloc_free(req);
5008                 return ret;
5009         }
5010
5011         ret = dsdb_autotransaction_request(ldb, req);
5012
5013         talloc_free(req);
5014         return ret;
5015 }
5016
5017 /*
5018   like dsdb_modify() but set all the element flags to
5019   LDB_FLAG_MOD_REPLACE
5020  */
5021 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
5022 {
5023         unsigned int i;
5024
5025         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5026         for (i=0;i<msg->num_elements;i++) {
5027                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5028         }
5029
5030         return dsdb_modify(ldb, msg, dsdb_flags);
5031 }
5032
5033
5034 /*
5035   search for attrs on one DN, allowing for dsdb_flags controls
5036  */
5037 int dsdb_search_dn(struct ldb_context *ldb,
5038                    TALLOC_CTX *mem_ctx,
5039                    struct ldb_result **_result,
5040                    struct ldb_dn *basedn,
5041                    const char * const *attrs,
5042                    uint32_t dsdb_flags)
5043 {
5044         int ret;
5045         struct ldb_request *req;
5046         struct ldb_result *res;
5047
5048         res = talloc_zero(mem_ctx, struct ldb_result);
5049         if (!res) {
5050                 return ldb_oom(ldb);
5051         }
5052
5053         ret = ldb_build_search_req(&req, ldb, res,
5054                                    basedn,
5055                                    LDB_SCOPE_BASE,
5056                                    NULL,
5057                                    attrs,
5058                                    NULL,
5059                                    res,
5060                                    ldb_search_default_callback,
5061                                    NULL);
5062         if (ret != LDB_SUCCESS) {
5063                 talloc_free(res);
5064                 return ret;
5065         }
5066
5067         ret = dsdb_request_add_controls(req, dsdb_flags);
5068         if (ret != LDB_SUCCESS) {
5069                 talloc_free(res);
5070                 return ret;
5071         }
5072
5073         ret = ldb_request(ldb, req);
5074         if (ret == LDB_SUCCESS) {
5075                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
5076         }
5077
5078         talloc_free(req);
5079         if (ret != LDB_SUCCESS) {
5080                 talloc_free(res);
5081                 return ret;
5082         }
5083
5084         *_result = res;
5085         return LDB_SUCCESS;
5086 }
5087
5088 /*
5089   search for attrs on one DN, by the GUID of the DN, allowing for
5090   dsdb_flags controls
5091  */
5092 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
5093                            TALLOC_CTX *mem_ctx,
5094                            struct ldb_result **_result,
5095                            const struct GUID *guid,
5096                            const char * const *attrs,
5097                            uint32_t dsdb_flags)
5098 {
5099         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5100         struct ldb_dn *dn;
5101         int ret;
5102
5103         dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
5104         if (dn == NULL) {
5105                 talloc_free(tmp_ctx);
5106                 return ldb_oom(ldb);
5107         }
5108
5109         ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
5110         talloc_free(tmp_ctx);
5111         return ret;
5112 }
5113
5114 /*
5115   general search with dsdb_flags for controls
5116  */
5117 int dsdb_search(struct ldb_context *ldb,
5118                 TALLOC_CTX *mem_ctx,
5119                 struct ldb_result **_result,
5120                 struct ldb_dn *basedn,
5121                 enum ldb_scope scope,
5122                 const char * const *attrs,
5123                 uint32_t dsdb_flags,
5124                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
5125 {
5126         int ret;
5127         struct ldb_request *req;
5128         struct ldb_result *res;
5129         va_list ap;
5130         char *expression = NULL;
5131         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5132
5133         /* cross-partitions searches with a basedn break multi-domain support */
5134         SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
5135
5136         res = talloc_zero(tmp_ctx, struct ldb_result);
5137         if (!res) {
5138                 talloc_free(tmp_ctx);
5139                 return ldb_oom(ldb);
5140         }
5141
5142         if (exp_fmt) {
5143                 va_start(ap, exp_fmt);
5144                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
5145                 va_end(ap);
5146
5147                 if (!expression) {
5148                         talloc_free(tmp_ctx);
5149                         return ldb_oom(ldb);
5150                 }
5151         }
5152
5153         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
5154                                    basedn,
5155                                    scope,
5156                                    expression,
5157                                    attrs,
5158                                    NULL,
5159                                    res,
5160                                    ldb_search_default_callback,
5161                                    NULL);
5162         if (ret != LDB_SUCCESS) {
5163                 talloc_free(tmp_ctx);
5164                 return ret;
5165         }
5166
5167         ret = dsdb_request_add_controls(req, dsdb_flags);
5168         if (ret != LDB_SUCCESS) {
5169                 talloc_free(tmp_ctx);
5170                 ldb_reset_err_string(ldb);
5171                 return ret;
5172         }
5173
5174         ret = ldb_request(ldb, req);
5175         if (ret == LDB_SUCCESS) {
5176                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
5177         }
5178
5179         if (ret != LDB_SUCCESS) {
5180                 talloc_free(tmp_ctx);
5181                 return ret;
5182         }
5183
5184         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
5185                 if (res->count == 0) {
5186                         talloc_free(tmp_ctx);
5187                         ldb_reset_err_string(ldb);
5188                         return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
5189                 }
5190                 if (res->count != 1) {
5191                         talloc_free(tmp_ctx);
5192                         ldb_reset_err_string(ldb);
5193                         return LDB_ERR_CONSTRAINT_VIOLATION;
5194                 }
5195         }
5196
5197         *_result = talloc_steal(mem_ctx, res);
5198         talloc_free(tmp_ctx);
5199
5200         return LDB_SUCCESS;
5201 }
5202
5203
5204 /*
5205   general search with dsdb_flags for controls
5206   returns exactly 1 record or an error
5207  */
5208 int dsdb_search_one(struct ldb_context *ldb,
5209                     TALLOC_CTX *mem_ctx,
5210                     struct ldb_message **msg,
5211                     struct ldb_dn *basedn,
5212                     enum ldb_scope scope,
5213                     const char * const *attrs,
5214                     uint32_t dsdb_flags,
5215                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
5216 {
5217         int ret;
5218         struct ldb_result *res;
5219         va_list ap;
5220         char *expression = NULL;
5221         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
5222
5223         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
5224
5225         res = talloc_zero(tmp_ctx, struct ldb_result);
5226         if (!res) {
5227                 talloc_free(tmp_ctx);
5228                 return ldb_oom(ldb);
5229         }
5230
5231         if (exp_fmt) {
5232                 va_start(ap, exp_fmt);
5233                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
5234                 va_end(ap);
5235
5236                 if (!expression) {
5237                         talloc_free(tmp_ctx);
5238                         return ldb_oom(ldb);
5239                 }
5240                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
5241                                   dsdb_flags, "%s", expression);
5242         } else {
5243                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
5244                                   dsdb_flags, NULL);
5245         }
5246
5247         if (ret != LDB_SUCCESS) {
5248                 talloc_free(tmp_ctx);
5249                 return ret;
5250         }
5251
5252         *msg = talloc_steal(mem_ctx, res->msgs[0]);
5253         talloc_free(tmp_ctx);
5254
5255         return LDB_SUCCESS;
5256 }
5257
5258 /* returns back the forest DNS name */
5259 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
5260 {
5261         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
5262                                                           ldb_get_root_basedn(ldb));
5263         char *p;
5264
5265         if (forest_name == NULL) {
5266                 return NULL;
5267         }
5268
5269         p = strchr(forest_name, '/');
5270         if (p) {
5271                 *p = '\0';
5272         }
5273
5274         return forest_name;
5275 }
5276
5277 /* returns back the default domain DNS name */
5278 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
5279 {
5280         const char *domain_name = ldb_dn_canonical_string(mem_ctx,
5281                                                           ldb_get_default_basedn(ldb));
5282         char *p;
5283
5284         if (domain_name == NULL) {
5285                 return NULL;
5286         }
5287
5288         p = strchr(domain_name, '/');
5289         if (p) {
5290                 *p = '\0';
5291         }
5292
5293         return domain_name;
5294 }
5295
5296 /*
5297    validate that an DSA GUID belongs to the specified user sid.
5298    The user SID must be a domain controller account (either RODC or
5299    RWDC)
5300  */
5301 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
5302                            const struct GUID *dsa_guid,
5303                            const struct dom_sid *sid)
5304 {
5305         /* strategy:
5306             - find DN of record with the DSA GUID in the
5307               configuration partition (objectGUID)
5308             - remove "NTDS Settings" component from DN
5309             - do a base search on that DN for serverReference with
5310               extended-dn enabled
5311             - extract objectSid from resulting serverReference
5312               attribute
5313             - check this sid matches the sid argument
5314         */
5315         struct ldb_dn *config_dn;
5316         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5317         struct ldb_message *msg;
5318         const char *attrs1[] = { NULL };
5319         const char *attrs2[] = { "serverReference", NULL };
5320         int ret;
5321         struct ldb_dn *dn, *account_dn;
5322         struct dom_sid sid2;
5323         NTSTATUS status;
5324
5325         config_dn = ldb_get_config_basedn(ldb);
5326
5327         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
5328                               attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
5329         if (ret != LDB_SUCCESS) {
5330                 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
5331                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
5332                 talloc_free(tmp_ctx);
5333                 return ldb_operr(ldb);
5334         }
5335         dn = msg->dn;
5336
5337         if (!ldb_dn_remove_child_components(dn, 1)) {
5338                 talloc_free(tmp_ctx);
5339                 return ldb_operr(ldb);
5340         }
5341
5342         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
5343                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
5344                               "(objectClass=server)");
5345         if (ret != LDB_SUCCESS) {
5346                 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
5347                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
5348                 talloc_free(tmp_ctx);
5349                 return ldb_operr(ldb);
5350         }
5351
5352         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
5353         if (account_dn == NULL) {
5354                 DEBUG(1,(__location__ ": Failed to find account dn "
5355                          "(serverReference) for %s, parent of DSA with "
5356                          "objectGUID %s, sid %s\n",
5357                          ldb_dn_get_linearized(msg->dn),
5358                          GUID_string(tmp_ctx, dsa_guid),
5359                          dom_sid_string(tmp_ctx, sid)));
5360                 talloc_free(tmp_ctx);
5361                 return ldb_operr(ldb);
5362         }
5363
5364         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
5365         if (!NT_STATUS_IS_OK(status)) {
5366                 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
5367                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
5368                 talloc_free(tmp_ctx);
5369                 return ldb_operr(ldb);
5370         }
5371
5372         if (!dom_sid_equal(sid, &sid2)) {
5373                 /* someone is trying to spoof another account */
5374                 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
5375                          GUID_string(tmp_ctx, dsa_guid),
5376                          dom_sid_string(tmp_ctx, sid),
5377                          dom_sid_string(tmp_ctx, &sid2)));
5378                 talloc_free(tmp_ctx);
5379                 return ldb_operr(ldb);
5380         }
5381
5382         talloc_free(tmp_ctx);
5383         return LDB_SUCCESS;
5384 }
5385
5386 static const char * const secret_attributes[] = {
5387         DSDB_SECRET_ATTRIBUTES,
5388         NULL
5389 };
5390
5391 /*
5392   check if the attribute belongs to the RODC filtered attribute set
5393   Note that attributes that are in the filtered attribute set are the
5394   ones that _are_ always sent to a RODC
5395 */
5396 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
5397 {
5398         /* they never get secret attributes */
5399         if (ldb_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
5400                 return false;
5401         }
5402
5403         /* they do get non-secret critical attributes */
5404         if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
5405                 return true;
5406         }
5407
5408         /* they do get non-secret attributes marked as being in the FAS  */
5409         if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
5410                 return true;
5411         }
5412
5413         /* other attributes are denied */
5414         return false;
5415 }
5416
5417 /* return fsmo role dn and role owner dn for a particular role*/
5418 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
5419                                struct ldb_context *ldb,
5420                                uint32_t role,
5421                                struct ldb_dn **fsmo_role_dn,
5422                                struct ldb_dn **role_owner_dn)
5423 {
5424         int ret;
5425         switch (role) {
5426         case DREPL_NAMING_MASTER:
5427                 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
5428                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5429                 if (ret != LDB_SUCCESS) {
5430                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
5431                                  ldb_errstring(ldb)));
5432                         talloc_free(tmp_ctx);
5433                         return WERR_DS_DRA_INTERNAL_ERROR;
5434                 }
5435                 break;
5436         case DREPL_INFRASTRUCTURE_MASTER:
5437                 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
5438                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5439                 if (ret != LDB_SUCCESS) {
5440                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5441                                  ldb_errstring(ldb)));
5442                         talloc_free(tmp_ctx);
5443                         return WERR_DS_DRA_INTERNAL_ERROR;
5444                 }
5445                 break;
5446         case DREPL_RID_MASTER:
5447                 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
5448                 if (ret != LDB_SUCCESS) {
5449                         DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
5450                         talloc_free(tmp_ctx);
5451                         return WERR_DS_DRA_INTERNAL_ERROR;
5452                 }
5453
5454                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5455                 if (ret != LDB_SUCCESS) {
5456                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
5457                                  ldb_errstring(ldb)));
5458                         talloc_free(tmp_ctx);
5459                         return WERR_DS_DRA_INTERNAL_ERROR;
5460                 }
5461                 break;
5462         case DREPL_SCHEMA_MASTER:
5463                 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
5464                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5465                 if (ret != LDB_SUCCESS) {
5466                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5467                                  ldb_errstring(ldb)));
5468                         talloc_free(tmp_ctx);
5469                         return WERR_DS_DRA_INTERNAL_ERROR;
5470                 }
5471                 break;
5472         case DREPL_PDC_MASTER:
5473                 *fsmo_role_dn = ldb_get_default_basedn(ldb);
5474                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5475                 if (ret != LDB_SUCCESS) {
5476                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
5477                                  ldb_errstring(ldb)));
5478                         talloc_free(tmp_ctx);
5479                         return WERR_DS_DRA_INTERNAL_ERROR;
5480                 }
5481                 break;
5482         default:
5483                 return WERR_DS_DRA_INTERNAL_ERROR;
5484         }
5485         return WERR_OK;
5486 }
5487
5488 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
5489                                     TALLOC_CTX *mem_ctx,
5490                                     struct ldb_dn *server_dn)
5491 {
5492         int ldb_ret;
5493         struct ldb_result *res = NULL;
5494         const char * const attrs[] = { "dNSHostName", NULL};
5495
5496         ldb_ret = ldb_search(ldb, mem_ctx, &res,
5497                              server_dn,
5498                              LDB_SCOPE_BASE,
5499                              attrs, NULL);
5500         if (ldb_ret != LDB_SUCCESS) {
5501                 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
5502                           ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
5503                 return NULL;
5504         }
5505
5506         return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
5507 }
5508
5509 /*
5510   returns true if an attribute is in the filter,
5511   false otherwise, provided that attribute value is provided with the expression
5512 */
5513 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
5514                              const char *attr)
5515 {
5516        unsigned int i;
5517        switch (tree->operation) {
5518        case LDB_OP_AND:
5519        case LDB_OP_OR:
5520                for (i=0;i<tree->u.list.num_elements;i++) {
5521                        if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
5522                                                        attr))
5523                                return true;
5524                }
5525                return false;
5526        case LDB_OP_NOT:
5527                return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
5528        case LDB_OP_EQUALITY:
5529        case LDB_OP_GREATER:
5530        case LDB_OP_LESS:
5531        case LDB_OP_APPROX:
5532                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
5533                        return true;
5534                }
5535                return false;
5536        case LDB_OP_SUBSTRING:
5537                if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
5538                        return true;
5539                }
5540                return false;
5541        case LDB_OP_PRESENT:
5542                /* (attrname=*) is not filtered out */
5543                return false;
5544        case LDB_OP_EXTENDED:
5545                if (tree->u.extended.attr &&
5546                    ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
5547                        return true;
5548                }
5549                return false;
5550        }
5551        return false;
5552 }
5553
5554 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
5555                    const char *location, const char *func,
5556                    const char *reason)
5557 {
5558         if (reason == NULL) {
5559                 reason = win_errstr(werr);
5560         }
5561         ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
5562                                W_ERROR_V(werr), reason, location, func);
5563         return ldb_ecode;
5564 }
5565
5566 /*
5567   map an ldb error code to an approximate NTSTATUS code
5568  */
5569 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
5570 {
5571         switch (err) {
5572         case LDB_SUCCESS:
5573                 return NT_STATUS_OK;
5574
5575         case LDB_ERR_PROTOCOL_ERROR:
5576                 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
5577
5578         case LDB_ERR_TIME_LIMIT_EXCEEDED:
5579                 return NT_STATUS_IO_TIMEOUT;
5580
5581         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
5582                 return NT_STATUS_BUFFER_TOO_SMALL;
5583
5584         case LDB_ERR_COMPARE_FALSE:
5585         case LDB_ERR_COMPARE_TRUE:
5586                 return NT_STATUS_REVISION_MISMATCH;
5587
5588         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
5589                 return NT_STATUS_NOT_SUPPORTED;
5590
5591         case LDB_ERR_STRONG_AUTH_REQUIRED:
5592         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
5593         case LDB_ERR_SASL_BIND_IN_PROGRESS:
5594         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
5595         case LDB_ERR_INVALID_CREDENTIALS:
5596         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
5597         case LDB_ERR_UNWILLING_TO_PERFORM:
5598                 return NT_STATUS_ACCESS_DENIED;
5599
5600         case LDB_ERR_NO_SUCH_OBJECT:
5601                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
5602
5603         case LDB_ERR_REFERRAL:
5604         case LDB_ERR_NO_SUCH_ATTRIBUTE:
5605                 return NT_STATUS_NOT_FOUND;
5606
5607         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
5608                 return NT_STATUS_NOT_SUPPORTED;
5609
5610         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
5611                 return NT_STATUS_BUFFER_TOO_SMALL;
5612
5613         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
5614         case LDB_ERR_INAPPROPRIATE_MATCHING:
5615         case LDB_ERR_CONSTRAINT_VIOLATION:
5616         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
5617         case LDB_ERR_INVALID_DN_SYNTAX:
5618         case LDB_ERR_NAMING_VIOLATION:
5619         case LDB_ERR_OBJECT_CLASS_VIOLATION:
5620         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
5621         case LDB_ERR_NOT_ALLOWED_ON_RDN:
5622                 return NT_STATUS_INVALID_PARAMETER;
5623
5624         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
5625         case LDB_ERR_ENTRY_ALREADY_EXISTS:
5626                 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
5627
5628         case LDB_ERR_BUSY:
5629                 return NT_STATUS_NETWORK_BUSY;
5630
5631         case LDB_ERR_ALIAS_PROBLEM:
5632         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
5633         case LDB_ERR_UNAVAILABLE:
5634         case LDB_ERR_LOOP_DETECT:
5635         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
5636         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
5637         case LDB_ERR_OTHER:
5638         case LDB_ERR_OPERATIONS_ERROR:
5639                 break;
5640         }
5641         return NT_STATUS_UNSUCCESSFUL;
5642 }
5643
5644
5645 /*
5646   create a new naming context that will hold a partial replica
5647  */
5648 int dsdb_create_partial_replica_NC(struct ldb_context *ldb,  struct ldb_dn *dn)
5649 {
5650         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5651         struct ldb_message *msg;
5652         int ret;
5653
5654         msg = ldb_msg_new(tmp_ctx);
5655         if (msg == NULL) {
5656                 talloc_free(tmp_ctx);
5657                 return ldb_oom(ldb);
5658         }
5659
5660         msg->dn = dn;
5661         ret = ldb_msg_add_string(msg, "objectClass", "top");
5662         if (ret != LDB_SUCCESS) {
5663                 talloc_free(tmp_ctx);
5664                 return ldb_oom(ldb);
5665         }
5666
5667         /* [MS-DRSR] implies that we should only add the 'top'
5668          * objectclass, but that would cause lots of problems with our
5669          * objectclass code as top is not structural, so we add
5670          * 'domainDNS' as well to keep things sane. We're expecting
5671          * this new NC to be of objectclass domainDNS after
5672          * replication anyway
5673          */
5674         ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
5675         if (ret != LDB_SUCCESS) {
5676                 talloc_free(tmp_ctx);
5677                 return ldb_oom(ldb);
5678         }
5679
5680         ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
5681                               INSTANCE_TYPE_IS_NC_HEAD|
5682                               INSTANCE_TYPE_NC_ABOVE|
5683                               INSTANCE_TYPE_UNINSTANT);
5684         if (ret != LDB_SUCCESS) {
5685                 talloc_free(tmp_ctx);
5686                 return ldb_oom(ldb);
5687         }
5688
5689         ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
5690         if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
5691                 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
5692                          ldb_dn_get_linearized(dn),
5693                          ldb_errstring(ldb), ldb_strerror(ret)));
5694                 talloc_free(tmp_ctx);
5695                 return ret;
5696         }
5697
5698         DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
5699
5700         talloc_free(tmp_ctx);
5701         return LDB_SUCCESS;
5702 }
5703
5704 /*
5705  * Return the effective badPwdCount
5706  *
5707  * This requires that the user_msg have (if present):
5708  *  - badPasswordTime
5709  *  - badPwdCount
5710  *
5711  * This also requires that the domain_msg have (if present):
5712  *  - lockOutObservationWindow
5713  */
5714 int dsdb_effective_badPwdCount(const struct ldb_message *user_msg,
5715                                int64_t lockOutObservationWindow,
5716                                NTTIME now)
5717 {
5718         int64_t badPasswordTime;
5719         badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
5720
5721         if (badPasswordTime - lockOutObservationWindow >= now) {
5722                 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
5723         } else {
5724                 return 0;
5725         }
5726 }
5727
5728 /*
5729  * Returns a user's PSO, or NULL if none was found
5730  */
5731 static struct ldb_result *lookup_user_pso(struct ldb_context *sam_ldb,
5732                                           TALLOC_CTX *mem_ctx,
5733                                           const struct ldb_message *user_msg,
5734                                           const char * const *attrs)
5735 {
5736         struct ldb_result *res = NULL;
5737         struct ldb_dn *pso_dn = NULL;
5738         int ret;
5739
5740         /* if the user has a PSO that applies, then use the PSO's setting */
5741         pso_dn = ldb_msg_find_attr_as_dn(sam_ldb, mem_ctx, user_msg,
5742                                          "msDS-ResultantPSO");
5743
5744         if (pso_dn != NULL) {
5745
5746                 ret = dsdb_search_dn(sam_ldb, mem_ctx, &res, pso_dn, attrs, 0);
5747                 if (ret != LDB_SUCCESS) {
5748
5749                         /*
5750                          * log the error. The caller should fallback to using
5751                          * the default domain password settings
5752                          */
5753                         DBG_ERR("Error retrieving msDS-ResultantPSO %s for %s",
5754                                 ldb_dn_get_linearized(pso_dn),
5755                                 ldb_dn_get_linearized(user_msg->dn));
5756                 }
5757                 talloc_free(pso_dn);
5758         }
5759         return res;
5760 }
5761
5762 /*
5763  * Return the msDS-LockoutObservationWindow for a user message
5764  *
5765  * This requires that the user_msg have (if present):
5766  *  - msDS-ResultantPSO
5767  */
5768 int64_t samdb_result_msds_LockoutObservationWindow(
5769         struct ldb_context *sam_ldb,
5770         TALLOC_CTX *mem_ctx,
5771         struct ldb_dn *domain_dn,
5772         const struct ldb_message *user_msg)
5773 {
5774         int64_t lockOutObservationWindow;
5775         struct ldb_result *res = NULL;
5776         const char *attrs[] = { "msDS-LockoutObservationWindow",
5777                                 NULL };
5778         if (domain_dn == NULL) {
5779                 smb_panic("domain dn is NULL");
5780         }
5781         res = lookup_user_pso(sam_ldb, mem_ctx, user_msg, attrs);
5782
5783         if (res != NULL) {
5784                 lockOutObservationWindow =
5785                         ldb_msg_find_attr_as_int64(res->msgs[0],
5786                                                    "msDS-LockoutObservationWindow",
5787                                                     DEFAULT_OBSERVATION_WINDOW);
5788                 talloc_free(res);
5789         } else {
5790
5791                 /* no PSO was found, lookup the default domain setting */
5792                 lockOutObservationWindow =
5793                          samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
5794                                             "lockOutObservationWindow", NULL);
5795         }
5796         return lockOutObservationWindow;
5797 }
5798
5799 /*
5800  * Return the effective badPwdCount
5801  *
5802  * This requires that the user_msg have (if present):
5803  *  - badPasswordTime
5804  *  - badPwdCount
5805  *  - msDS-ResultantPSO
5806  */
5807 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
5808                                        TALLOC_CTX *mem_ctx,
5809                                        struct ldb_dn *domain_dn,
5810                                        const struct ldb_message *user_msg)
5811 {
5812         struct timeval tv_now = timeval_current();
5813         NTTIME now = timeval_to_nttime(&tv_now);
5814         int64_t lockOutObservationWindow =
5815                 samdb_result_msds_LockoutObservationWindow(
5816                         sam_ldb, mem_ctx, domain_dn, user_msg);
5817         return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5818 }
5819
5820 /*
5821  * Returns the lockoutThreshold that applies. If a PSO is specified, then that
5822  * setting is used over the domain defaults
5823  */
5824 static int64_t get_lockout_threshold(struct ldb_message *domain_msg,
5825                                      struct ldb_message *pso_msg)
5826 {
5827         if (pso_msg != NULL) {
5828                 return ldb_msg_find_attr_as_int(pso_msg,
5829                                                 "msDS-LockoutThreshold", 0);
5830         } else {
5831                 return ldb_msg_find_attr_as_int(domain_msg,
5832                                                 "lockoutThreshold", 0);
5833         }
5834 }
5835
5836 /*
5837  * Returns the lockOutObservationWindow that applies. If a PSO is specified,
5838  * then that setting is used over the domain defaults
5839  */
5840 static int64_t get_lockout_observation_window(struct ldb_message *domain_msg,
5841                                               struct ldb_message *pso_msg)
5842 {
5843         if (pso_msg != NULL) {
5844                 return ldb_msg_find_attr_as_int64(pso_msg,
5845                                                   "msDS-LockoutObservationWindow",
5846                                                    DEFAULT_OBSERVATION_WINDOW);
5847         } else {
5848                 return ldb_msg_find_attr_as_int64(domain_msg,
5849                                                   "lockOutObservationWindow",
5850                                                    DEFAULT_OBSERVATION_WINDOW);
5851         }
5852 }
5853
5854 /*
5855  * Prepare an update to the badPwdCount and associated attributes.
5856  *
5857  * This requires that the user_msg have (if present):
5858  *  - objectSid
5859  *  - badPasswordTime
5860  *  - badPwdCount
5861  *
5862  * This also requires that the domain_msg have (if present):
5863  *  - pwdProperties
5864  *  - lockoutThreshold
5865  *  - lockOutObservationWindow
5866  *
5867  * This also requires that the pso_msg have (if present):
5868  *  - msDS-LockoutThreshold
5869  *  - msDS-LockoutObservationWindow
5870  */
5871 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
5872                                    struct ldb_context *sam_ctx,
5873                                    struct ldb_message *user_msg,
5874                                    struct ldb_message *domain_msg,
5875                                    struct ldb_message *pso_msg,
5876                                    struct ldb_message **_mod_msg)
5877 {
5878         int ret, badPwdCount;
5879         unsigned int i;
5880         int64_t lockoutThreshold, lockOutObservationWindow;
5881         struct dom_sid *sid;
5882         struct timeval tv_now = timeval_current();
5883         NTTIME now = timeval_to_nttime(&tv_now);
5884         NTSTATUS status;
5885         uint32_t pwdProperties, rid = 0;
5886         struct ldb_message *mod_msg;
5887
5888         sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
5889
5890         pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
5891                                                   "pwdProperties", -1);
5892         if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
5893                 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
5894                 if (!NT_STATUS_IS_OK(status)) {
5895                         /*
5896                          * This can't happen anyway, but always try
5897                          * and update the badPwdCount on failure
5898                          */
5899                         rid = 0;
5900                 }
5901         }
5902         TALLOC_FREE(sid);
5903
5904         /*
5905          * Work out if we are doing password lockout on the domain.
5906          * Also, the built in administrator account is exempt:
5907          * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
5908          */
5909         lockoutThreshold = get_lockout_threshold(domain_msg, pso_msg);
5910         if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
5911                 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
5912                           ldb_dn_get_linearized(user_msg->dn)));
5913                 return NT_STATUS_OK;
5914         }
5915
5916         mod_msg = ldb_msg_new(mem_ctx);
5917         if (mod_msg == NULL) {
5918                 return NT_STATUS_NO_MEMORY;
5919         }
5920         mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
5921         if (mod_msg->dn == NULL) {
5922                 TALLOC_FREE(mod_msg);
5923                 return NT_STATUS_NO_MEMORY;
5924         }
5925
5926         lockOutObservationWindow = get_lockout_observation_window(domain_msg,
5927                                                                   pso_msg);
5928
5929         badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5930
5931         badPwdCount++;
5932
5933         ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
5934         if (ret != LDB_SUCCESS) {
5935                 TALLOC_FREE(mod_msg);
5936                 return NT_STATUS_NO_MEMORY;
5937         }
5938         ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
5939         if (ret != LDB_SUCCESS) {
5940                 TALLOC_FREE(mod_msg);
5941                 return NT_STATUS_NO_MEMORY;
5942         }
5943
5944         if (badPwdCount >= lockoutThreshold) {
5945                 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
5946                 if (ret != LDB_SUCCESS) {
5947                         TALLOC_FREE(mod_msg);
5948                         return NT_STATUS_NO_MEMORY;
5949                 }
5950                 DEBUGC( DBGC_AUTH, 1, ("Locked out user %s after %d wrong passwords\n",
5951                           ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5952         } else {
5953                 DEBUGC( DBGC_AUTH, 5, ("Updated badPwdCount on %s after %d wrong passwords\n",
5954                           ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5955         }
5956
5957         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5958         for (i=0; i< mod_msg->num_elements; i++) {
5959                 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5960         }
5961
5962         *_mod_msg = mod_msg;
5963         return NT_STATUS_OK;
5964 }
5965
5966 /**
5967  * Sets defaults for a User object
5968  * List of default attributes set:
5969  *      accountExpires, badPasswordTime, badPwdCount,
5970  *      codePage, countryCode, lastLogoff, lastLogon
5971  *      logonCount, pwdLastSet
5972  */
5973 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
5974                                struct ldb_message *usr_obj,
5975                                struct ldb_request *req)
5976 {
5977         size_t i;
5978         int ret;
5979         const struct attribute_values {
5980                 const char *name;
5981                 const char *value;
5982                 const char *add_value;
5983                 const char *mod_value;
5984                 const char *control;
5985                 unsigned add_flags;
5986                 unsigned mod_flags;
5987         } map[] = {
5988                 {
5989                         .name = "accountExpires",
5990                         .add_value = "9223372036854775807",
5991                         .mod_value = "0",
5992                 },
5993                 {
5994                         .name = "badPasswordTime",
5995                         .value = "0"
5996                 },
5997                 {
5998                         .name = "badPwdCount",
5999                         .value = "0"
6000                 },
6001                 {
6002                         .name = "codePage",
6003                         .value = "0"
6004                 },
6005                 {
6006                         .name = "countryCode",
6007                         .value = "0"
6008                 },
6009                 {
6010                         .name = "lastLogoff",
6011                         .value = "0"
6012                 },
6013                 {
6014                         .name = "lastLogon",
6015                         .value = "0"
6016                 },
6017                 {
6018                         .name = "logonCount",
6019                         .value = "0"
6020                 },
6021                 {
6022                         .name = "logonHours",
6023                         .add_flags = DSDB_FLAG_INTERNAL_FORCE_META_DATA,
6024                 },
6025                 {
6026                         .name = "pwdLastSet",
6027                         .value = "0",
6028                         .control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
6029                 },
6030                 {
6031                         .name = "adminCount",
6032                         .mod_value = "0",
6033                 },
6034                 {
6035                         .name = "operatorCount",
6036                         .mod_value = "0",
6037                 },
6038         };
6039
6040         for (i = 0; i < ARRAY_SIZE(map); i++) {
6041                 bool added = false;
6042                 const char *value = NULL;
6043                 unsigned flags = 0;
6044
6045                 if (req != NULL && req->operation == LDB_ADD) {
6046                         value = map[i].add_value;
6047                         flags = map[i].add_flags;
6048                 } else {
6049                         value = map[i].mod_value;
6050                         flags = map[i].mod_flags;
6051                 }
6052
6053                 if (value == NULL) {
6054                         value = map[i].value;
6055                 }
6056
6057                 if (value != NULL) {
6058                         flags |= LDB_FLAG_MOD_ADD;
6059                 }
6060
6061                 if (flags == 0) {
6062                         continue;
6063                 }
6064
6065                 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
6066                                                      map[i].name,
6067                                                      value, flags,
6068                                                      &added);
6069                 if (ret != LDB_SUCCESS) {
6070                         return ret;
6071                 }
6072
6073                 if (req != NULL && added && map[i].control != NULL) {
6074                         ret = ldb_request_add_control(req,
6075                                                       map[i].control,
6076                                                       false, NULL);
6077                         if (ret != LDB_SUCCESS) {
6078                                 return ret;
6079                         }
6080                 }
6081         }
6082
6083         return LDB_SUCCESS;
6084 }
6085
6086 /**
6087  * Sets 'sAMAccountType on user object based on userAccountControl.
6088  * This function is used in processing both 'add' and 'modify' requests.
6089  * @param ldb Current ldb_context
6090  * @param usr_obj ldb_message representing User object
6091  * @param user_account_control Value for userAccountControl flags
6092  * @param account_type_p Optional pointer to account_type to return
6093  * @return LDB_SUCCESS or LDB_ERR* code on failure
6094  */
6095 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
6096                                    uint32_t user_account_control, uint32_t *account_type_p)
6097 {
6098         int ret;
6099         uint32_t account_type;
6100
6101         account_type = ds_uf2atype(user_account_control);
6102         if (account_type == 0) {
6103                 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
6104                 return LDB_ERR_UNWILLING_TO_PERFORM;
6105         }
6106         ret = samdb_msg_add_uint_flags(ldb, usr_obj, usr_obj,
6107                                        "sAMAccountType",
6108                                        account_type,
6109                                        LDB_FLAG_MOD_REPLACE);
6110         if (ret != LDB_SUCCESS) {
6111                 return ret;
6112         }
6113
6114         if (account_type_p) {
6115                 *account_type_p = account_type;
6116         }
6117
6118         return LDB_SUCCESS;
6119 }
6120
6121 /**
6122  * Determine and set primaryGroupID based on userAccountControl value.
6123  * This function is used in processing both 'add' and 'modify' requests.
6124  * @param ldb Current ldb_context
6125  * @param usr_obj ldb_message representing User object
6126  * @param user_account_control Value for userAccountControl flags
6127  * @param group_rid_p Optional pointer to group RID to return
6128  * @return LDB_SUCCESS or LDB_ERR* code on failure
6129  */
6130 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
6131                                        uint32_t user_account_control, uint32_t *group_rid_p)
6132 {
6133         int ret;
6134         uint32_t rid;
6135
6136         rid = ds_uf2prim_group_rid(user_account_control);
6137
6138         ret = samdb_msg_add_uint_flags(ldb, usr_obj, usr_obj,
6139                                        "primaryGroupID", rid,
6140                                        LDB_FLAG_MOD_REPLACE);
6141         if (ret != LDB_SUCCESS) {
6142                 return ret;
6143         }
6144
6145         if (group_rid_p) {
6146                 *group_rid_p = rid;
6147         }
6148
6149         return LDB_SUCCESS;
6150 }
6151
6152 /**
6153  * Returns True if the source and target DNs both have the same naming context,
6154  * i.e. they're both in the same partition.
6155  */
6156 bool dsdb_objects_have_same_nc(struct ldb_context *ldb,
6157                                TALLOC_CTX *mem_ctx,
6158                                struct ldb_dn *source_dn,
6159                                struct ldb_dn *target_dn)
6160 {
6161         TALLOC_CTX *tmp_ctx;
6162         struct ldb_dn *source_nc = NULL;
6163         struct ldb_dn *target_nc = NULL;
6164         int ret;
6165         bool same_nc = true;
6166
6167         tmp_ctx = talloc_new(mem_ctx);
6168
6169         ret = dsdb_find_nc_root(ldb, tmp_ctx, source_dn, &source_nc);
6170         /* fix clang warning */
6171         if (source_nc == NULL) {
6172                 ret = LDB_ERR_OTHER;
6173         }
6174         if (ret != LDB_SUCCESS) {
6175                 DBG_ERR("Failed to find base DN for source %s: %s\n",
6176                         ldb_dn_get_linearized(source_dn), ldb_errstring(ldb));
6177                 talloc_free(tmp_ctx);
6178                 return true;
6179         }
6180
6181         ret = dsdb_find_nc_root(ldb, tmp_ctx, target_dn, &target_nc);
6182         /* fix clang warning */
6183         if (target_nc == NULL) {
6184                 ret = LDB_ERR_OTHER;
6185         }
6186         if (ret != LDB_SUCCESS) {
6187                 DBG_ERR("Failed to find base DN for target %s: %s\n",
6188                         ldb_dn_get_linearized(target_dn), ldb_errstring(ldb));
6189                 talloc_free(tmp_ctx);
6190                 return true;
6191         }
6192
6193         same_nc = (ldb_dn_compare(source_nc, target_nc) == 0);
6194
6195         talloc_free(tmp_ctx);
6196
6197         return same_nc;
6198 }
6199 /*
6200  * Context for dsdb_count_domain_callback
6201  */
6202 struct dsdb_count_domain_context {
6203         /*
6204          * Number of matching records
6205          */
6206         size_t count;
6207         /*
6208          * sid of the domain that the records must belong to.
6209          * if NULL records can belong to any domain.
6210          */
6211         struct dom_sid *dom_sid;
6212 };
6213
6214 /*
6215  * @brief ldb aysnc callback for dsdb_domain_count.
6216  *
6217  * count the number of records in the database matching an LDAP query,
6218  * optionally filtering for domain membership.
6219  *
6220  * @param [in,out] req the ldb request being processed
6221  *                    req->context contains:
6222  *                        count   The number of matching records
6223  *                        dom_sid The domain sid, if present records must belong
6224  *                                to the domain to be counted.
6225  *@param [in,out] ares The query result.
6226  *
6227  * @return an LDB error code
6228  *
6229  */
6230 static int dsdb_count_domain_callback(
6231         struct ldb_request *req,
6232         struct ldb_reply *ares)
6233 {
6234
6235         if (ares == NULL) {
6236                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
6237         }
6238         if (ares->error != LDB_SUCCESS) {
6239                 int error = ares->error;
6240                 TALLOC_FREE(ares);
6241                 return ldb_request_done(req, error);
6242         }
6243
6244         switch (ares->type) {
6245         case LDB_REPLY_ENTRY:
6246         {
6247                 struct dsdb_count_domain_context *context = NULL;
6248                 ssize_t ret;
6249                 bool in_domain;
6250                 struct dom_sid sid;
6251                 const struct ldb_val *v;
6252
6253                 context = req->context;
6254                 if (context->dom_sid == NULL) {
6255                         context->count++;
6256                         break;
6257                 }
6258
6259                 v = ldb_msg_find_ldb_val(ares->message, "objectSid");
6260                 if (v == NULL) {
6261                         break;
6262                 }
6263
6264                 ret = sid_parse(v->data, v->length, &sid);
6265                 if (ret == -1) {
6266                         break;
6267                 }
6268
6269                 in_domain = dom_sid_in_domain(context->dom_sid, &sid);
6270                 if (!in_domain) {
6271                         break;
6272                 }
6273
6274                 context->count++;
6275                 break;
6276         }
6277         case LDB_REPLY_REFERRAL:
6278                 break;
6279
6280         case LDB_REPLY_DONE:
6281                 TALLOC_FREE(ares);
6282                 return ldb_request_done(req, LDB_SUCCESS);
6283         }
6284
6285         TALLOC_FREE(ares);
6286
6287         return LDB_SUCCESS;
6288 }
6289
6290 /*
6291  * @brief Count the number of records matching a query.
6292  *
6293  * Count the number of entries in the database matching the supplied query,
6294  * optionally filtering only those entries belonging to the supplied domain.
6295  *
6296  * @param ldb [in] Current ldb context
6297  * @param count [out] Pointer to the count
6298  * @param base [in] The base dn for the quey
6299  * @param dom_sid [in] The domain sid, if non NULL records that are not a member
6300  *                     of the domain are ignored.
6301  * @param scope [in] Search scope.
6302  * @param exp_fmt [in] format string for the query.
6303  *
6304  * @return LDB_STATUS code.
6305  */
6306 int PRINTF_ATTRIBUTE(6, 7) dsdb_domain_count(
6307         struct ldb_context *ldb,
6308         size_t *count,
6309         struct ldb_dn *base,
6310         struct dom_sid *dom_sid,
6311         enum ldb_scope scope,
6312         const char *exp_fmt, ...)
6313 {
6314         TALLOC_CTX *tmp_ctx = NULL;
6315         struct ldb_request *req = NULL;
6316         struct dsdb_count_domain_context *context = NULL;
6317         char *expression = NULL;
6318         const char *object_sid[] = {"objectSid", NULL};
6319         const char *none[] = {NULL};
6320         va_list ap;
6321         int ret;
6322
6323         *count = 0;
6324         tmp_ctx = talloc_new(ldb);
6325
6326         context = talloc_zero(tmp_ctx, struct dsdb_count_domain_context);
6327         if (context == NULL) {
6328                 return LDB_ERR_OPERATIONS_ERROR;
6329         }
6330         context->dom_sid = dom_sid;
6331
6332         if (exp_fmt) {
6333                 va_start(ap, exp_fmt);
6334                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
6335                 va_end(ap);
6336
6337                 if (expression == NULL) {
6338                         TALLOC_FREE(context);
6339                         TALLOC_FREE(tmp_ctx);
6340                         return LDB_ERR_OPERATIONS_ERROR;
6341                 }
6342         }
6343
6344         ret = ldb_build_search_req(
6345                 &req,
6346                 ldb,
6347                 tmp_ctx,
6348                 base,
6349                 scope,
6350                 expression,
6351                 (dom_sid == NULL) ? none : object_sid,
6352                 NULL,
6353                 context,
6354                 dsdb_count_domain_callback,
6355                 NULL);
6356         ldb_req_set_location(req, "dsdb_domain_count");
6357
6358         if (ret != LDB_SUCCESS) goto done;
6359
6360         ret = ldb_request(ldb, req);
6361
6362         if (ret == LDB_SUCCESS) {
6363                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
6364                 if (ret == LDB_SUCCESS) {
6365                         *count = context->count;
6366                 }
6367         }
6368
6369
6370 done:
6371         TALLOC_FREE(expression);
6372         TALLOC_FREE(req);
6373         TALLOC_FREE(context);
6374         TALLOC_FREE(tmp_ctx);
6375
6376         return ret;
6377 }
6378
6379 /*
6380  * Returns 1 if 'sids' contains the Protected Users group SID for the domain, 0
6381  * if not. Returns a negative value on error.
6382  */
6383 int dsdb_is_protected_user(struct ldb_context *ldb,
6384                            const struct auth_SidAttr *sids,
6385                            uint32_t num_sids)
6386 {
6387         const struct dom_sid *domain_sid = NULL;
6388         struct dom_sid protected_users_sid;
6389         uint32_t i;
6390
6391         domain_sid = samdb_domain_sid(ldb);
6392         if (domain_sid == NULL) {
6393                 return -1;
6394         }
6395
6396         protected_users_sid = *domain_sid;
6397         if (!sid_append_rid(&protected_users_sid, DOMAIN_RID_PROTECTED_USERS)) {
6398                 return -1;
6399         }
6400
6401         for (i = 0; i < num_sids; ++i) {
6402                 if (dom_sid_equal(&protected_users_sid, &sids[i].sid)) {
6403                         return 1;
6404                 }
6405         }
6406
6407         return 0;
6408 }