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