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