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