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