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