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