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