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