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