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