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