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