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