s4 dsdb util: samdb_client_site_name clean up
[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 "system/filesys.h"
43 #include "lib/util/tsort.h"
44 #include "dsdb/common/util.h"
45 #include "lib/socket/socket.h"
46 #include "librpc/gen_ndr/irpc.h"
47 #include "libds/common/flag_mapping.h"
48 #include "lib/util/access.h"
49 #include "lib/util/util_str_hex.h"
50 #include "libcli/util/ntstatus.h"
51
52 /*
53  * This included to allow us to handle DSDB_FLAG_REPLICATED_UPDATE in
54  * dsdb_request_add_controls()
55  */
56 #include "dsdb/samdb/ldb_modules/util.h"
57
58 /* default is 30 minutes: -1e7 * 30 * 60 */
59 #define DEFAULT_OBSERVATION_WINDOW              -18000000000
60
61 /*
62   search the sam for the specified attributes in a specific domain, filter on
63   objectSid being in domain_sid.
64 */
65 int samdb_search_domain(struct ldb_context *sam_ldb,
66                         TALLOC_CTX *mem_ctx, 
67                         struct ldb_dn *basedn,
68                         struct ldb_message ***res,
69                         const char * const *attrs,
70                         const struct dom_sid *domain_sid,
71                         const char *format, ...)  _PRINTF_ATTRIBUTE(7,8)
72 {
73         va_list ap;
74         int i, count;
75
76         va_start(ap, format);
77         count = gendb_search_v(sam_ldb, mem_ctx, basedn,
78                                res, attrs, format, ap);
79         va_end(ap);
80
81         i=0;
82
83         while (i<count) {
84                 struct dom_sid *entry_sid;
85
86                 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
87
88                 if ((entry_sid == NULL) ||
89                     (!dom_sid_in_domain(domain_sid, entry_sid))) {
90                         /* Delete that entry from the result set */
91                         (*res)[i] = (*res)[count-1];
92                         count -= 1;
93                         talloc_free(entry_sid);
94                         continue;
95                 }
96                 talloc_free(entry_sid);
97                 i += 1;
98         }
99
100         return count;
101 }
102
103 /*
104   search the sam for a single string attribute in exactly 1 record
105 */
106 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
107                                   TALLOC_CTX *mem_ctx,
108                                   struct ldb_dn *basedn,
109                                   const char *attr_name,
110                                   const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
111 {
112         int count;
113         const char *attrs[2] = { NULL, NULL };
114         struct ldb_message **res = NULL;
115
116         attrs[0] = attr_name;
117
118         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
119         if (count > 1) {                
120                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
121                          attr_name, format, count));
122         }
123         if (count != 1) {
124                 talloc_free(res);
125                 return NULL;
126         }
127
128         return ldb_msg_find_attr_as_string(res[0], attr_name, NULL);
129 }
130
131 /*
132   search the sam for a single string attribute in exactly 1 record
133 */
134 const char *samdb_search_string(struct ldb_context *sam_ldb,
135                                 TALLOC_CTX *mem_ctx,
136                                 struct ldb_dn *basedn,
137                                 const char *attr_name,
138                                 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
139 {
140         va_list ap;
141         const char *str;
142
143         va_start(ap, format);
144         str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
145         va_end(ap);
146
147         return str;
148 }
149
150 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
151                                TALLOC_CTX *mem_ctx,
152                                struct ldb_dn *basedn,
153                                const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
154 {
155         va_list ap;
156         struct ldb_dn *ret;
157         struct ldb_message **res = NULL;
158         int count;
159
160         va_start(ap, format);
161         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
162         va_end(ap);
163
164         if (count != 1) return NULL;
165
166         ret = talloc_steal(mem_ctx, res[0]->dn);
167         talloc_free(res);
168
169         return ret;
170 }
171
172 /*
173   search the sam for a dom_sid attribute in exactly 1 record
174 */
175 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
176                                      TALLOC_CTX *mem_ctx,
177                                      struct ldb_dn *basedn,
178                                      const char *attr_name,
179                                      const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
180 {
181         va_list ap;
182         int count;
183         struct ldb_message **res;
184         const char *attrs[2] = { NULL, NULL };
185         struct dom_sid *sid;
186
187         attrs[0] = attr_name;
188
189         va_start(ap, format);
190         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
191         va_end(ap);
192         if (count > 1) {                
193                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
194                          attr_name, format, count));
195         }
196         if (count != 1) {
197                 talloc_free(res);
198                 return NULL;
199         }
200         sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
201         talloc_free(res);
202         return sid;     
203 }
204
205 /*
206   search the sam for a single integer attribute in exactly 1 record
207 */
208 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
209                          TALLOC_CTX *mem_ctx,
210                          unsigned int default_value,
211                          struct ldb_dn *basedn,
212                          const char *attr_name,
213                          const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
214 {
215         va_list ap;
216         int count;
217         struct ldb_message **res;
218         const char *attrs[2] = { NULL, NULL };
219
220         attrs[0] = attr_name;
221
222         va_start(ap, format);
223         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
224         va_end(ap);
225
226         if (count != 1) {
227                 return default_value;
228         }
229
230         return ldb_msg_find_attr_as_uint(res[0], attr_name, default_value);
231 }
232
233 /*
234   search the sam for a single signed 64 bit integer attribute in exactly 1 record
235 */
236 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
237                            TALLOC_CTX *mem_ctx,
238                            int64_t default_value,
239                            struct ldb_dn *basedn,
240                            const char *attr_name,
241                            const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
242 {
243         va_list ap;
244         int count;
245         struct ldb_message **res;
246         const char *attrs[2] = { NULL, NULL };
247
248         attrs[0] = attr_name;
249
250         va_start(ap, format);
251         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
252         va_end(ap);
253
254         if (count != 1) {
255                 return default_value;
256         }
257
258         return ldb_msg_find_attr_as_int64(res[0], attr_name, default_value);
259 }
260
261 /*
262   search the sam for multipe records each giving a single string attribute
263   return the number of matches, or -1 on error
264 */
265 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
266                                  TALLOC_CTX *mem_ctx,
267                                  struct ldb_dn *basedn,
268                                  const char ***strs,
269                                  const char *attr_name,
270                                  const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
271 {
272         va_list ap;
273         int count, i;
274         const char *attrs[2] = { NULL, NULL };
275         struct ldb_message **res = NULL;
276
277         attrs[0] = attr_name;
278
279         va_start(ap, format);
280         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
281         va_end(ap);
282
283         if (count <= 0) {
284                 return count;
285         }
286
287         /* make sure its single valued */
288         for (i=0;i<count;i++) {
289                 if (res[i]->num_elements != 1) {
290                         DEBUG(1,("samdb: search for %s %s not single valued\n", 
291                                  attr_name, format));
292                         talloc_free(res);
293                         return -1;
294                 }
295         }
296
297         *strs = talloc_array(mem_ctx, const char *, count+1);
298         if (! *strs) {
299                 talloc_free(res);
300                 return -1;
301         }
302
303         for (i=0;i<count;i++) {
304                 (*strs)[i] = ldb_msg_find_attr_as_string(res[i], attr_name, NULL);
305         }
306         (*strs)[count] = NULL;
307
308         return count;
309 }
310
311 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
312                                const char *attr, struct ldb_dn *default_value)
313 {
314         struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
315         if (!ret_dn) {
316                 return default_value;
317         }
318         return ret_dn;
319 }
320
321 /*
322   pull a rid from a objectSid in a result set. 
323 */
324 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
325                                    const char *attr, uint32_t default_value)
326 {
327         struct dom_sid *sid;
328         uint32_t rid;
329
330         sid = samdb_result_dom_sid(mem_ctx, msg, attr);
331         if (sid == NULL) {
332                 return default_value;
333         }
334         rid = sid->sub_auths[sid->num_auths-1];
335         talloc_free(sid);
336         return rid;
337 }
338
339 /*
340   pull a dom_sid structure from a objectSid in a result set. 
341 */
342 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
343                                      const char *attr)
344 {
345         bool ok;
346         const struct ldb_val *v;
347         struct dom_sid *sid;
348         v = ldb_msg_find_ldb_val(msg, attr);
349         if (v == NULL) {
350                 return NULL;
351         }
352         sid = talloc(mem_ctx, struct dom_sid);
353         if (sid == NULL) {
354                 return NULL;
355         }
356         ok = sid_parse(v->data, v->length, sid);
357         if (!ok) {
358                 talloc_free(sid);
359                 return NULL;
360         }
361         return sid;
362 }
363
364 /*
365   pull a guid structure from a objectGUID in a result set. 
366 */
367 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
368 {
369         const struct ldb_val *v;
370         struct GUID guid;
371         NTSTATUS status;
372
373         v = ldb_msg_find_ldb_val(msg, attr);
374         if (!v) return GUID_zero();
375
376         status = GUID_from_ndr_blob(v, &guid);
377         if (!NT_STATUS_IS_OK(status)) {
378                 return GUID_zero();
379         }
380
381         return guid;
382 }
383
384 /*
385   pull a sid prefix from a objectSid in a result set. 
386   this is used to find the domain sid for a user
387 */
388 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
389                                         const char *attr)
390 {
391         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
392         if (!sid || sid->num_auths < 1) return NULL;
393         sid->num_auths--;
394         return sid;
395 }
396
397 /*
398   pull a NTTIME in a result set. 
399 */
400 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
401                            NTTIME default_value)
402 {
403         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
404 }
405
406 /*
407  * Windows stores 0 for lastLogoff.
408  * But when a MS DC return the lastLogoff (as Logoff Time)
409  * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
410  * cause windows 2008 and newer version to fail for SMB requests
411  */
412 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
413 {
414         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
415
416         if (ret == 0)
417                 ret = 0x7FFFFFFFFFFFFFFFULL;
418
419         return ret;
420 }
421
422 /*
423  * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
424  * indicate an account doesn't expire.
425  *
426  * When Windows initially creates an account, it sets
427  * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF).  However,
428  * when changing from an account having a specific expiration date to
429  * that account never expiring, it sets accountExpires = 0.
430  *
431  * Consolidate that logic here to allow clearer logic for account expiry in
432  * the rest of the code.
433  */
434 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
435 {
436         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
437                                                  0);
438
439         if (ret == 0)
440                 ret = 0x7FFFFFFFFFFFFFFFULL;
441
442         return ret;
443 }
444
445 /*
446   construct the allow_password_change field from the PwdLastSet attribute and the 
447   domain password settings
448 */
449 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb, 
450                                           TALLOC_CTX *mem_ctx, 
451                                           struct ldb_dn *domain_dn, 
452                                           struct ldb_message *msg, 
453                                           const char *attr)
454 {
455         uint64_t attr_time = ldb_msg_find_attr_as_uint64(msg, attr, 0);
456         int64_t minPwdAge;
457
458         if (attr_time == 0) {
459                 return 0;
460         }
461
462         minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
463
464         /* yes, this is a -= not a += as minPwdAge is stored as the negative
465            of the number of 100-nano-seconds */
466         attr_time -= minPwdAge;
467
468         return attr_time;
469 }
470
471 /*
472   pull a samr_Password structutre from a result set. 
473 */
474 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
475 {
476         struct samr_Password *hash = NULL;
477         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
478         if (val && (val->length >= sizeof(hash->hash))) {
479                 hash = talloc(mem_ctx, struct samr_Password);
480                 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
481         }
482         return hash;
483 }
484
485 /*
486   pull an array of samr_Password structures from a result set.
487 */
488 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
489                            const char *attr, struct samr_Password **hashes)
490 {
491         unsigned int count, i;
492         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
493
494         *hashes = NULL;
495         if (!val) {
496                 return 0;
497         }
498         count = val->length / 16;
499         if (count == 0) {
500                 return 0;
501         }
502
503         *hashes = talloc_array(mem_ctx, struct samr_Password, count);
504         if (! *hashes) {
505                 return 0;
506         }
507
508         for (i=0;i<count;i++) {
509                 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
510         }
511
512         return count;
513 }
514
515 NTSTATUS samdb_result_passwords_from_history(TALLOC_CTX *mem_ctx,
516                                              struct loadparm_context *lp_ctx,
517                                              struct ldb_message *msg,
518                                              unsigned int idx,
519                                              struct samr_Password **lm_pwd,
520                                              struct samr_Password **nt_pwd)
521 {
522         struct samr_Password *lmPwdHash, *ntPwdHash;
523
524         if (nt_pwd) {
525                 unsigned int num_nt;
526                 num_nt = samdb_result_hashes(mem_ctx, msg, "ntPwdHistory", &ntPwdHash);
527                 if (num_nt <= idx) {
528                         *nt_pwd = NULL;
529                 } else {
530                         *nt_pwd = &ntPwdHash[idx];
531                 }
532         }
533         if (lm_pwd) {
534                 /* Ensure that if we have turned off LM
535                  * authentication, that we never use the LM hash, even
536                  * if we store it */
537                 if (lpcfg_lanman_auth(lp_ctx)) {
538                         unsigned int num_lm;
539                         num_lm = samdb_result_hashes(mem_ctx, msg, "lmPwdHistory", &lmPwdHash);
540                         if (num_lm <= idx) {
541                                 *lm_pwd = NULL;
542                         } else {
543                                 *lm_pwd = &lmPwdHash[idx];
544                         }
545                 } else {
546                         *lm_pwd = NULL;
547                 }
548         }
549         return NT_STATUS_OK;
550 }
551
552 NTSTATUS samdb_result_passwords_no_lockout(TALLOC_CTX *mem_ctx,
553                                            struct loadparm_context *lp_ctx,
554                                            const struct ldb_message *msg,
555                                            struct samr_Password **lm_pwd,
556                                            struct samr_Password **nt_pwd)
557 {
558         struct samr_Password *lmPwdHash, *ntPwdHash;
559
560         if (nt_pwd) {
561                 unsigned int num_nt;
562                 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
563                 if (num_nt == 0) {
564                         *nt_pwd = NULL;
565                 } else if (num_nt > 1) {
566                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
567                 } else {
568                         *nt_pwd = &ntPwdHash[0];
569                 }
570         }
571         if (lm_pwd) {
572                 /* Ensure that if we have turned off LM
573                  * authentication, that we never use the LM hash, even
574                  * if we store it */
575                 if (lpcfg_lanman_auth(lp_ctx)) {
576                         unsigned int num_lm;
577                         num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
578                         if (num_lm == 0) {
579                                 *lm_pwd = NULL;
580                         } else if (num_lm > 1) {
581                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
582                         } else {
583                                 *lm_pwd = &lmPwdHash[0];
584                         }
585                 } else {
586                         *lm_pwd = NULL;
587                 }
588         }
589         return NT_STATUS_OK;
590 }
591
592 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx,
593                                 struct loadparm_context *lp_ctx,
594                                 const struct ldb_message *msg,
595                                 struct samr_Password **lm_pwd,
596                                 struct samr_Password **nt_pwd)
597 {
598         uint16_t acct_flags;
599
600         acct_flags = samdb_result_acct_flags(msg,
601                                              "msDS-User-Account-Control-Computed");
602         /* Quit if the account was locked out. */
603         if (acct_flags & ACB_AUTOLOCK) {
604                 DEBUG(3,("samdb_result_passwords: Account for user %s was locked out.\n",
605                          ldb_dn_get_linearized(msg->dn)));
606                 return NT_STATUS_ACCOUNT_LOCKED_OUT;
607         }
608
609         return samdb_result_passwords_no_lockout(mem_ctx, lp_ctx, msg,
610                                                  lm_pwd, nt_pwd);
611 }
612
613 /*
614   pull a samr_LogonHours structutre from a result set. 
615 */
616 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
617 {
618         struct samr_LogonHours hours;
619         size_t units_per_week = 168;
620         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
621
622         ZERO_STRUCT(hours);
623
624         if (val) {
625                 units_per_week = val->length * 8;
626         }
627
628         hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
629         if (!hours.bits) {
630                 return hours;
631         }
632         hours.units_per_week = units_per_week;
633         memset(hours.bits, 0xFF, units_per_week/8);
634         if (val) {
635                 memcpy(hours.bits, val->data, val->length);
636         }
637
638         return hours;
639 }
640
641 /*
642   pull a set of account_flags from a result set. 
643
644   Naturally, this requires that userAccountControl and
645   (if not null) the attributes 'attr' be already
646   included in msg
647 */
648 uint32_t samdb_result_acct_flags(const struct ldb_message *msg, const char *attr)
649 {
650         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
651         uint32_t attr_flags = 0;
652         uint32_t acct_flags = ds_uf2acb(userAccountControl);
653         if (attr) {
654                 attr_flags = ldb_msg_find_attr_as_uint(msg, attr, UF_ACCOUNTDISABLE);
655                 if (attr_flags == UF_ACCOUNTDISABLE) {
656                         DEBUG(0, ("Attribute %s not found, disabling account %s!\n", attr,
657                                   ldb_dn_get_linearized(msg->dn)));
658                 }
659                 acct_flags |= ds_uf2acb(attr_flags);
660         }
661
662         return acct_flags;
663 }
664
665 NTSTATUS samdb_result_parameters(TALLOC_CTX *mem_ctx,
666                                  struct ldb_message *msg,
667                                  const char *attr,
668                                  struct lsa_BinaryString *s)
669 {
670         int i;
671         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
672
673         ZERO_STRUCTP(s);
674
675         if (!val) {
676                 return NT_STATUS_OK;
677         }
678
679         if ((val->length % 2) != 0) {
680                 /*
681                  * If the on-disk data is not even in length, we know
682                  * it is corrupt, and can not be safely pushed.  We
683                  * would either truncate, send either a un-initilaised
684                  * byte or send a forced zero byte
685                  */
686                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
687         }
688
689         s->array = talloc_array(mem_ctx, uint16_t, val->length/2);
690         if (!s->array) {
691                 return NT_STATUS_NO_MEMORY;
692         }
693         s->length = s->size = val->length;
694
695         /* The on-disk format is the 'network' format, being UTF16LE (sort of) */
696         for (i = 0; i < s->length / 2; i++) {
697                 s->array[i] = SVAL(val->data, i * 2);
698         }
699
700         return NT_STATUS_OK;
701 }
702
703 /* Find an attribute, with a particular value */
704
705 /* The current callers of this function expect a very specific
706  * behaviour: In particular, objectClass subclass equivilance is not
707  * wanted.  This means that we should not lookup the schema for the
708  * comparison function */
709 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb, 
710                                                  const struct ldb_message *msg, 
711                                                  const char *name, const char *value)
712 {
713         unsigned int i;
714         struct ldb_message_element *el = ldb_msg_find_element(msg, name);
715
716         if (!el) {
717                 return NULL;
718         }
719
720         for (i=0;i<el->num_values;i++) {
721                 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
722                         return el;
723                 }
724         }
725
726         return NULL;
727 }
728
729 static int samdb_find_or_add_attribute_ex(struct ldb_context *ldb,
730                                           struct ldb_message *msg,
731                                           const char *name,
732                                           const char *set_value,
733                                           unsigned attr_flags,
734                                           bool *added)
735 {
736         int ret;
737         struct ldb_message_element *el;
738
739         SMB_ASSERT(attr_flags != 0);
740
741         el = ldb_msg_find_element(msg, name);
742         if (el) {
743                 if (added != NULL) {
744                         *added = false;
745                 }
746
747                 return LDB_SUCCESS;
748         }
749
750         ret = ldb_msg_add_empty(msg, name,
751                                 attr_flags,
752                                 &el);
753         if (ret != LDB_SUCCESS) {
754                 return ret;
755         }
756
757         if (set_value != NULL) {
758                 ret = ldb_msg_add_string(msg, name, set_value);
759                 if (ret != LDB_SUCCESS) {
760                         return ret;
761                 }
762         }
763
764         if (added != NULL) {
765                 *added = true;
766         }
767         return LDB_SUCCESS;
768 }
769
770 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
771 {
772         return samdb_find_or_add_attribute_ex(ldb, msg, name, set_value, LDB_FLAG_MOD_ADD, NULL);
773 }
774
775 /*
776   add a dom_sid element to a message
777 */
778 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
779                           const char *attr_name, const struct dom_sid *sid)
780 {
781         struct ldb_val v;
782         enum ndr_err_code ndr_err;
783
784         ndr_err = ndr_push_struct_blob(&v, mem_ctx, 
785                                        sid,
786                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
787         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
788                 return ldb_operr(sam_ldb);
789         }
790         return ldb_msg_add_value(msg, attr_name, &v, NULL);
791 }
792
793
794 /*
795   add a delete element operation to a message
796 */
797 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
798                          const char *attr_name)
799 {
800         /* we use an empty replace rather than a delete, as it allows for 
801            dsdb_replace() to be used everywhere */
802         return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
803 }
804
805 /*
806   add an add attribute value to a message or enhance an existing attribute
807   which has the same name and the add flag set.
808 */
809 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
810                          struct ldb_message *msg, const char *attr_name,
811                          const char *value)
812 {
813         struct ldb_message_element *el;
814         struct ldb_val val, *vals;
815         char *v;
816         unsigned int i;
817         bool found = false;
818         int ret;
819
820         v = talloc_strdup(mem_ctx, value);
821         if (v == NULL) {
822                 return ldb_oom(sam_ldb);
823         }
824
825         val.data = (uint8_t *) v;
826         val.length = strlen(v);
827
828         if (val.length == 0) {
829                 /* allow empty strings as non-existent attributes */
830                 return LDB_SUCCESS;
831         }
832
833         for (i = 0; i < msg->num_elements; i++) {
834                 el = &msg->elements[i];
835                 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
836                     (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
837                         found = true;
838                         break;
839                 }
840         }
841         if (!found) {
842                 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
843                                         &el);
844                 if (ret != LDB_SUCCESS) {
845                         return ret;
846                 }
847         }
848
849         vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
850                               el->num_values + 1);
851         if (vals == NULL) {
852                 return ldb_oom(sam_ldb);
853         }
854         el->values = vals;
855         el->values[el->num_values] = val;
856         ++(el->num_values);
857
858         return LDB_SUCCESS;
859 }
860
861 /*
862   add a delete attribute value to a message or enhance an existing attribute
863   which has the same name and the delete flag set.
864 */
865 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
866                          struct ldb_message *msg, const char *attr_name,
867                          const char *value)
868 {
869         struct ldb_message_element *el;
870         struct ldb_val val, *vals;
871         char *v;
872         unsigned int i;
873         bool found = false;
874         int ret;
875
876         v = talloc_strdup(mem_ctx, value);
877         if (v == NULL) {
878                 return ldb_oom(sam_ldb);
879         }
880
881         val.data = (uint8_t *) v;
882         val.length = strlen(v);
883
884         if (val.length == 0) {
885                 /* allow empty strings as non-existent attributes */
886                 return LDB_SUCCESS;
887         }
888
889         for (i = 0; i < msg->num_elements; i++) {
890                 el = &msg->elements[i];
891                 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
892                     (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
893                         found = true;
894                         break;
895                 }
896         }
897         if (!found) {
898                 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
899                                         &el);
900                 if (ret != LDB_SUCCESS) {
901                         return ret;
902                 }
903         }
904
905         vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
906                               el->num_values + 1);
907         if (vals == NULL) {
908                 return ldb_oom(sam_ldb);
909         }
910         el->values = vals;
911         el->values[el->num_values] = val;
912         ++(el->num_values);
913
914         return LDB_SUCCESS;
915 }
916
917 /*
918   add a int element to a message
919 */
920 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
921                        const char *attr_name, int v)
922 {
923         const char *s = talloc_asprintf(mem_ctx, "%d", v);
924         if (s == NULL) {
925                 return ldb_oom(sam_ldb);
926         }
927         return ldb_msg_add_string(msg, attr_name, s);
928 }
929
930 /*
931  * Add an unsigned int element to a message
932  *
933  * The issue here is that we have not yet first cast to int32_t explicitly,
934  * before we cast to an signed int to printf() into the %d or cast to a
935  * int64_t before we then cast to a long long to printf into a %lld.
936  *
937  * There are *no* unsigned integers in Active Directory LDAP, even the RID
938  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
939  * (See the schema, and the syntax definitions in schema_syntax.c).
940  *
941  */
942 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
943                        const char *attr_name, unsigned int v)
944 {
945         return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
946 }
947
948 /*
949   add a (signed) int64_t element to a message
950 */
951 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
952                         const char *attr_name, int64_t v)
953 {
954         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
955         if (s == NULL) {
956                 return ldb_oom(sam_ldb);
957         }
958         return ldb_msg_add_string(msg, attr_name, s);
959 }
960
961 /*
962  * Add an unsigned int64_t (uint64_t) element to a message
963  *
964  * The issue here is that we have not yet first cast to int32_t explicitly,
965  * before we cast to an signed int to printf() into the %d or cast to a
966  * int64_t before we then cast to a long long to printf into a %lld.
967  *
968  * There are *no* unsigned integers in Active Directory LDAP, even the RID
969  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
970  * (See the schema, and the syntax definitions in schema_syntax.c).
971  *
972  */
973 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
974                         const char *attr_name, uint64_t v)
975 {
976         return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
977 }
978
979 /*
980   add a samr_Password element to a message
981 */
982 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
983                        const char *attr_name, const struct samr_Password *hash)
984 {
985         struct ldb_val val;
986         val.data = talloc_memdup(mem_ctx, hash->hash, 16);
987         if (!val.data) {
988                 return ldb_oom(sam_ldb);
989         }
990         val.length = 16;
991         return ldb_msg_add_value(msg, attr_name, &val, NULL);
992 }
993
994 /*
995   add a samr_Password array to a message
996 */
997 int samdb_msg_add_hashes(struct ldb_context *ldb,
998                          TALLOC_CTX *mem_ctx, struct ldb_message *msg,
999                          const char *attr_name, struct samr_Password *hashes,
1000                          unsigned int count)
1001 {
1002         struct ldb_val val;
1003         unsigned int i;
1004         val.data = talloc_array_size(mem_ctx, 16, count);
1005         val.length = count*16;
1006         if (!val.data) {
1007                 return ldb_oom(ldb);
1008         }
1009         for (i=0;i<count;i++) {
1010                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
1011         }
1012         return ldb_msg_add_value(msg, attr_name, &val, NULL);
1013 }
1014
1015 /*
1016   add a acct_flags element to a message
1017 */
1018 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1019                              const char *attr_name, uint32_t v)
1020 {
1021         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1022 }
1023
1024 /*
1025   add a logon_hours element to a message
1026 */
1027 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1028                               const char *attr_name, struct samr_LogonHours *hours)
1029 {
1030         struct ldb_val val;
1031         val.length = hours->units_per_week / 8;
1032         val.data = hours->bits;
1033         return ldb_msg_add_value(msg, attr_name, &val, NULL);
1034 }
1035
1036 /*
1037   add a parameters element to a message
1038 */
1039 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1040                              const char *attr_name, struct lsa_BinaryString *parameters)
1041 {
1042         int i;
1043         struct ldb_val val;
1044         if ((parameters->length % 2) != 0) {
1045                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
1046         }
1047
1048         val.data = talloc_array(mem_ctx, uint8_t, parameters->length);
1049         if (val.data == NULL) {
1050                 return LDB_ERR_OPERATIONS_ERROR;
1051         }
1052         val.length = parameters->length;
1053         for (i = 0; i < parameters->length / 2; i++) {
1054                 /*
1055                  * The on-disk format needs to be in the 'network'
1056                  * format, parmeters->array is a uint16_t array of
1057                  * length parameters->length / 2
1058                  */
1059                 SSVAL(val.data, i * 2, parameters->array[i]);
1060         }
1061         return ldb_msg_add_steal_value(msg, attr_name, &val);
1062 }
1063
1064 /*
1065  * Sets an unsigned int element in a message
1066  *
1067  * The issue here is that we have not yet first cast to int32_t explicitly,
1068  * before we cast to an signed int to printf() into the %d or cast to a
1069  * int64_t before we then cast to a long long to printf into a %lld.
1070  *
1071  * There are *no* unsigned integers in Active Directory LDAP, even the RID
1072  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1073  * (See the schema, and the syntax definitions in schema_syntax.c).
1074  *
1075  */
1076 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1077                        struct ldb_message *msg, const char *attr_name,
1078                        unsigned int v)
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 samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1087 }
1088
1089 /*
1090  * Handle ldb_request in transaction
1091  */
1092 int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1093                                  struct ldb_request *req)
1094 {
1095         int ret;
1096
1097         ret = ldb_transaction_start(sam_ldb);
1098         if (ret != LDB_SUCCESS) {
1099                 return ret;
1100         }
1101
1102         ret = ldb_request(sam_ldb, req);
1103         if (ret == LDB_SUCCESS) {
1104                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1105         }
1106
1107         if (ret == LDB_SUCCESS) {
1108                 return ldb_transaction_commit(sam_ldb);
1109         }
1110         ldb_transaction_cancel(sam_ldb);
1111
1112         return ret;
1113 }
1114
1115 /*
1116   return a default security descriptor
1117 */
1118 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1119 {
1120         struct security_descriptor *sd;
1121
1122         sd = security_descriptor_initialise(mem_ctx);
1123
1124         return sd;
1125 }
1126
1127 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx) 
1128 {
1129         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1130         struct ldb_dn *aggregate_dn;
1131         if (!schema_dn) {
1132                 return NULL;
1133         }
1134
1135         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1136         if (!aggregate_dn) {
1137                 return NULL;
1138         }
1139         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1140                 return NULL;
1141         }
1142         return aggregate_dn;
1143 }
1144
1145 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1146 {
1147         struct ldb_dn *new_dn;
1148
1149         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1150         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1151                 talloc_free(new_dn);
1152                 return NULL;
1153         }
1154         return new_dn;
1155 }
1156
1157 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1158 {
1159        struct ldb_dn *new_dn;
1160
1161        new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1162        if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1163                talloc_free(new_dn);
1164                return NULL;
1165        }
1166        return new_dn;
1167 }
1168
1169 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1170 {
1171         struct ldb_dn *new_dn;
1172
1173         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1174         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1175                 talloc_free(new_dn);
1176                 return NULL;
1177         }
1178         return new_dn;
1179 }
1180
1181 /*
1182   work out the domain sid for the current open ldb
1183 */
1184 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1185 {
1186         TALLOC_CTX *tmp_ctx;
1187         const struct dom_sid *domain_sid;
1188         const char *attrs[] = {
1189                 "objectSid",
1190                 NULL
1191         };
1192         struct ldb_result *res;
1193         int ret;
1194
1195         /* see if we have a cached copy */
1196         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1197         if (domain_sid) {
1198                 return domain_sid;
1199         }
1200
1201         tmp_ctx = talloc_new(ldb);
1202         if (tmp_ctx == NULL) {
1203                 goto failed;
1204         }
1205
1206         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1207
1208         if (ret != LDB_SUCCESS) {
1209                 goto failed;
1210         }
1211
1212         if (res->count != 1) {
1213                 goto failed;
1214         }
1215
1216         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1217         if (domain_sid == NULL) {
1218                 goto failed;
1219         }
1220
1221         /* cache the domain_sid in the ldb */
1222         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1223                 goto failed;
1224         }
1225
1226         talloc_steal(ldb, domain_sid);
1227         talloc_free(tmp_ctx);
1228
1229         return domain_sid;
1230
1231 failed:
1232         talloc_free(tmp_ctx);
1233         return NULL;
1234 }
1235
1236 /*
1237   get domain sid from cache
1238 */
1239 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1240 {
1241         return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1242 }
1243
1244 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1245 {
1246         TALLOC_CTX *tmp_ctx;
1247         struct dom_sid *dom_sid_new;
1248         struct dom_sid *dom_sid_old;
1249
1250         /* see if we have a cached copy */
1251         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1252                                                      "cache.domain_sid"), struct dom_sid);
1253
1254         tmp_ctx = talloc_new(ldb);
1255         if (tmp_ctx == NULL) {
1256                 goto failed;
1257         }
1258
1259         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1260         if (!dom_sid_new) {
1261                 goto failed;
1262         }
1263
1264         /* cache the domain_sid in the ldb */
1265         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1266                 goto failed;
1267         }
1268
1269         talloc_steal(ldb, dom_sid_new);
1270         talloc_free(tmp_ctx);
1271         talloc_free(dom_sid_old);
1272
1273         return true;
1274
1275 failed:
1276         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1277         talloc_free(tmp_ctx);
1278         return false;
1279 }
1280
1281 /*
1282   work out the domain guid for the current open ldb
1283 */
1284 const struct GUID *samdb_domain_guid(struct ldb_context *ldb)
1285 {
1286         TALLOC_CTX *tmp_ctx = NULL;
1287         struct GUID *domain_guid = NULL;
1288         const char *attrs[] = {
1289                 "objectGUID",
1290                 NULL
1291         };
1292         struct ldb_result *res = NULL;
1293         int ret;
1294
1295         /* see if we have a cached copy */
1296         domain_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.domain_guid");
1297         if (domain_guid) {
1298                 return domain_guid;
1299         }
1300
1301         tmp_ctx = talloc_new(ldb);
1302         if (tmp_ctx == NULL) {
1303                 goto failed;
1304         }
1305
1306         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectGUID=*");
1307         if (ret != LDB_SUCCESS) {
1308                 goto failed;
1309         }
1310
1311         if (res->count != 1) {
1312                 goto failed;
1313         }
1314
1315         domain_guid = talloc(tmp_ctx, struct GUID);
1316         if (domain_guid == NULL) {
1317                 goto failed;
1318         }
1319         *domain_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1320
1321         /* cache the domain_sid in the ldb */
1322         if (ldb_set_opaque(ldb, "cache.domain_guid", domain_guid) != LDB_SUCCESS) {
1323                 goto failed;
1324         }
1325
1326         talloc_steal(ldb, domain_guid);
1327         talloc_free(tmp_ctx);
1328
1329         return domain_guid;
1330
1331 failed:
1332         talloc_free(tmp_ctx);
1333         return NULL;
1334 }
1335
1336 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1337 {
1338         TALLOC_CTX *tmp_ctx;
1339         struct ldb_dn *ntds_settings_dn_new;
1340         struct ldb_dn *ntds_settings_dn_old;
1341
1342         /* see if we have a forced copy from provision */
1343         ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb, 
1344                                                               "forced.ntds_settings_dn"), struct ldb_dn);
1345
1346         tmp_ctx = talloc_new(ldb);
1347         if (tmp_ctx == NULL) {
1348                 goto failed;
1349         }
1350
1351         ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1352         if (!ntds_settings_dn_new) {
1353                 goto failed;
1354         }
1355
1356         /* set the DN in the ldb to avoid lookups during provision */
1357         if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1358                 goto failed;
1359         }
1360
1361         talloc_steal(ldb, ntds_settings_dn_new);
1362         talloc_free(tmp_ctx);
1363         talloc_free(ntds_settings_dn_old);
1364
1365         return true;
1366
1367 failed:
1368         DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1369         talloc_free(tmp_ctx);
1370         return false;
1371 }
1372
1373 /*
1374   work out the ntds settings dn for the current open ldb
1375 */
1376 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1377 {
1378         TALLOC_CTX *tmp_ctx;
1379         const char *root_attrs[] = { "dsServiceName", NULL };
1380         int ret;
1381         struct ldb_result *root_res;
1382         struct ldb_dn *settings_dn;
1383
1384         /* see if we have a cached copy */
1385         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1386         if (settings_dn) {
1387                 return ldb_dn_copy(mem_ctx, settings_dn);
1388         }
1389
1390         tmp_ctx = talloc_new(mem_ctx);
1391         if (tmp_ctx == NULL) {
1392                 goto failed;
1393         }
1394
1395         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1396         if (ret != LDB_SUCCESS) {
1397                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1398                          ldb_errstring(ldb)));
1399                 goto failed;
1400         }
1401
1402         if (root_res->count != 1) {
1403                 goto failed;
1404         }
1405
1406         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1407
1408         /* note that we do not cache the DN here, as that would mean
1409          * we could not handle server renames at runtime. Only
1410          * provision sets up forced.ntds_settings_dn */
1411
1412         talloc_steal(mem_ctx, settings_dn);
1413         talloc_free(tmp_ctx);
1414
1415         return settings_dn;
1416
1417 failed:
1418         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1419         talloc_free(tmp_ctx);
1420         return NULL;
1421 }
1422
1423 /*
1424   work out the ntds settings invocationId for the current open ldb
1425 */
1426 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1427 {
1428         TALLOC_CTX *tmp_ctx;
1429         const char *attrs[] = { "invocationId", NULL };
1430         int ret;
1431         struct ldb_result *res;
1432         struct GUID *invocation_id;
1433
1434         /* see if we have a cached copy */
1435         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1436         if (invocation_id) {
1437                 SMB_ASSERT(!GUID_all_zero(invocation_id));
1438                 return invocation_id;
1439         }
1440
1441         tmp_ctx = talloc_new(ldb);
1442         if (tmp_ctx == NULL) {
1443                 goto failed;
1444         }
1445
1446         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1447         if (ret) {
1448                 goto failed;
1449         }
1450
1451         if (res->count != 1) {
1452                 goto failed;
1453         }
1454
1455         invocation_id = talloc(tmp_ctx, struct GUID);
1456         if (!invocation_id) {
1457                 goto failed;
1458         }
1459
1460         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1461         if (GUID_all_zero(invocation_id)) {
1462                 if (ldb_msg_find_ldb_val(res->msgs[0], "invocationId")) {
1463                         DEBUG(0, ("Failed to find our own NTDS Settings invocationId in the ldb!\n"));  
1464                 } else {
1465                         DEBUG(0, ("Failed to find parse own NTDS Settings invocationId from the ldb!\n"));
1466                 }
1467                 goto failed;
1468         }
1469
1470         /* cache the domain_sid in the ldb */
1471         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1472                 goto failed;
1473         }
1474
1475         talloc_steal(ldb, invocation_id);
1476         talloc_free(tmp_ctx);
1477
1478         return invocation_id;
1479
1480 failed:
1481         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1482         talloc_free(tmp_ctx);
1483         return NULL;
1484 }
1485
1486 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1487 {
1488         TALLOC_CTX *tmp_ctx;
1489         struct GUID *invocation_id_new;
1490         struct GUID *invocation_id_old;
1491
1492         /* see if we have a cached copy */
1493         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1494                                                          "cache.invocation_id");
1495
1496         tmp_ctx = talloc_new(ldb);
1497         if (tmp_ctx == NULL) {
1498                 goto failed;
1499         }
1500
1501         invocation_id_new = talloc(tmp_ctx, struct GUID);
1502         if (!invocation_id_new) {
1503                 goto failed;
1504         }
1505
1506         SMB_ASSERT(!GUID_all_zero(invocation_id_in));
1507         *invocation_id_new = *invocation_id_in;
1508
1509         /* cache the domain_sid in the ldb */
1510         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1511                 goto failed;
1512         }
1513
1514         talloc_steal(ldb, invocation_id_new);
1515         talloc_free(tmp_ctx);
1516         talloc_free(invocation_id_old);
1517
1518         return true;
1519
1520 failed:
1521         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1522         talloc_free(tmp_ctx);
1523         return false;
1524 }
1525
1526 /*
1527   work out the ntds settings objectGUID for the current open ldb
1528 */
1529 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1530 {
1531         TALLOC_CTX *tmp_ctx;
1532         const char *attrs[] = { "objectGUID", NULL };
1533         int ret;
1534         struct ldb_result *res;
1535         struct GUID *ntds_guid;
1536
1537         /* see if we have a cached copy */
1538         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1539         if (ntds_guid) {
1540                 return ntds_guid;
1541         }
1542
1543         tmp_ctx = talloc_new(ldb);
1544         if (tmp_ctx == NULL) {
1545                 goto failed;
1546         }
1547
1548         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1549         if (ret) {
1550                 goto failed;
1551         }
1552
1553         if (res->count != 1) {
1554                 goto failed;
1555         }
1556
1557         ntds_guid = talloc(tmp_ctx, struct GUID);
1558         if (!ntds_guid) {
1559                 goto failed;
1560         }
1561
1562         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1563
1564         /* cache the domain_sid in the ldb */
1565         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1566                 goto failed;
1567         }
1568
1569         talloc_steal(ldb, ntds_guid);
1570         talloc_free(tmp_ctx);
1571
1572         return ntds_guid;
1573
1574 failed:
1575         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1576         talloc_free(tmp_ctx);
1577         return NULL;
1578 }
1579
1580 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1581 {
1582         TALLOC_CTX *tmp_ctx;
1583         struct GUID *ntds_guid_new;
1584         struct GUID *ntds_guid_old;
1585
1586         /* see if we have a cached copy */
1587         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1588
1589         tmp_ctx = talloc_new(ldb);
1590         if (tmp_ctx == NULL) {
1591                 goto failed;
1592         }
1593
1594         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1595         if (!ntds_guid_new) {
1596                 goto failed;
1597         }
1598
1599         *ntds_guid_new = *ntds_guid_in;
1600
1601         /* cache the domain_sid in the ldb */
1602         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1603                 goto failed;
1604         }
1605
1606         talloc_steal(ldb, ntds_guid_new);
1607         talloc_free(tmp_ctx);
1608         talloc_free(ntds_guid_old);
1609
1610         return true;
1611
1612 failed:
1613         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1614         talloc_free(tmp_ctx);
1615         return false;
1616 }
1617
1618 /*
1619   work out the server dn for the current open ldb
1620 */
1621 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1622 {
1623         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1624         struct ldb_dn *dn;
1625         if (!tmp_ctx) {
1626                 return NULL;
1627         }
1628         dn = ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb, tmp_ctx));
1629         talloc_free(tmp_ctx);
1630         return dn;
1631         
1632 }
1633
1634 /*
1635   work out the server dn for the current open ldb
1636 */
1637 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1638 {
1639         struct ldb_dn *server_dn;
1640         struct ldb_dn *servers_dn;
1641         struct ldb_dn *server_site_dn;
1642
1643         /* TODO: there must be a saner way to do this!! */
1644         server_dn = samdb_server_dn(ldb, mem_ctx);
1645         if (!server_dn) return NULL;
1646
1647         servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1648         talloc_free(server_dn);
1649         if (!servers_dn) return NULL;
1650
1651         server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1652         talloc_free(servers_dn);
1653
1654         return server_site_dn;
1655 }
1656
1657 /*
1658   find the site name from a computers DN record
1659  */
1660 int samdb_find_site_for_computer(struct ldb_context *ldb,
1661                                  TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1662                                  const char **site_name)
1663 {
1664         int ret;
1665         struct ldb_dn *dn;
1666         const struct ldb_val *rdn_val;
1667
1668         *site_name = NULL;
1669
1670         ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1671         if (ret != LDB_SUCCESS) {
1672                 return ret;
1673         }
1674
1675         if (!ldb_dn_remove_child_components(dn, 2)) {
1676                 talloc_free(dn);
1677                 return LDB_ERR_INVALID_DN_SYNTAX;
1678         }
1679
1680         rdn_val = ldb_dn_get_rdn_val(dn);
1681         if (rdn_val == NULL) {
1682                 return LDB_ERR_OPERATIONS_ERROR;
1683         }
1684
1685         (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1686         talloc_free(dn);
1687         if (!*site_name) {
1688                 return LDB_ERR_OPERATIONS_ERROR;
1689         }
1690         return LDB_SUCCESS;
1691 }
1692
1693 /*
1694   find the NTDS GUID from a computers DN record
1695  */
1696 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1697                                      struct GUID *ntds_guid)
1698 {
1699         int ret;
1700         struct ldb_dn *dn;
1701
1702         *ntds_guid = GUID_zero();
1703
1704         ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1705         if (ret != LDB_SUCCESS) {
1706                 return ret;
1707         }
1708
1709         if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1710                 talloc_free(dn);
1711                 return LDB_ERR_OPERATIONS_ERROR;
1712         }
1713
1714         ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1715         talloc_free(dn);
1716         return ret;
1717 }
1718
1719 /*
1720   find a 'reference' DN that points at another object
1721   (eg. serverReference, rIDManagerReference etc)
1722  */
1723 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1724                        const char *attribute, struct ldb_dn **dn)
1725 {
1726         const char *attrs[2];
1727         struct ldb_result *res;
1728         int ret;
1729
1730         attrs[0] = attribute;
1731         attrs[1] = NULL;
1732
1733         ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY|DSDB_SEARCH_SHOW_EXTENDED_DN, NULL);
1734         if (ret != LDB_SUCCESS) {
1735                 ldb_asprintf_errstring(ldb, "Cannot find DN %s to get attribute %s for reference dn: %s",
1736                                        ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb));
1737                 return ret;
1738         }
1739
1740         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1741         if (!*dn) {
1742                 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1743                         ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1744                                                ldb_dn_get_linearized(base));
1745                 } else {
1746                         ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1747                                                ldb_dn_get_linearized(base));
1748                 }
1749                 talloc_free(res);
1750                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1751         }
1752
1753         talloc_free(res);
1754         return LDB_SUCCESS;
1755 }
1756
1757 /*
1758   find if a DN (must have GUID component!) is our ntdsDsa
1759  */
1760 int samdb_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *dn, bool *is_ntdsa)
1761 {
1762         NTSTATUS status;
1763         struct GUID dn_guid;
1764         const struct GUID *our_ntds_guid;
1765         status = dsdb_get_extended_dn_guid(dn, &dn_guid, "GUID");
1766         if (!NT_STATUS_IS_OK(status)) {
1767                 return LDB_ERR_OPERATIONS_ERROR;
1768         }
1769
1770         our_ntds_guid = samdb_ntds_objectGUID(ldb);
1771         if (!our_ntds_guid) {
1772                 DEBUG(0, ("Failed to find our NTDS Settings GUID for comparison with %s - %s\n", ldb_dn_get_linearized(dn), ldb_errstring(ldb)));
1773                 return LDB_ERR_OPERATIONS_ERROR;
1774         }
1775
1776         *is_ntdsa = GUID_equal(&dn_guid, our_ntds_guid);
1777         return LDB_SUCCESS;
1778 }
1779
1780 /*
1781   find a 'reference' DN that points at another object and indicate if it is our ntdsDsa
1782  */
1783 int samdb_reference_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *base,
1784                                     const char *attribute, bool *is_ntdsa)
1785 {
1786         int ret;
1787         struct ldb_dn *referenced_dn;
1788         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1789         if (tmp_ctx == NULL) {
1790                 return LDB_ERR_OPERATIONS_ERROR;
1791         }
1792         ret = samdb_reference_dn(ldb, tmp_ctx, base, attribute, &referenced_dn);
1793         if (ret != LDB_SUCCESS) {
1794                 DEBUG(0, ("Failed to find object %s for attribute %s - %s\n", ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb)));
1795                 return ret;
1796         }
1797
1798         ret = samdb_dn_is_our_ntdsa(ldb, referenced_dn, is_ntdsa);
1799         
1800         talloc_free(tmp_ctx);
1801         return ret;
1802 }
1803
1804 /*
1805   find our machine account via the serverReference attribute in the
1806   server DN
1807  */
1808 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1809 {
1810         struct ldb_dn *server_dn;
1811         int ret;
1812
1813         server_dn = samdb_server_dn(ldb, mem_ctx);
1814         if (server_dn == NULL) {
1815                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
1816         }
1817
1818         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1819         talloc_free(server_dn);
1820
1821         return ret;
1822 }
1823
1824 /*
1825   find the RID Manager$ DN via the rIDManagerReference attribute in the
1826   base DN
1827  */
1828 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1829 {
1830         return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1831                                   "rIDManagerReference", dn);
1832 }
1833
1834 /*
1835   find the RID Set DN via the rIDSetReferences attribute in our
1836   machine account DN
1837  */
1838 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1839 {
1840         struct ldb_dn *server_ref_dn;
1841         int ret;
1842
1843         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1844         if (ret != LDB_SUCCESS) {
1845                 return ret;
1846         }
1847         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1848         talloc_free(server_ref_dn);
1849         return ret;
1850 }
1851
1852 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1853 {
1854         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1855                                                                             mem_ctx));
1856
1857         if (val == NULL) {
1858                 return NULL;
1859         }
1860
1861         return (const char *) val->data;
1862 }
1863
1864 /*
1865  * Finds the client site by using the client's IP address.
1866  * The "subnet_name" returns the name of the subnet if parameter != NULL
1867  *
1868  * Has a Windows-based fallback to provide the only site available, or an empty
1869  * string if there are multiple sites.
1870  */
1871 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1872                                    const char *ip_address, char **subnet_name,
1873                                    bool fallback)
1874 {
1875         const char *attrs[] = { "cn", "siteObject", NULL };
1876         struct ldb_dn *sites_container_dn = NULL;
1877         struct ldb_dn *subnets_dn = NULL;
1878         struct ldb_dn *sites_dn = NULL;
1879         struct ldb_result *res = NULL;
1880         const struct ldb_val *val = NULL;
1881         const char *site_name = NULL;
1882         const char *l_subnet_name = NULL;
1883         const char *allow_list[2] = { NULL, NULL };
1884         unsigned int i, count;
1885         int ret;
1886
1887         /*
1888          * if we don't have a client ip e.g. ncalrpc
1889          * the server site is the client site
1890          */
1891         if (ip_address == NULL) {
1892                 return samdb_server_site_name(ldb, mem_ctx);
1893         }
1894
1895         sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1896         if (sites_container_dn == NULL) {
1897                 goto exit;
1898         }
1899
1900         subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1901         if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1902                 goto exit;
1903         }
1904
1905         ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1906                          attrs, NULL);
1907         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1908                 count = 0;
1909         } else if (ret != LDB_SUCCESS) {
1910                 goto exit;
1911         } else {
1912                 count = res->count;
1913         }
1914
1915         for (i = 0; i < count; i++) {
1916                 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1917                                                             NULL);
1918
1919                 allow_list[0] = l_subnet_name;
1920
1921                 if (allow_access_nolog(NULL, allow_list, "", ip_address)) {
1922                         sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1923                                                            res->msgs[i],
1924                                                            "siteObject");
1925                         if (sites_dn == NULL) {
1926                                 /* No reference, maybe another subnet matches */
1927                                 continue;
1928                         }
1929
1930                         /* "val" cannot be NULL here since "sites_dn" != NULL */
1931                         val = ldb_dn_get_rdn_val(sites_dn);
1932                         site_name = talloc_strdup(mem_ctx,
1933                                                   (const char *) val->data);
1934
1935                         TALLOC_FREE(sites_dn);
1936
1937                         break;
1938                 }
1939         }
1940
1941         if (site_name == NULL && fallback) {
1942                 /* This is the Windows Server fallback rule: when no subnet
1943                  * exists and we have only one site available then use it (it
1944                  * is for sure the same as our server site). If more sites do
1945                  * exist then we don't know which one to use and set the site
1946                  * name to "". */
1947                 size_t cnt = 0;
1948                 ret = dsdb_domain_count(
1949                         ldb,
1950                         &cnt,
1951                         sites_container_dn,
1952                         NULL,
1953                         LDB_SCOPE_SUBTREE,
1954                         "(objectClass=site)");
1955                 if (ret != LDB_SUCCESS) {
1956                         goto exit;
1957                 }
1958                 if (cnt == 1) {
1959                         site_name = samdb_server_site_name(ldb, mem_ctx);
1960                 } else {
1961                         site_name = talloc_strdup(mem_ctx, "");
1962                 }
1963                 l_subnet_name = NULL;
1964         }
1965
1966         if (subnet_name != NULL) {
1967                 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1968         }
1969
1970 exit:
1971         TALLOC_FREE(sites_container_dn);
1972         TALLOC_FREE(subnets_dn);
1973         TALLOC_FREE(res);
1974
1975         return site_name;
1976 }
1977
1978 /*
1979   work out if we are the PDC for the domain of the current open ldb
1980 */
1981 bool samdb_is_pdc(struct ldb_context *ldb)
1982 {
1983         int ret;
1984         bool is_pdc;
1985
1986         ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner", 
1987                                               &is_pdc);
1988         if (ret != LDB_SUCCESS) {
1989                 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n", 
1990                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1991                          ldb_errstring(ldb)));
1992                 return false;
1993         }
1994
1995         return is_pdc;
1996 }
1997
1998 /*
1999   work out if we are a Global Catalog server for the domain of the current open ldb
2000 */
2001 bool samdb_is_gc(struct ldb_context *ldb)
2002 {
2003         uint32_t options;
2004         if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
2005                 return false;
2006         }
2007         return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
2008 }
2009
2010 /* Find a domain object in the parents of a particular DN.  */
2011 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2012                                    struct ldb_dn **parent_dn, const char **errstring)
2013 {
2014         TALLOC_CTX *local_ctx;
2015         struct ldb_dn *sdn = dn;
2016         struct ldb_result *res = NULL;
2017         int ret = LDB_SUCCESS;
2018         const char *attrs[] = { NULL };
2019
2020         local_ctx = talloc_new(mem_ctx);
2021         if (local_ctx == NULL) return ldb_oom(ldb);
2022
2023         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
2024                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
2025                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
2026                 if (ret == LDB_SUCCESS) {
2027                         if (res->count == 1) {
2028                                 break;
2029                         }
2030                 } else {
2031                         break;
2032                 }
2033         }
2034
2035         if (ret != LDB_SUCCESS) {
2036                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
2037                                              ldb_dn_get_linearized(dn),
2038                                              ldb_dn_get_linearized(sdn),
2039                                              ldb_errstring(ldb));
2040                 talloc_free(local_ctx);
2041                 return ret;
2042         }
2043         if (res->count != 1) {
2044                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
2045                                              ldb_dn_get_linearized(dn));
2046                 DEBUG(0,(__location__ ": %s\n", *errstring));
2047                 talloc_free(local_ctx);
2048                 return LDB_ERR_CONSTRAINT_VIOLATION;
2049         }
2050
2051         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2052         talloc_free(local_ctx);
2053         return ret;
2054 }
2055
2056 static void pwd_timeout_debug(struct tevent_context *unused1,
2057                               struct tevent_timer *unused2,
2058                               struct timeval unused3,
2059                               void *unused4)
2060 {
2061         DEBUG(0, ("WARNING: check_password_complexity: password script "
2062                   "took more than 1 second to run\n"));
2063 }
2064
2065
2066 /*
2067  * Performs checks on a user password (plaintext UNIX format - attribute
2068  * "password"). The remaining parameters have to be extracted from the domain
2069  * object in the AD.
2070  *
2071  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
2072  */
2073 enum samr_ValidationStatus samdb_check_password(TALLOC_CTX *mem_ctx,
2074                                                 struct loadparm_context *lp_ctx,
2075                                                 const char *account_name,
2076                                                 const char *user_principal_name,
2077                                                 const char *full_name,
2078                                                 const DATA_BLOB *utf8_blob,
2079                                                 const uint32_t pwdProperties,
2080                                                 const uint32_t minPwdLength)
2081 {
2082         const char *utf8_pw = (const char *)utf8_blob->data;
2083         size_t utf8_len = strlen_m(utf8_pw);
2084         char *password_script = NULL;
2085
2086         /* checks if the "minPwdLength" property is satisfied */
2087         if (minPwdLength > utf8_len) {
2088                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2089         }
2090
2091         /* checks the password complexity */
2092         if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
2093                 return SAMR_VALIDATION_STATUS_SUCCESS;
2094         }
2095
2096         if (utf8_len == 0) {
2097                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2098         }
2099
2100         password_script = lpcfg_check_password_script(lp_ctx, mem_ctx);
2101         if (password_script != NULL && *password_script != '\0') {
2102                 int check_ret = 0;
2103                 int error = 0;
2104                 struct tevent_context *event_ctx = NULL;
2105                 struct tevent_req *req = NULL;
2106                 int cps_stdin = -1;
2107                 const char * const cmd[4] = {
2108                         "/bin/sh", "-c",
2109                         password_script,
2110                         NULL
2111                 };
2112
2113                 event_ctx = tevent_context_init(mem_ctx);
2114                 if (event_ctx == NULL) {
2115                         TALLOC_FREE(password_script);
2116                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2117                 }
2118
2119                 /* Gives a warning after 1 second, terminates after 10 */
2120                 tevent_add_timer(event_ctx, event_ctx,
2121                                  tevent_timeval_current_ofs(1, 0),
2122                                  pwd_timeout_debug, NULL);
2123
2124                 check_ret = setenv("SAMBA_CPS_ACCOUNT_NAME", account_name, 1);
2125                 if (check_ret != 0) {
2126                         TALLOC_FREE(password_script);
2127                         TALLOC_FREE(event_ctx);
2128                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2129                 }
2130                 if (user_principal_name != NULL) {
2131                         check_ret = setenv("SAMBA_CPS_USER_PRINCIPAL_NAME",
2132                                            user_principal_name, 1);
2133                 } else {
2134                         unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2135                 }
2136                 if (check_ret != 0) {
2137                         TALLOC_FREE(password_script);
2138                         TALLOC_FREE(event_ctx);
2139                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2140                 }
2141                 if (full_name != NULL) {
2142                         check_ret = setenv("SAMBA_CPS_FULL_NAME", full_name, 1);
2143                 } else {
2144                         unsetenv("SAMBA_CPS_FULL_NAME");
2145                 }
2146                 if (check_ret != 0) {
2147                         TALLOC_FREE(password_script);
2148                         TALLOC_FREE(event_ctx);
2149                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2150                 }
2151
2152                 req = samba_runcmd_send(event_ctx, event_ctx,
2153                                         tevent_timeval_current_ofs(10, 0),
2154                                         100, 100, cmd, NULL);
2155                 unsetenv("SAMBA_CPS_ACCOUNT_NAME");
2156                 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2157                 unsetenv("SAMBA_CPS_FULL_NAME");
2158                 if (req == NULL) {
2159                         TALLOC_FREE(password_script);
2160                         TALLOC_FREE(event_ctx);
2161                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2162                 }
2163
2164                 cps_stdin = samba_runcmd_export_stdin(req);
2165
2166                 if (write(cps_stdin, utf8_pw, utf8_len) != utf8_len) {
2167                         close(cps_stdin);
2168                         cps_stdin = -1;
2169                         TALLOC_FREE(password_script);
2170                         TALLOC_FREE(event_ctx);
2171                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2172                 }
2173
2174                 close(cps_stdin);
2175                 cps_stdin = -1;
2176
2177                 if (!tevent_req_poll(req, event_ctx)) {
2178                         TALLOC_FREE(password_script);
2179                         TALLOC_FREE(event_ctx);
2180                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2181                 }
2182
2183                 check_ret = samba_runcmd_recv(req, &error);
2184                 TALLOC_FREE(event_ctx);
2185
2186                 if (error == ETIMEDOUT) {
2187                         DEBUG(0, ("check_password_complexity: check password script took too long!\n"));
2188                         TALLOC_FREE(password_script);
2189                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2190                 }
2191                 DEBUG(5,("check_password_complexity: check password script (%s) "
2192                          "returned [%d]\n", password_script, check_ret));
2193
2194                 if (check_ret != 0) {
2195                         DEBUG(1,("check_password_complexity: "
2196                                  "check password script said new password is not good "
2197                                  "enough!\n"));
2198                         TALLOC_FREE(password_script);
2199                         return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2200                 }
2201
2202                 TALLOC_FREE(password_script);
2203                 return SAMR_VALIDATION_STATUS_SUCCESS;
2204         }
2205
2206         TALLOC_FREE(password_script);
2207
2208         /*
2209          * Here are the standard AD password quality rules, which we
2210          * run after the script.
2211          */
2212
2213         if (!check_password_quality(utf8_pw)) {
2214                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2215         }
2216
2217         return SAMR_VALIDATION_STATUS_SUCCESS;
2218 }
2219
2220 /*
2221  * Callback for "samdb_set_password" password change
2222  */
2223 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2224 {
2225         int ret;
2226
2227         if (!ares) {
2228                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2229         }
2230
2231         if (ares->error != LDB_SUCCESS) {
2232                 ret = ares->error;
2233                 req->context = talloc_steal(req,
2234                                             ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2235                 talloc_free(ares);
2236                 return ldb_request_done(req, ret);
2237         }
2238
2239         if (ares->type != LDB_REPLY_DONE) {
2240                 talloc_free(ares);
2241                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2242         }
2243
2244         req->context = talloc_steal(req,
2245                                     ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2246         talloc_free(ares);
2247         return ldb_request_done(req, LDB_SUCCESS);
2248 }
2249
2250 /*
2251  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2252  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2253  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2254  * user change or not. The "rejectReason" gives some more information if the
2255  * change failed.
2256  *
2257  * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2258  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2259  */
2260 static NTSTATUS samdb_set_password_internal(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2261                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2262                             const DATA_BLOB *new_password,
2263                             const struct samr_Password *lmNewHash,
2264                             const struct samr_Password *ntNewHash,
2265                             const struct samr_Password *lmOldHash,
2266                             const struct samr_Password *ntOldHash,
2267                             enum samPwdChangeReason *reject_reason,
2268                             struct samr_DomInfo1 **_dominfo,
2269                             bool permit_interdomain_trust)
2270 {
2271         struct ldb_message *msg;
2272         struct ldb_message_element *el;
2273         struct ldb_request *req;
2274         struct dsdb_control_password_change_status *pwd_stat = NULL;
2275         int ret;
2276         bool hash_values = false;
2277         NTSTATUS status = NT_STATUS_OK;
2278
2279 #define CHECK_RET(x) \
2280         if (x != LDB_SUCCESS) { \
2281                 talloc_free(msg); \
2282                 return NT_STATUS_NO_MEMORY; \
2283         }
2284
2285         msg = ldb_msg_new(mem_ctx);
2286         if (msg == NULL) {
2287                 return NT_STATUS_NO_MEMORY;
2288         }
2289         msg->dn = user_dn;
2290         if ((new_password != NULL)
2291                         && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2292                 /* we have the password as plaintext UTF16 */
2293                 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2294                                             new_password, NULL));
2295                 el = ldb_msg_find_element(msg, "clearTextPassword");
2296                 el->flags = LDB_FLAG_MOD_REPLACE;
2297         } else if ((new_password == NULL)
2298                         && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2299                 /* we have a password as LM and/or NT hash */
2300                 if (lmNewHash != NULL) {
2301                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2302                                 "dBCSPwd", lmNewHash));
2303                         el = ldb_msg_find_element(msg, "dBCSPwd");
2304                         el->flags = LDB_FLAG_MOD_REPLACE;
2305                 }
2306                 if (ntNewHash != NULL) {
2307                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2308                                 "unicodePwd", ntNewHash));
2309                         el = ldb_msg_find_element(msg, "unicodePwd");
2310                         el->flags = LDB_FLAG_MOD_REPLACE;
2311                 }
2312                 hash_values = true;
2313         } else {
2314                 /* the password wasn't specified correctly */
2315                 talloc_free(msg);
2316                 return NT_STATUS_INVALID_PARAMETER;
2317         }
2318
2319         /* build modify request */
2320         ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2321                                 samdb_set_password_callback, NULL);
2322         if (ret != LDB_SUCCESS) {
2323                 talloc_free(msg);
2324                 return NT_STATUS_NO_MEMORY;
2325         }
2326
2327         /* A password change operation */
2328         if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2329                 struct dsdb_control_password_change *change;
2330
2331                 change = talloc(req, struct dsdb_control_password_change);
2332                 if (change == NULL) {
2333                         talloc_free(req);
2334                         talloc_free(msg);
2335                         return NT_STATUS_NO_MEMORY;
2336                 }
2337
2338                 change->old_nt_pwd_hash = ntOldHash;
2339                 change->old_lm_pwd_hash = lmOldHash;
2340
2341                 ret = ldb_request_add_control(req,
2342                                               DSDB_CONTROL_PASSWORD_CHANGE_OID,
2343                                               true, change);
2344                 if (ret != LDB_SUCCESS) {
2345                         talloc_free(req);
2346                         talloc_free(msg);
2347                         return NT_STATUS_NO_MEMORY;
2348                 }
2349         }
2350         if (hash_values) {
2351                 ret = ldb_request_add_control(req,
2352                                               DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2353                                               true, NULL);
2354                 if (ret != LDB_SUCCESS) {
2355                         talloc_free(req);
2356                         talloc_free(msg);
2357                         return NT_STATUS_NO_MEMORY;
2358                 }
2359         }
2360         if (permit_interdomain_trust) {
2361                 ret = ldb_request_add_control(req,
2362                                               DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
2363                                               false, NULL);
2364                 if (ret != LDB_SUCCESS) {
2365                         talloc_free(req);
2366                         talloc_free(msg);
2367                         return NT_STATUS_NO_MEMORY;
2368                 }
2369         }
2370         ret = ldb_request_add_control(req,
2371                                       DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2372                                       true, NULL);
2373         if (ret != LDB_SUCCESS) {
2374                 talloc_free(req);
2375                 talloc_free(msg);
2376                 return NT_STATUS_NO_MEMORY;
2377         }
2378
2379         ret = dsdb_autotransaction_request(ldb, req);
2380
2381         if (req->context != NULL) {
2382                 struct ldb_control *control = talloc_get_type_abort(req->context,
2383                                                                     struct ldb_control);
2384                 pwd_stat = talloc_get_type_abort(control->data,
2385                                                  struct dsdb_control_password_change_status);
2386                 talloc_steal(mem_ctx, pwd_stat);
2387         }
2388
2389         talloc_free(req);
2390         talloc_free(msg);
2391
2392         /* Sets the domain info (if requested) */
2393         if (_dominfo != NULL) {
2394                 struct samr_DomInfo1 *dominfo;
2395
2396                 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2397                 if (dominfo == NULL) {
2398                         return NT_STATUS_NO_MEMORY;
2399                 }
2400
2401                 if (pwd_stat != NULL) {
2402                         dominfo->min_password_length     = pwd_stat->domain_data.minPwdLength;
2403                         dominfo->password_properties     = pwd_stat->domain_data.pwdProperties;
2404                         dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2405                         dominfo->max_password_age        = pwd_stat->domain_data.maxPwdAge;
2406                         dominfo->min_password_age        = pwd_stat->domain_data.minPwdAge;
2407                 }
2408
2409                 *_dominfo = dominfo;
2410         }
2411
2412         if (reject_reason != NULL) {
2413                 if (pwd_stat != NULL) {
2414                         *reject_reason = pwd_stat->reject_reason;
2415                 } else {
2416                         *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2417                 }
2418         }
2419
2420         if (pwd_stat != NULL) {
2421                 talloc_free(pwd_stat);
2422         }
2423
2424         if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2425                 const char *errmsg = ldb_errstring(ldb);
2426                 char *endptr = NULL;
2427                 WERROR werr = WERR_GEN_FAILURE;
2428                 status = NT_STATUS_UNSUCCESSFUL;
2429                 if (errmsg != NULL) {
2430                         werr = W_ERROR(strtol(errmsg, &endptr, 16));
2431                         DBG_WARNING("%s\n", errmsg);
2432                 }
2433                 if (endptr != errmsg) {
2434                         if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2435                                 status = NT_STATUS_WRONG_PASSWORD;
2436                         }
2437                         if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2438                                 status = NT_STATUS_PASSWORD_RESTRICTION;
2439                         }
2440                 }
2441         } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2442                 /* don't let the caller know if an account doesn't exist */
2443                 status = NT_STATUS_WRONG_PASSWORD;
2444         } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2445                 status = NT_STATUS_ACCESS_DENIED;
2446         } else if (ret != LDB_SUCCESS) {
2447                 DEBUG(1, ("Failed to set password on %s: %s\n",
2448                           ldb_dn_get_linearized(user_dn),
2449                           ldb_errstring(ldb)));
2450                 status = NT_STATUS_UNSUCCESSFUL;
2451         }
2452
2453         return status;
2454 }
2455
2456 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2457                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2458                             const DATA_BLOB *new_password,
2459                             const struct samr_Password *lmNewHash,
2460                             const struct samr_Password *ntNewHash,
2461                             const struct samr_Password *lmOldHash,
2462                             const struct samr_Password *ntOldHash,
2463                             enum samPwdChangeReason *reject_reason,
2464                             struct samr_DomInfo1 **_dominfo)
2465 {
2466         return samdb_set_password_internal(ldb, mem_ctx,
2467                             user_dn, domain_dn,
2468                             new_password,
2469                             lmNewHash, ntNewHash,
2470                             lmOldHash, ntOldHash,
2471                             reject_reason, _dominfo,
2472                             false); /* reject trusts */
2473 }
2474
2475 /*
2476  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2477  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2478  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2479  * user change or not. The "rejectReason" gives some more information if the
2480  * change failed.
2481  *
2482  * This wrapper function for "samdb_set_password" takes a SID as input rather
2483  * than a user DN.
2484  *
2485  * This call encapsulates a new LDB transaction for changing the password;
2486  * therefore the user hasn't to start a new one.
2487  *
2488  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2489  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2490  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2491  *   NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2492  */
2493 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2494                                 const struct dom_sid *user_sid,
2495                                 const uint32_t *new_version, /* optional for trusts */
2496                                 const DATA_BLOB *new_password,
2497                                 const struct samr_Password *lmNewHash,
2498                                 const struct samr_Password *ntNewHash,
2499                                 const struct samr_Password *lmOldHash,
2500                                 const struct samr_Password *ntOldHash,
2501                                 enum samPwdChangeReason *reject_reason,
2502                                 struct samr_DomInfo1 **_dominfo) 
2503 {
2504         TALLOC_CTX *frame = talloc_stackframe();
2505         NTSTATUS nt_status;
2506         const char * const user_attrs[] = {
2507                 "userAccountControl",
2508                 "sAMAccountName",
2509                 NULL
2510         };
2511         struct ldb_message *user_msg = NULL;
2512         int ret;
2513         uint32_t uac = 0;
2514
2515         ret = ldb_transaction_start(ldb);
2516         if (ret != LDB_SUCCESS) {
2517                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2518                 TALLOC_FREE(frame);
2519                 return NT_STATUS_TRANSACTION_ABORTED;
2520         }
2521
2522         ret = dsdb_search_one(ldb, frame, &user_msg, ldb_get_default_basedn(ldb),
2523                               LDB_SCOPE_SUBTREE, user_attrs, 0,
2524                               "(&(objectSid=%s)(objectClass=user))",
2525                               ldap_encode_ndr_dom_sid(frame, user_sid));
2526         if (ret != LDB_SUCCESS) {
2527                 ldb_transaction_cancel(ldb);
2528                 DEBUG(3, ("samdb_set_password_sid: SID[%s] not found in samdb %s - %s, "
2529                           "returning NO_SUCH_USER\n",
2530                           dom_sid_string(frame, user_sid),
2531                           ldb_strerror(ret), ldb_errstring(ldb)));
2532                 TALLOC_FREE(frame);
2533                 return NT_STATUS_NO_SUCH_USER;
2534         }
2535
2536         uac = ldb_msg_find_attr_as_uint(user_msg, "userAccountControl", 0);
2537         if (!(uac & UF_ACCOUNT_TYPE_MASK)) {
2538                 ldb_transaction_cancel(ldb);
2539                 DEBUG(1, ("samdb_set_password_sid: invalid "
2540                           "userAccountControl[0x%08X] for SID[%s] DN[%s], "
2541                           "returning NO_SUCH_USER\n",
2542                           (unsigned)uac, dom_sid_string(frame, user_sid),
2543                           ldb_dn_get_linearized(user_msg->dn)));
2544                 TALLOC_FREE(frame);
2545                 return NT_STATUS_NO_SUCH_USER;
2546         }
2547
2548         if (uac & UF_INTERDOMAIN_TRUST_ACCOUNT) {
2549                 const char * const tdo_attrs[] = {
2550                         "trustAuthIncoming",
2551                         "trustDirection",
2552                         NULL
2553                 };
2554                 struct ldb_message *tdo_msg = NULL;
2555                 const char *account_name = NULL;
2556                 uint32_t trust_direction;
2557                 uint32_t i;
2558                 const struct ldb_val *old_val = NULL;
2559                 struct trustAuthInOutBlob old_blob = {
2560                         .count = 0,
2561                 };
2562                 uint32_t old_version = 0;
2563                 struct AuthenticationInformation *old_version_a = NULL;
2564                 uint32_t _new_version = 0;
2565                 struct trustAuthInOutBlob new_blob = {
2566                         .count = 0,
2567                 };
2568                 struct ldb_val new_val = {
2569                         .length = 0,
2570                 };
2571                 struct timeval tv = timeval_current();
2572                 NTTIME now = timeval_to_nttime(&tv);
2573                 enum ndr_err_code ndr_err;
2574
2575                 if (new_password == NULL && ntNewHash == NULL) {
2576                         ldb_transaction_cancel(ldb);
2577                         DEBUG(1, ("samdb_set_password_sid: "
2578                                   "no new password provided "
2579                                   "sAMAccountName for SID[%s] DN[%s], "
2580                                   "returning INVALID_PARAMETER\n",
2581                                   dom_sid_string(frame, user_sid),
2582                                   ldb_dn_get_linearized(user_msg->dn)));
2583                         TALLOC_FREE(frame);
2584                         return NT_STATUS_INVALID_PARAMETER;
2585                 }
2586
2587                 if (new_password != NULL && ntNewHash != NULL) {
2588                         ldb_transaction_cancel(ldb);
2589                         DEBUG(1, ("samdb_set_password_sid: "
2590                                   "two new passwords provided "
2591                                   "sAMAccountName for SID[%s] DN[%s], "
2592                                   "returning INVALID_PARAMETER\n",
2593                                   dom_sid_string(frame, user_sid),
2594                                   ldb_dn_get_linearized(user_msg->dn)));
2595                         TALLOC_FREE(frame);
2596                         return NT_STATUS_INVALID_PARAMETER;
2597                 }
2598
2599                 if (new_password != NULL && (new_password->length % 2)) {
2600                         ldb_transaction_cancel(ldb);
2601                         DEBUG(2, ("samdb_set_password_sid: "
2602                                   "invalid utf16 length (%zu) "
2603                                   "sAMAccountName for SID[%s] DN[%s], "
2604                                   "returning WRONG_PASSWORD\n",
2605                                   new_password->length,
2606                                   dom_sid_string(frame, user_sid),
2607                                   ldb_dn_get_linearized(user_msg->dn)));
2608                         TALLOC_FREE(frame);
2609                         return NT_STATUS_WRONG_PASSWORD;
2610                 }
2611
2612                 if (new_password != NULL && new_password->length >= 500) {
2613                         ldb_transaction_cancel(ldb);
2614                         DEBUG(2, ("samdb_set_password_sid: "
2615                                   "utf16 password too long (%zu) "
2616                                   "sAMAccountName for SID[%s] DN[%s], "
2617                                   "returning WRONG_PASSWORD\n",
2618                                   new_password->length,
2619                                   dom_sid_string(frame, user_sid),
2620                                   ldb_dn_get_linearized(user_msg->dn)));
2621                         TALLOC_FREE(frame);
2622                         return NT_STATUS_WRONG_PASSWORD;
2623                 }
2624
2625                 account_name = ldb_msg_find_attr_as_string(user_msg,
2626                                                         "sAMAccountName", NULL);
2627                 if (account_name == NULL) {
2628                         ldb_transaction_cancel(ldb);
2629                         DEBUG(1, ("samdb_set_password_sid: missing "
2630                                   "sAMAccountName for SID[%s] DN[%s], "
2631                                   "returning NO_SUCH_USER\n",
2632                                   dom_sid_string(frame, user_sid),
2633                                   ldb_dn_get_linearized(user_msg->dn)));
2634                         TALLOC_FREE(frame);
2635                         return NT_STATUS_NO_SUCH_USER;
2636                 }
2637
2638                 nt_status = dsdb_trust_search_tdo_by_type(ldb,
2639                                                           SEC_CHAN_DOMAIN,
2640                                                           account_name,
2641                                                           tdo_attrs,
2642                                                           frame, &tdo_msg);
2643                 if (!NT_STATUS_IS_OK(nt_status)) {
2644                         ldb_transaction_cancel(ldb);
2645                         DEBUG(1, ("samdb_set_password_sid: dsdb_trust_search_tdo "
2646                                   "failed(%s) for sAMAccountName[%s] SID[%s] DN[%s], "
2647                                   "returning INTERNAL_DB_CORRUPTION\n",
2648                                   nt_errstr(nt_status), account_name,
2649                                   dom_sid_string(frame, user_sid),
2650                                   ldb_dn_get_linearized(user_msg->dn)));
2651                         TALLOC_FREE(frame);
2652                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
2653                 }
2654
2655                 trust_direction = ldb_msg_find_attr_as_int(tdo_msg,
2656                                                            "trustDirection", 0);
2657                 if (!(trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {
2658                         ldb_transaction_cancel(ldb);
2659                         DEBUG(1, ("samdb_set_password_sid: direction[0x%08X] is "
2660                                   "not inbound for sAMAccountName[%s] "
2661                                   "DN[%s] TDO[%s], "
2662                                   "returning INTERNAL_DB_CORRUPTION\n",
2663                                   (unsigned)trust_direction,
2664                                   account_name,
2665                                   ldb_dn_get_linearized(user_msg->dn),
2666                                   ldb_dn_get_linearized(tdo_msg->dn)));
2667                         TALLOC_FREE(frame);
2668                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
2669                 }
2670
2671                 old_val = ldb_msg_find_ldb_val(tdo_msg, "trustAuthIncoming");
2672                 if (old_val != NULL) {
2673                         ndr_err = ndr_pull_struct_blob(old_val, frame, &old_blob,
2674                                         (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2675                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2676                                 ldb_transaction_cancel(ldb);
2677                                 DEBUG(1, ("samdb_set_password_sid: "
2678                                           "failed(%s) to parse "
2679                                           "trustAuthOutgoing sAMAccountName[%s] "
2680                                           "DN[%s] TDO[%s], "
2681                                           "returning INTERNAL_DB_CORRUPTION\n",
2682                                           ndr_map_error2string(ndr_err),
2683                                           account_name,
2684                                           ldb_dn_get_linearized(user_msg->dn),
2685                                           ldb_dn_get_linearized(tdo_msg->dn)));
2686
2687                                 TALLOC_FREE(frame);
2688                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2689                         }
2690                 }
2691
2692                 for (i = old_blob.current.count; i > 0; i--) {
2693                         struct AuthenticationInformation *a =
2694                                 &old_blob.current.array[i - 1];
2695
2696                         switch (a->AuthType) {
2697                         case TRUST_AUTH_TYPE_NONE:
2698                                 if (i == old_blob.current.count) {
2699                                         /*
2700                                          * remove TRUST_AUTH_TYPE_NONE at the
2701                                          * end
2702                                          */
2703                                         old_blob.current.count--;
2704                                 }
2705                                 break;
2706
2707                         case TRUST_AUTH_TYPE_VERSION:
2708                                 old_version_a = a;
2709                                 old_version = a->AuthInfo.version.version;
2710                                 break;
2711
2712                         case TRUST_AUTH_TYPE_CLEAR:
2713                                 break;
2714
2715                         case TRUST_AUTH_TYPE_NT4OWF:
2716                                 break;
2717                         }
2718                 }
2719
2720                 if (new_version == NULL) {
2721                         _new_version = 0;
2722                         new_version = &_new_version;
2723                 }
2724
2725                 if (old_version_a != NULL && *new_version != (old_version + 1)) {
2726                         old_version_a->LastUpdateTime = now;
2727                         old_version_a->AuthType = TRUST_AUTH_TYPE_NONE;
2728                 }
2729
2730                 new_blob.count = MAX(old_blob.current.count, 2);
2731                 new_blob.current.array = talloc_zero_array(frame,
2732                                                 struct AuthenticationInformation,
2733                                                 new_blob.count);
2734                 if (new_blob.current.array == NULL) {
2735                         ldb_transaction_cancel(ldb);
2736                         TALLOC_FREE(frame);
2737                         return NT_STATUS_NO_MEMORY;
2738                 }
2739                 new_blob.previous.array = talloc_zero_array(frame,
2740                                                 struct AuthenticationInformation,
2741                                                 new_blob.count);
2742                 if (new_blob.current.array == NULL) {
2743                         ldb_transaction_cancel(ldb);
2744                         TALLOC_FREE(frame);
2745                         return NT_STATUS_NO_MEMORY;
2746                 }
2747
2748                 for (i = 0; i < old_blob.current.count; i++) {
2749                         struct AuthenticationInformation *o =
2750                                 &old_blob.current.array[i];
2751                         struct AuthenticationInformation *p =
2752                                 &new_blob.previous.array[i];
2753
2754                         *p = *o;
2755                         new_blob.previous.count++;
2756                 }
2757                 for (; i < new_blob.count; i++) {
2758                         struct AuthenticationInformation *pi =
2759                                 &new_blob.previous.array[i];
2760
2761                         if (i == 0) {
2762                                 /*
2763                                  * new_blob.previous is still empty so
2764                                  * we'll do new_blob.previous = new_blob.current
2765                                  * below.
2766                                  */
2767                                 break;
2768                         }
2769
2770                         pi->LastUpdateTime = now;
2771                         pi->AuthType = TRUST_AUTH_TYPE_NONE;
2772                         new_blob.previous.count++;
2773                 }
2774
2775                 for (i = 0; i < new_blob.count; i++) {
2776                         struct AuthenticationInformation *ci =
2777                                 &new_blob.current.array[i];
2778
2779                         ci->LastUpdateTime = now;
2780                         switch (i) {
2781                         case 0:
2782                                 if (ntNewHash != NULL) {
2783                                         ci->AuthType = TRUST_AUTH_TYPE_NT4OWF;
2784                                         ci->AuthInfo.nt4owf.password = *ntNewHash;
2785                                         break;
2786                                 }
2787
2788                                 ci->AuthType = TRUST_AUTH_TYPE_CLEAR;
2789                                 ci->AuthInfo.clear.size = new_password->length;
2790                                 ci->AuthInfo.clear.password = new_password->data;
2791                                 break;
2792                         case 1:
2793                                 ci->AuthType = TRUST_AUTH_TYPE_VERSION;
2794                                 ci->AuthInfo.version.version = *new_version;
2795                                 break;
2796                         default:
2797                                 ci->AuthType = TRUST_AUTH_TYPE_NONE;
2798                                 break;
2799                         }
2800
2801                         new_blob.current.count++;
2802                 }
2803
2804                 if (new_blob.previous.count == 0) {
2805                         TALLOC_FREE(new_blob.previous.array);
2806                         new_blob.previous = new_blob.current;
2807                 }
2808
2809                 ndr_err = ndr_push_struct_blob(&new_val, frame, &new_blob,
2810                                 (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2811                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2812                         ldb_transaction_cancel(ldb);
2813                         DEBUG(1, ("samdb_set_password_sid: "
2814                                   "failed(%s) to generate "
2815                                   "trustAuthOutgoing sAMAccountName[%s] "
2816                                   "DN[%s] TDO[%s], "
2817                                   "returning UNSUCCESSFUL\n",
2818                                   ndr_map_error2string(ndr_err),
2819                                   account_name,
2820                                   ldb_dn_get_linearized(user_msg->dn),
2821                                   ldb_dn_get_linearized(tdo_msg->dn)));
2822                         TALLOC_FREE(frame);
2823                         return NT_STATUS_UNSUCCESSFUL;
2824                 }
2825
2826                 tdo_msg->num_elements = 0;
2827                 TALLOC_FREE(tdo_msg->elements);
2828
2829                 ret = ldb_msg_add_empty(tdo_msg, "trustAuthIncoming",
2830                                         LDB_FLAG_MOD_REPLACE, NULL);
2831                 if (ret != LDB_SUCCESS) {
2832                         ldb_transaction_cancel(ldb);
2833                         TALLOC_FREE(frame);
2834                         return NT_STATUS_NO_MEMORY;
2835                 }
2836                 ret = ldb_msg_add_value(tdo_msg, "trustAuthIncoming",
2837                                         &new_val, NULL);
2838                 if (ret != LDB_SUCCESS) {
2839                         ldb_transaction_cancel(ldb);
2840                         TALLOC_FREE(frame);
2841                         return NT_STATUS_NO_MEMORY;
2842                 }
2843
2844                 ret = ldb_modify(ldb, tdo_msg);
2845                 if (ret != LDB_SUCCESS) {
2846                         nt_status = dsdb_ldb_err_to_ntstatus(ret);
2847                         ldb_transaction_cancel(ldb);
2848                         DEBUG(1, ("samdb_set_password_sid: "
2849                                   "failed to replace "
2850                                   "trustAuthOutgoing sAMAccountName[%s] "
2851                                   "DN[%s] TDO[%s], "
2852                                   "%s - %s\n",
2853                                   account_name,
2854                                   ldb_dn_get_linearized(user_msg->dn),
2855                                   ldb_dn_get_linearized(tdo_msg->dn),
2856                                   nt_errstr(nt_status), ldb_errstring(ldb)));
2857                         TALLOC_FREE(frame);
2858                         return nt_status;
2859                 }
2860         }
2861
2862         nt_status = samdb_set_password_internal(ldb, mem_ctx,
2863                                                 user_msg->dn, NULL,
2864                                                 new_password,
2865                                                 lmNewHash, ntNewHash,
2866                                                 lmOldHash, ntOldHash,
2867                                                 reject_reason, _dominfo,
2868                                                 true); /* permit trusts */
2869         if (!NT_STATUS_IS_OK(nt_status)) {
2870                 ldb_transaction_cancel(ldb);
2871                 TALLOC_FREE(frame);
2872                 return nt_status;
2873         }
2874
2875         ret = ldb_transaction_commit(ldb);
2876         if (ret != LDB_SUCCESS) {
2877                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2878                          ldb_dn_get_linearized(user_msg->dn),
2879                          ldb_errstring(ldb)));
2880                 TALLOC_FREE(frame);
2881                 return NT_STATUS_TRANSACTION_ABORTED;
2882         }
2883
2884         TALLOC_FREE(frame);
2885         return NT_STATUS_OK;
2886 }
2887
2888
2889 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2890                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2891 {
2892         struct ldb_message *msg;
2893         struct ldb_dn *basedn;
2894         char *sidstr;
2895         int ret;
2896
2897         sidstr = dom_sid_string(mem_ctx, sid);
2898         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2899
2900         /* We might have to create a ForeignSecurityPrincipal, even if this user
2901          * is in our own domain */
2902
2903         msg = ldb_msg_new(sidstr);
2904         if (msg == NULL) {
2905                 talloc_free(sidstr);
2906                 return NT_STATUS_NO_MEMORY;
2907         }
2908
2909         ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2910                                 ldb_get_default_basedn(sam_ctx),
2911                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2912                                 &basedn);
2913         if (ret != LDB_SUCCESS) {
2914                 DEBUG(0, ("Failed to find DN for "
2915                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2916                 talloc_free(sidstr);
2917                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2918         }
2919
2920         /* add core elements to the ldb_message for the alias */
2921         msg->dn = basedn;
2922         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2923                 talloc_free(sidstr);
2924                 return NT_STATUS_NO_MEMORY;
2925         }
2926
2927         ret = ldb_msg_add_string(msg, "objectClass",
2928                                  "foreignSecurityPrincipal");
2929         if (ret != LDB_SUCCESS) {
2930                 talloc_free(sidstr);
2931                 return NT_STATUS_NO_MEMORY;
2932         }
2933
2934         /* create the alias */
2935         ret = ldb_add(sam_ctx, msg);
2936         if (ret != LDB_SUCCESS) {
2937                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2938                          "record %s: %s\n", 
2939                          ldb_dn_get_linearized(msg->dn),
2940                          ldb_errstring(sam_ctx)));
2941                 talloc_free(sidstr);
2942                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2943         }
2944
2945         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2946         talloc_free(sidstr);
2947
2948         return NT_STATUS_OK;
2949 }
2950
2951
2952 /*
2953   Find the DN of a domain, assuming it to be a dotted.dns name
2954 */
2955
2956 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2957 {
2958         unsigned int i;
2959         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2960         const char *binary_encoded;
2961         const char * const *split_realm;
2962         struct ldb_dn *dn;
2963
2964         if (!tmp_ctx) {
2965                 return NULL;
2966         }
2967
2968         split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
2969         if (!split_realm) {
2970                 talloc_free(tmp_ctx);
2971                 return NULL;
2972         }
2973         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2974         for (i=0; split_realm[i]; i++) {
2975                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2976                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2977                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2978                                   binary_encoded, ldb_dn_get_linearized(dn)));
2979                         talloc_free(tmp_ctx);
2980                         return NULL;
2981                 }
2982         }
2983         if (!ldb_dn_validate(dn)) {
2984                 DEBUG(2, ("Failed to validated DN %s\n",
2985                           ldb_dn_get_linearized(dn)));
2986                 talloc_free(tmp_ctx);
2987                 return NULL;
2988         }
2989         talloc_free(tmp_ctx);
2990         return dn;
2991 }
2992
2993
2994 /*
2995   Find the DNS equivalent of a DN, in dotted DNS form
2996 */
2997 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
2998 {
2999         int i, num_components = ldb_dn_get_comp_num(dn);
3000         char *dns_name = talloc_strdup(mem_ctx, "");
3001         if (dns_name == NULL) {
3002                 return NULL;
3003         }
3004
3005         for (i=0; i<num_components; i++) {
3006                 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
3007                 char *s;
3008                 if (v == NULL) {
3009                         talloc_free(dns_name);
3010                         return NULL;
3011                 }
3012                 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
3013                                                   (int)v->length, (int)v->length, (char *)v->data);
3014                 if (s == NULL) {
3015                         talloc_free(dns_name);
3016                         return NULL;
3017                 }
3018                 dns_name = s;
3019         }
3020
3021         /* remove the last '.' */
3022         if (dns_name[0] != 0) {
3023                 dns_name[strlen(dns_name)-1] = 0;
3024         }
3025
3026         return dns_name;
3027 }
3028
3029 /*
3030   Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
3031   name is based on the forest DNS name
3032 */
3033 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
3034                                 TALLOC_CTX *mem_ctx,
3035                                 const struct GUID *ntds_guid)
3036 {
3037         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3038         const char *guid_str;
3039         struct ldb_dn *forest_dn;
3040         const char *dnsforest;
3041         char *ret;
3042
3043         guid_str = GUID_string(tmp_ctx, ntds_guid);
3044         if (guid_str == NULL) {
3045                 talloc_free(tmp_ctx);
3046                 return NULL;
3047         }
3048         forest_dn = ldb_get_root_basedn(samdb);
3049         if (forest_dn == NULL) {
3050                 talloc_free(tmp_ctx);
3051                 return NULL;
3052         }
3053         dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
3054         if (dnsforest == NULL) {
3055                 talloc_free(tmp_ctx);
3056                 return NULL;
3057         }
3058         ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
3059         talloc_free(tmp_ctx);
3060         return ret;
3061 }
3062
3063
3064 /*
3065   Find the DN of a domain, be it the netbios or DNS name 
3066 */
3067 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
3068                                   const char *domain_name) 
3069 {
3070         const char * const domain_ref_attrs[] = {
3071                 "ncName", NULL
3072         };
3073         const char * const domain_ref2_attrs[] = {
3074                 NULL
3075         };
3076         struct ldb_result *res_domain_ref;
3077         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
3078         /* find the domain's DN */
3079         int ret_domain = ldb_search(ldb, mem_ctx,
3080                                             &res_domain_ref, 
3081                                             samdb_partitions_dn(ldb, mem_ctx), 
3082                                             LDB_SCOPE_ONELEVEL, 
3083                                             domain_ref_attrs,
3084                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
3085                                             escaped_domain);
3086         if (ret_domain != LDB_SUCCESS) {
3087                 return NULL;
3088         }
3089
3090         if (res_domain_ref->count == 0) {
3091                 ret_domain = ldb_search(ldb, mem_ctx,
3092                                                 &res_domain_ref, 
3093                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
3094                                                 LDB_SCOPE_BASE,
3095                                                 domain_ref2_attrs,
3096                                                 "(objectclass=domain)");
3097                 if (ret_domain != LDB_SUCCESS) {
3098                         return NULL;
3099                 }
3100
3101                 if (res_domain_ref->count == 1) {
3102                         return res_domain_ref->msgs[0]->dn;
3103                 }
3104                 return NULL;
3105         }
3106
3107         if (res_domain_ref->count > 1) {
3108                 DEBUG(0,("Found %d records matching domain [%s]\n", 
3109                          ret_domain, domain_name));
3110                 return NULL;
3111         }
3112
3113         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
3114
3115 }
3116
3117
3118 /*
3119   use a GUID to find a DN
3120  */
3121 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
3122                          TALLOC_CTX *mem_ctx,
3123                          const struct GUID *guid,
3124                          uint32_t dsdb_flags,
3125                          struct ldb_dn **dn)
3126 {
3127         int ret;
3128         struct ldb_result *res;
3129         const char *attrs[] = { NULL };
3130         char *guid_str = GUID_string(mem_ctx, guid);
3131
3132         if (!guid_str) {
3133                 return ldb_operr(ldb);
3134         }
3135
3136         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3137                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3138                           DSDB_SEARCH_SHOW_EXTENDED_DN |
3139                           DSDB_SEARCH_ONE_ONLY | dsdb_flags,
3140                           "objectGUID=%s", guid_str);
3141         talloc_free(guid_str);
3142         if (ret != LDB_SUCCESS) {
3143                 return ret;
3144         }
3145
3146         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3147         talloc_free(res);
3148
3149         return LDB_SUCCESS;
3150 }
3151
3152 /*
3153   use a DN to find a GUID with a given attribute name
3154  */
3155 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
3156                               struct ldb_dn *dn, const char *attribute,
3157                               struct GUID *guid)
3158 {
3159         int ret;
3160         struct ldb_result *res;
3161         const char *attrs[2];
3162         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3163
3164         attrs[0] = attribute;
3165         attrs[1] = NULL;
3166
3167         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3168                              DSDB_SEARCH_SHOW_DELETED |
3169                              DSDB_SEARCH_SHOW_RECYCLED);
3170         if (ret != LDB_SUCCESS) {
3171                 talloc_free(tmp_ctx);
3172                 return ret;
3173         }
3174         if (res->count < 1) {
3175                 talloc_free(tmp_ctx);
3176                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3177         }
3178         *guid = samdb_result_guid(res->msgs[0], attribute);
3179         talloc_free(tmp_ctx);
3180         return LDB_SUCCESS;
3181 }
3182
3183 /*
3184   use a DN to find a GUID
3185  */
3186 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
3187                          struct ldb_dn *dn, struct GUID *guid)
3188 {
3189         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
3190 }
3191
3192
3193
3194 /*
3195  adds the given GUID to the given ldb_message. This value is added
3196  for the given attr_name (may be either "objectGUID" or "parentGUID").
3197  */
3198 int dsdb_msg_add_guid(struct ldb_message *msg,
3199                 struct GUID *guid,
3200                 const char *attr_name)
3201 {
3202         int ret;
3203         struct ldb_val v;
3204         NTSTATUS status;
3205         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
3206
3207         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
3208         if (!NT_STATUS_IS_OK(status)) {
3209                 ret = LDB_ERR_OPERATIONS_ERROR;
3210                 goto done;
3211         }
3212
3213         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
3214         if (ret != LDB_SUCCESS) {
3215                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
3216                                          attr_name));
3217                 goto done;
3218         }
3219
3220         ret = LDB_SUCCESS;
3221
3222 done:
3223         talloc_free(tmp_ctx);
3224         return ret;
3225
3226 }
3227
3228
3229 /*
3230   use a DN to find a SID
3231  */
3232 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
3233                         struct ldb_dn *dn, struct dom_sid *sid)
3234 {
3235         int ret;
3236         struct ldb_result *res;
3237         const char *attrs[] = { "objectSid", NULL };
3238         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3239         struct dom_sid *s;
3240
3241         ZERO_STRUCTP(sid);
3242
3243         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3244                              DSDB_SEARCH_SHOW_DELETED |
3245                              DSDB_SEARCH_SHOW_RECYCLED);
3246         if (ret != LDB_SUCCESS) {
3247                 talloc_free(tmp_ctx);
3248                 return ret;
3249         }
3250         if (res->count < 1) {
3251                 talloc_free(tmp_ctx);
3252                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3253         }
3254         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
3255         if (s == NULL) {
3256                 talloc_free(tmp_ctx);
3257                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3258         }
3259         *sid = *s;
3260         talloc_free(tmp_ctx);
3261         return LDB_SUCCESS;
3262 }
3263
3264 /*
3265   use a SID to find a DN
3266  */
3267 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
3268                         TALLOC_CTX *mem_ctx,
3269                         struct dom_sid *sid, struct ldb_dn **dn)
3270 {
3271         int ret;
3272         struct ldb_result *res;
3273         const char *attrs[] = { NULL };
3274         char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
3275
3276         if (!sid_str) {
3277                 return ldb_operr(ldb);
3278         }
3279
3280         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3281                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3282                           DSDB_SEARCH_SHOW_EXTENDED_DN |
3283                           DSDB_SEARCH_ONE_ONLY,
3284                           "objectSid=%s", sid_str);
3285         talloc_free(sid_str);
3286         if (ret != LDB_SUCCESS) {
3287                 return ret;
3288         }
3289
3290         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3291         talloc_free(res);
3292
3293         return LDB_SUCCESS;
3294 }
3295
3296 /*
3297   load a repsFromTo blob list for a given partition GUID
3298   attr must be "repsFrom" or "repsTo"
3299  */
3300 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3301                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
3302 {
3303         const char *attrs[] = { attr, NULL };
3304         struct ldb_result *res = NULL;
3305         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3306         unsigned int i;
3307         struct ldb_message_element *el;
3308         int ret;
3309
3310         *r = NULL;
3311         *count = 0;
3312
3313         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
3314         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3315                 /* partition hasn't been replicated yet */
3316                 return WERR_OK;
3317         }
3318         if (ret != LDB_SUCCESS) {
3319                 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
3320                 talloc_free(tmp_ctx);
3321                 return WERR_DS_DRA_INTERNAL_ERROR;
3322         }
3323
3324         el = ldb_msg_find_element(res->msgs[0], attr);
3325         if (el == NULL) {
3326                 /* it's OK to be empty */
3327                 talloc_free(tmp_ctx);
3328                 return WERR_OK;
3329         }
3330
3331         *count = el->num_values;
3332         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
3333         if (*r == NULL) {
3334                 talloc_free(tmp_ctx);
3335                 return WERR_DS_DRA_INTERNAL_ERROR;
3336         }
3337
3338         for (i=0; i<(*count); i++) {
3339                 enum ndr_err_code ndr_err;
3340                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
3341                                                mem_ctx, 
3342                                                &(*r)[i], 
3343                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3344                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3345                         talloc_free(tmp_ctx);
3346                         return WERR_DS_DRA_INTERNAL_ERROR;
3347                 }
3348         }
3349
3350         talloc_free(tmp_ctx);
3351         
3352         return WERR_OK;
3353 }
3354
3355 /*
3356   save the repsFromTo blob list for a given partition GUID
3357   attr must be "repsFrom" or "repsTo"
3358  */
3359 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3360                      const char *attr, struct repsFromToBlob *r, uint32_t count)
3361 {
3362         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3363         struct ldb_message *msg;
3364         struct ldb_message_element *el;
3365         unsigned int i;
3366
3367         msg = ldb_msg_new(tmp_ctx);
3368         msg->dn = dn;
3369         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
3370                 goto failed;
3371         }
3372
3373         el->values = talloc_array(msg, struct ldb_val, count);
3374         if (!el->values) {
3375                 goto failed;
3376         }
3377
3378         for (i=0; i<count; i++) {
3379                 struct ldb_val v;
3380                 enum ndr_err_code ndr_err;
3381
3382                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, 
3383                                                &r[i], 
3384                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3385                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3386                         goto failed;
3387                 }
3388
3389                 el->num_values++;
3390                 el->values[i] = v;
3391         }
3392
3393         if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
3394                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
3395                 goto failed;
3396         }
3397
3398         talloc_free(tmp_ctx);
3399         
3400         return WERR_OK;
3401
3402 failed:
3403         talloc_free(tmp_ctx);
3404         return WERR_DS_DRA_INTERNAL_ERROR;
3405 }
3406
3407
3408 /*
3409   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
3410   object for a partition
3411  */
3412 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
3413                                 uint64_t *uSN, uint64_t *urgent_uSN)
3414 {
3415         struct ldb_request *req;
3416         int ret;
3417         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3418         struct dsdb_control_current_partition *p_ctrl;
3419         struct ldb_result *res;
3420
3421         res = talloc_zero(tmp_ctx, struct ldb_result);
3422         if (!res) {
3423                 talloc_free(tmp_ctx);
3424                 return ldb_oom(ldb);
3425         }
3426
3427         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3428                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
3429                                    LDB_SCOPE_BASE,
3430                                    NULL, NULL,
3431                                    NULL,
3432                                    res, ldb_search_default_callback,
3433                                    NULL);
3434         if (ret != LDB_SUCCESS) {
3435                 talloc_free(tmp_ctx);
3436                 return ret;
3437         }
3438
3439         p_ctrl = talloc(req, struct dsdb_control_current_partition);
3440         if (p_ctrl == NULL) {
3441                 talloc_free(tmp_ctx);
3442                 return ldb_oom(ldb);
3443         }
3444         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
3445         p_ctrl->dn = dn;
3446         
3447         ret = ldb_request_add_control(req,
3448                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
3449                                       false, p_ctrl);
3450         if (ret != LDB_SUCCESS) {
3451                 talloc_free(tmp_ctx);
3452                 return ret;
3453         }
3454         
3455         /* Run the new request */
3456         ret = ldb_request(ldb, req);
3457         
3458         if (ret == LDB_SUCCESS) {
3459                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3460         }
3461
3462         if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
3463                 /* it hasn't been created yet, which means
3464                    an implicit value of zero */
3465                 *uSN = 0;
3466                 talloc_free(tmp_ctx);
3467                 return LDB_SUCCESS;
3468         }
3469
3470         if (ret != LDB_SUCCESS) {
3471                 talloc_free(tmp_ctx);
3472                 return ret;
3473         }
3474
3475         if (res->count < 1) {
3476                 *uSN = 0;
3477                 if (urgent_uSN) {
3478                         *urgent_uSN = 0;
3479                 }
3480         } else {
3481                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
3482                 if (urgent_uSN) {
3483                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
3484                 }
3485         }
3486
3487         talloc_free(tmp_ctx);
3488
3489         return LDB_SUCCESS;     
3490 }
3491
3492 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
3493                                                    const struct drsuapi_DsReplicaCursor2 *c2)
3494 {
3495         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3496 }
3497
3498 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
3499                                     const struct drsuapi_DsReplicaCursor *c2)
3500 {
3501         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3502 }
3503
3504
3505 /*
3506   see if a computer identified by its invocationId is a RODC
3507 */
3508 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
3509 {
3510         /* 1) find the DN for this servers NTDSDSA object
3511            2) search for the msDS-isRODC attribute
3512            3) if not present then not a RODC
3513            4) if present and TRUE then is a RODC
3514         */
3515         struct ldb_dn *config_dn;
3516         const char *attrs[] = { "msDS-isRODC", NULL };
3517         int ret;
3518         struct ldb_result *res;
3519         TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
3520
3521         config_dn = ldb_get_config_basedn(sam_ctx);
3522         if (!config_dn) {
3523                 talloc_free(tmp_ctx);
3524                 return ldb_operr(sam_ctx);
3525         }
3526
3527         ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
3528                           DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
3529
3530         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3531                 *is_rodc = false;
3532                 talloc_free(tmp_ctx);
3533                 return LDB_SUCCESS;
3534         }
3535
3536         if (ret != LDB_SUCCESS) {
3537                 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
3538                          GUID_string(tmp_ctx, objectGUID)));
3539                 *is_rodc = false;
3540                 talloc_free(tmp_ctx);
3541                 return ret;
3542         }
3543
3544         ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
3545         *is_rodc = (ret == 1);
3546
3547         talloc_free(tmp_ctx);
3548         return LDB_SUCCESS;
3549 }
3550
3551
3552 /*
3553   see if we are a RODC
3554 */
3555 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
3556 {
3557         const struct GUID *objectGUID;
3558         int ret;
3559         bool *cached;
3560
3561         /* see if we have a cached copy */
3562         cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
3563         if (cached) {
3564                 *am_rodc = *cached;
3565                 return LDB_SUCCESS;
3566         }
3567
3568         objectGUID = samdb_ntds_objectGUID(sam_ctx);
3569         if (!objectGUID) {
3570                 return ldb_operr(sam_ctx);
3571         }
3572
3573         ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
3574         if (ret != LDB_SUCCESS) {
3575                 return ret;
3576         }
3577
3578         cached = talloc(sam_ctx, bool);
3579         if (cached == NULL) {
3580                 return ldb_oom(sam_ctx);
3581         }
3582         *cached = *am_rodc;
3583
3584         ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
3585         if (ret != LDB_SUCCESS) {
3586                 talloc_free(cached);
3587                 return ldb_operr(sam_ctx);
3588         }
3589
3590         return LDB_SUCCESS;
3591 }
3592
3593 int samdb_dns_host_name(struct ldb_context *sam_ctx, const char **host_name)
3594 {
3595         const char *_host_name = NULL;
3596         const char *attrs[] = { "dnsHostName", NULL };
3597         TALLOC_CTX *tmp_ctx = NULL;
3598         int ret;
3599         struct ldb_result *res = NULL;
3600
3601         _host_name = (const char *)ldb_get_opaque(sam_ctx, "cache.dns_host_name");
3602         if (_host_name != NULL) {
3603                 *host_name = _host_name;
3604                 return LDB_SUCCESS;
3605         }
3606
3607         tmp_ctx = talloc_new(sam_ctx);
3608
3609         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, NULL, attrs, 0);
3610
3611         if (res->count != 1 || ret != LDB_SUCCESS) {
3612                 DEBUG(0, ("Failed to get rootDSE for dnsHostName: %s",
3613                           ldb_errstring(sam_ctx)));
3614                 TALLOC_FREE(tmp_ctx);
3615                 return ret;
3616         }
3617
3618
3619         _host_name = ldb_msg_find_attr_as_string(res->msgs[0],
3620                                                  "dnsHostName",
3621                                                  NULL);
3622         if (_host_name == NULL) {
3623                 DEBUG(0, ("Failed to get dnsHostName from rootDSE"));
3624                 TALLOC_FREE(tmp_ctx);
3625                 return LDB_ERR_OPERATIONS_ERROR;
3626         }
3627         ret = ldb_set_opaque(sam_ctx, "cache.dns_host_name",
3628                              discard_const_p(char *, _host_name));
3629         if (ret != LDB_SUCCESS) {
3630                 TALLOC_FREE(tmp_ctx);
3631                 return ldb_operr(sam_ctx);
3632         }
3633
3634         *host_name = talloc_steal(sam_ctx, _host_name);
3635
3636         TALLOC_FREE(tmp_ctx);
3637         return LDB_SUCCESS;
3638 }
3639
3640 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3641 {
3642         TALLOC_CTX *tmp_ctx;
3643         bool *cached;
3644
3645         tmp_ctx = talloc_new(ldb);
3646         if (tmp_ctx == NULL) {
3647                 goto failed;
3648         }
3649
3650         cached = talloc(tmp_ctx, bool);
3651         if (!cached) {
3652                 goto failed;
3653         }
3654
3655         *cached = am_rodc;
3656         if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3657                 goto failed;
3658         }
3659
3660         talloc_steal(ldb, cached);
3661         talloc_free(tmp_ctx);
3662         return true;
3663
3664 failed:
3665         DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3666         talloc_free(tmp_ctx);
3667         return false;
3668 }
3669
3670
3671 /*
3672  * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3673  * flags are DS_NTDSSETTINGS_OPT_*
3674  */
3675 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3676                                         uint32_t *options)
3677 {
3678         int rc;
3679         TALLOC_CTX *tmp_ctx;
3680         struct ldb_result *res;
3681         struct ldb_dn *site_dn;
3682         const char *attrs[] = { "options", NULL };
3683
3684         tmp_ctx = talloc_new(ldb_ctx);
3685         if (tmp_ctx == NULL)
3686                 goto failed;
3687
3688         /* Retrieve the site dn for the ldb that we
3689          * have open.  This is our local site.
3690          */
3691         site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3692         if (site_dn == NULL)
3693                 goto failed;
3694
3695         /* Perform a one level (child) search from the local
3696          * site distinguided name.   We're looking for the
3697          * "options" attribute within the nTDSSiteSettings
3698          * object
3699          */
3700         rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3701                         LDB_SCOPE_ONELEVEL, attrs,
3702                         "objectClass=nTDSSiteSettings");
3703
3704         if (rc != LDB_SUCCESS || res->count != 1)
3705                 goto failed;
3706
3707         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3708
3709         talloc_free(tmp_ctx);
3710
3711         return LDB_SUCCESS;
3712
3713 failed:
3714         DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3715         talloc_free(tmp_ctx);
3716         return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
3717 }
3718
3719 /*
3720   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
3721
3722   flags are DS_NTDS_OPTION_*
3723 */
3724 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3725 {
3726         TALLOC_CTX *tmp_ctx;
3727         const char *attrs[] = { "options", NULL };
3728         int ret;
3729         struct ldb_result *res;
3730
3731         tmp_ctx = talloc_new(ldb);
3732         if (tmp_ctx == NULL) {
3733                 goto failed;
3734         }
3735
3736         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3737         if (ret != LDB_SUCCESS) {
3738                 goto failed;
3739         }
3740
3741         if (res->count != 1) {
3742                 goto failed;
3743         }
3744
3745         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3746
3747         talloc_free(tmp_ctx);
3748
3749         return LDB_SUCCESS;
3750
3751 failed:
3752         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3753         talloc_free(tmp_ctx);
3754         return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3755 }
3756
3757 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3758 {
3759         const char *attrs[] = { "objectCategory", NULL };
3760         int ret;
3761         struct ldb_result *res;
3762
3763         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3764         if (ret != LDB_SUCCESS) {
3765                 goto failed;
3766         }
3767
3768         if (res->count != 1) {
3769                 goto failed;
3770         }
3771
3772         return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3773
3774 failed:
3775         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3776         return NULL;
3777 }
3778
3779 /*
3780  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3781  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3782  */
3783 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3784 {
3785         char **tokens, *ret;
3786         size_t i;
3787
3788         tokens = str_list_make(mem_ctx, cn, " -_");
3789         if (tokens == NULL || tokens[0] == NULL) {
3790                 return NULL;
3791         }
3792
3793         /* "tolower()" and "toupper()" should also work properly on 0x00 */
3794         tokens[0][0] = tolower(tokens[0][0]);
3795         for (i = 1; tokens[i] != NULL; i++)
3796                 tokens[i][0] = toupper(tokens[i][0]);
3797
3798         ret = talloc_strdup(mem_ctx, tokens[0]);
3799         for (i = 1; tokens[i] != NULL; i++)
3800                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3801
3802         talloc_free(tokens);
3803
3804         return ret;
3805 }
3806
3807 /*
3808  * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3809  */
3810 int dsdb_functional_level(struct ldb_context *ldb)
3811 {
3812         int *domainFunctionality =
3813                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3814         if (!domainFunctionality) {
3815                 /* this is expected during initial provision */
3816                 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3817                 return DS_DOMAIN_FUNCTION_2000;
3818         }
3819         return *domainFunctionality;
3820 }
3821
3822 /*
3823  * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3824  */
3825 int dsdb_forest_functional_level(struct ldb_context *ldb)
3826 {
3827         int *forestFunctionality =
3828                 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3829         if (!forestFunctionality) {
3830                 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3831                 return DS_DOMAIN_FUNCTION_2000;
3832         }
3833         return *forestFunctionality;
3834 }
3835
3836 /*
3837   set a GUID in an extended DN structure
3838  */
3839 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3840 {
3841         struct ldb_val v;
3842         NTSTATUS status;
3843         int ret;
3844
3845         status = GUID_to_ndr_blob(guid, dn, &v);
3846         if (!NT_STATUS_IS_OK(status)) {
3847                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3848         }
3849
3850         ret = ldb_dn_set_extended_component(dn, component_name, &v);
3851         data_blob_free(&v);
3852         return ret;
3853 }
3854
3855 /*
3856   return a GUID from a extended DN structure
3857  */
3858 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3859 {
3860         const struct ldb_val *v;
3861
3862         v = ldb_dn_get_extended_component(dn, component_name);
3863         if (v == NULL) {
3864                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3865         }
3866
3867         return GUID_from_ndr_blob(v, guid);
3868 }
3869
3870 /*
3871   return a uint64_t from a extended DN structure
3872  */
3873 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3874 {
3875         const struct ldb_val *v;
3876
3877         v = ldb_dn_get_extended_component(dn, component_name);
3878         if (v == NULL) {
3879                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3880         }
3881
3882         /* Just check we don't allow the caller to fill our stack */
3883         if (v->length >= 64) {
3884                 return NT_STATUS_INVALID_PARAMETER;
3885         } else {
3886                 char s[v->length+1];
3887                 memcpy(s, v->data, v->length);
3888                 s[v->length] = 0;
3889
3890                 *val = strtoull(s, NULL, 0);
3891         }
3892         return NT_STATUS_OK;
3893 }
3894
3895 /*
3896   return a NTTIME from a extended DN structure
3897  */
3898 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3899 {
3900         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3901 }
3902
3903 /*
3904   return a uint32_t from a extended DN structure
3905  */
3906 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3907 {
3908         const struct ldb_val *v;
3909
3910         v = ldb_dn_get_extended_component(dn, component_name);
3911         if (v == NULL) {
3912                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3913         }
3914
3915         /* Just check we don't allow the caller to fill our stack */
3916         if (v->length >= 32) {
3917                 return NT_STATUS_INVALID_PARAMETER;
3918         } else {
3919                 char s[v->length + 1];
3920                 memcpy(s, v->data, v->length);
3921                 s[v->length] = 0;
3922                 *val = strtoul(s, NULL, 0);
3923         }
3924
3925         return NT_STATUS_OK;
3926 }
3927
3928 /*
3929   return a dom_sid from a extended DN structure
3930  */
3931 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3932 {
3933         const struct ldb_val *sid_blob;
3934         enum ndr_err_code ndr_err;
3935
3936         sid_blob = ldb_dn_get_extended_component(dn, component_name);
3937         if (!sid_blob) {
3938                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3939         }
3940
3941         ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
3942                                                    (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3943         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3944                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3945                 return status;
3946         }
3947
3948         return NT_STATUS_OK;
3949 }
3950
3951
3952 /*
3953   return RMD_FLAGS directly from a ldb_dn
3954   returns 0 if not found
3955  */
3956 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3957 {
3958         uint32_t rmd_flags = 0;
3959         NTSTATUS status = dsdb_get_extended_dn_uint32(dn, &rmd_flags,
3960                                                       "RMD_FLAGS");
3961         if (NT_STATUS_IS_OK(status)) {
3962                 return rmd_flags;
3963         }
3964         return 0;
3965 }
3966
3967 /*
3968   return RMD_FLAGS directly from a ldb_val for a DN
3969   returns 0 if RMD_FLAGS is not found
3970  */
3971 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3972 {
3973         const char *p;
3974         uint32_t flags;
3975         char *end;
3976
3977         if (val->length < 13) {
3978                 return 0;
3979         }
3980         p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3981         if (!p) {
3982                 return 0;
3983         }
3984         flags = strtoul(p+11, &end, 10);
3985         if (!end || *end != '>') {
3986                 /* it must end in a > */
3987                 return 0;
3988         }
3989         return flags;
3990 }
3991
3992 /*
3993   return true if a ldb_val containing a DN in storage form is deleted
3994  */
3995 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3996 {
3997         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3998 }
3999
4000 /*
4001   return true if a ldb_val containing a DN in storage form is
4002   in the upgraded w2k3 linked attribute format
4003  */
4004 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
4005 {
4006         return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
4007 }
4008
4009 /*
4010   return a DN for a wellknown GUID
4011  */
4012 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
4013                       struct ldb_dn *nc_root, const char *wk_guid,
4014                       struct ldb_dn **wkguid_dn)
4015 {
4016         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4017         const char *attrs[] = { NULL };
4018         int ret;
4019         struct ldb_dn *dn;
4020         struct ldb_result *res;
4021
4022         /* construct the magic WKGUID DN */
4023         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
4024                             wk_guid, ldb_dn_get_linearized(nc_root));
4025         if (!wkguid_dn) {
4026                 talloc_free(tmp_ctx);
4027                 return ldb_operr(samdb);
4028         }
4029
4030         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
4031                              DSDB_SEARCH_SHOW_DELETED |
4032                              DSDB_SEARCH_SHOW_RECYCLED);
4033         if (ret != LDB_SUCCESS) {
4034                 talloc_free(tmp_ctx);
4035                 return ret;
4036         }
4037
4038         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
4039         talloc_free(tmp_ctx);
4040         return LDB_SUCCESS;
4041 }
4042
4043
4044 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
4045 {
4046         return ldb_dn_compare(*dn1, *dn2);
4047 }
4048
4049 /*
4050   find a NC root given a DN within the NC
4051  */
4052 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
4053                       struct ldb_dn **nc_root)
4054 {
4055         const char *root_attrs[] = { "namingContexts", NULL };
4056         TALLOC_CTX *tmp_ctx;
4057         int ret;
4058         struct ldb_message_element *el;
4059         struct ldb_result *root_res;
4060         unsigned int i;
4061         struct ldb_dn **nc_dns;
4062
4063         tmp_ctx = talloc_new(samdb);
4064         if (tmp_ctx == NULL) {
4065                 return ldb_oom(samdb);
4066         }
4067
4068         ret = ldb_search(samdb, tmp_ctx, &root_res,
4069                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
4070         if (ret != LDB_SUCCESS || root_res->count == 0) {
4071                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
4072                 talloc_free(tmp_ctx);
4073                 return ret;
4074         }
4075
4076         el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
4077         if ((el == NULL) || (el->num_values < 3)) {
4078                 struct ldb_message *tmp_msg;
4079
4080                 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list.\n"));
4081
4082                 /* This generates a temporary list of NCs in order to let the
4083                  * provisioning work. */
4084                 tmp_msg = ldb_msg_new(tmp_ctx);
4085                 if (tmp_msg == NULL) {
4086                         talloc_free(tmp_ctx);
4087                         return ldb_oom(samdb);
4088                 }
4089                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4090                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
4091                 if (ret != LDB_SUCCESS) {
4092                         talloc_free(tmp_ctx);
4093                         return ret;
4094                 }
4095                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4096                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
4097                 if (ret != LDB_SUCCESS) {
4098                         talloc_free(tmp_ctx);
4099                         return ret;
4100                 }
4101                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4102                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
4103                 if (ret != LDB_SUCCESS) {
4104                         talloc_free(tmp_ctx);
4105                         return ret;
4106                 }
4107                 el = &tmp_msg->elements[0];
4108         }
4109
4110        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
4111        if (!nc_dns) {
4112                talloc_free(tmp_ctx);
4113                return ldb_oom(samdb);
4114        }
4115
4116        for (i=0; i<el->num_values; i++) {
4117                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
4118                if (nc_dns[i] == NULL) {
4119                        talloc_free(tmp_ctx);
4120                        return ldb_operr(samdb);
4121                }
4122        }
4123
4124        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
4125
4126        for (i=0; i<el->num_values; i++) {
4127                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
4128                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
4129                        talloc_free(tmp_ctx);
4130                        return LDB_SUCCESS;
4131                }
4132        }
4133
4134        talloc_free(tmp_ctx);
4135        return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4136 }
4137
4138
4139 /*
4140   find the deleted objects DN for any object, by looking for the NC
4141   root, then looking up the wellknown GUID
4142  */
4143 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
4144                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
4145                                 struct ldb_dn **do_dn)
4146 {
4147         struct ldb_dn *nc_root;
4148         int ret;
4149
4150         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
4151         if (ret != LDB_SUCCESS) {
4152                 return ret;
4153         }
4154
4155         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
4156         talloc_free(nc_root);
4157         return ret;
4158 }
4159
4160 /*
4161   return the tombstoneLifetime, in days
4162  */
4163 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
4164 {
4165         struct ldb_dn *dn;
4166         dn = ldb_get_config_basedn(ldb);
4167         if (!dn) {
4168                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4169         }
4170         dn = ldb_dn_copy(ldb, dn);
4171         if (!dn) {
4172                 return ldb_operr(ldb);
4173         }
4174         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
4175          be a wellknown GUID for this */
4176         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
4177                 talloc_free(dn);
4178                 return ldb_operr(ldb);
4179         }
4180
4181         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
4182         talloc_free(dn);
4183         return LDB_SUCCESS;
4184 }
4185
4186 /*
4187   compare a ldb_val to a string case insensitively
4188  */
4189 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
4190 {
4191         size_t len = strlen(s);
4192         int ret;
4193         if (len > v->length) return 1;
4194         ret = strncasecmp(s, (const char *)v->data, v->length);
4195         if (ret != 0) return ret;
4196         if (v->length > len && v->data[len] != 0) {
4197                 return -1;
4198         }
4199         return 0;
4200 }
4201
4202
4203 /*
4204   load the UDV for a partition in v2 format
4205   The list is returned sorted, and with our local cursor added
4206  */
4207 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4208                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
4209 {
4210         static const char *attrs[] = { "replUpToDateVector", NULL };
4211         struct ldb_result *r;
4212         const struct ldb_val *ouv_value;
4213         unsigned int i;
4214         int ret;
4215         uint64_t highest_usn = 0;
4216         const struct GUID *our_invocation_id;
4217         static const struct timeval tv1970;
4218         NTTIME nt1970 = timeval_to_nttime(&tv1970);
4219
4220         ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
4221         if (ret != LDB_SUCCESS) {
4222                 return ret;
4223         }
4224
4225         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
4226         if (ouv_value) {
4227                 enum ndr_err_code ndr_err;
4228                 struct replUpToDateVectorBlob ouv;
4229
4230                 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
4231                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
4232                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4233                         talloc_free(r);
4234                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4235                 }
4236                 if (ouv.version != 2) {
4237                         /* we always store as version 2, and
4238                          * replUpToDateVector is not replicated
4239                          */
4240                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4241                 }
4242
4243                 *count = ouv.ctr.ctr2.count;
4244                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
4245         } else {
4246                 *count = 0;
4247                 *cursors = NULL;
4248         }
4249
4250         talloc_free(r);
4251
4252         our_invocation_id = samdb_ntds_invocation_id(samdb);
4253         if (!our_invocation_id) {
4254                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
4255                 talloc_free(*cursors);
4256                 return ldb_operr(samdb);
4257         }
4258
4259         ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
4260         if (ret != LDB_SUCCESS) {
4261                 /* nothing to add - this can happen after a vampire */
4262                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4263                 return LDB_SUCCESS;
4264         }
4265
4266         for (i=0; i<*count; i++) {
4267                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
4268                         (*cursors)[i].highest_usn = highest_usn;
4269                         (*cursors)[i].last_sync_success = nt1970;
4270                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4271                         return LDB_SUCCESS;
4272                 }
4273         }
4274
4275         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
4276         if (! *cursors) {
4277                 return ldb_oom(samdb);
4278         }
4279
4280         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
4281         (*cursors)[*count].highest_usn = highest_usn;
4282         (*cursors)[*count].last_sync_success = nt1970;
4283         (*count)++;
4284
4285         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4286
4287         return LDB_SUCCESS;
4288 }
4289
4290 /*
4291   load the UDV for a partition in version 1 format
4292   The list is returned sorted, and with our local cursor added
4293  */
4294 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4295                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
4296 {
4297         struct drsuapi_DsReplicaCursor2 *v2;
4298         uint32_t i;
4299         int ret;
4300
4301         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
4302         if (ret != LDB_SUCCESS) {
4303                 return ret;
4304         }
4305
4306         if (*count == 0) {
4307                 talloc_free(v2);
4308                 *cursors = NULL;
4309                 return LDB_SUCCESS;
4310         }
4311
4312         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
4313         if (*cursors == NULL) {
4314                 talloc_free(v2);
4315                 return ldb_oom(samdb);
4316         }
4317
4318         for (i=0; i<*count; i++) {
4319                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
4320                 (*cursors)[i].highest_usn = v2[i].highest_usn;
4321         }
4322         talloc_free(v2);
4323         return LDB_SUCCESS;
4324 }
4325
4326 /*
4327   add a set of controls to a ldb_request structure based on a set of
4328   flags. See util.h for a list of available flags
4329  */
4330 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
4331 {
4332         int ret;
4333         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
4334                 struct ldb_search_options_control *options;
4335                 /* Using the phantom root control allows us to search all partitions */
4336                 options = talloc(req, struct ldb_search_options_control);
4337                 if (options == NULL) {
4338                         return LDB_ERR_OPERATIONS_ERROR;
4339                 }
4340                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
4341
4342                 ret = ldb_request_add_control(req,
4343                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
4344                                               true, options);
4345                 if (ret != LDB_SUCCESS) {
4346                         return ret;
4347                 }
4348         }
4349
4350         if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
4351                 ret = ldb_request_add_control(req,
4352                                               DSDB_CONTROL_NO_GLOBAL_CATALOG,
4353                                               false, NULL);
4354                 if (ret != LDB_SUCCESS) {
4355                         return ret;
4356                 }
4357         }
4358
4359         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
4360                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
4361                 if (ret != LDB_SUCCESS) {
4362                         return ret;
4363                 }
4364         }
4365
4366         if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
4367                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
4368                 if (ret != LDB_SUCCESS) {
4369                         return ret;
4370                 }
4371         }
4372
4373         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
4374                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
4375                 if (ret != LDB_SUCCESS) {
4376                         return ret;
4377                 }
4378         }
4379
4380         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
4381                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
4382                 if (!extended_ctrl) {
4383                         return LDB_ERR_OPERATIONS_ERROR;
4384                 }
4385                 extended_ctrl->type = 1;
4386
4387                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
4388                 if (ret != LDB_SUCCESS) {
4389                         return ret;
4390                 }
4391         }
4392
4393         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
4394                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
4395                 if (ret != LDB_SUCCESS) {
4396                         return ret;
4397                 }
4398         }
4399
4400         if (dsdb_flags & DSDB_MODIFY_RELAX) {
4401                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
4402                 if (ret != LDB_SUCCESS) {
4403                         return ret;
4404                 }
4405         }
4406
4407         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
4408                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
4409                 if (ret != LDB_SUCCESS) {
4410                         return ret;
4411                 }
4412         }
4413
4414         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
4415                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
4416                 if (ret != LDB_SUCCESS) {
4417                         return ret;
4418                 }
4419         }
4420
4421         if (dsdb_flags & DSDB_TREE_DELETE) {
4422                 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
4423                 if (ret != LDB_SUCCESS) {
4424                         return ret;
4425                 }
4426         }
4427
4428         if (dsdb_flags & DSDB_PROVISION) {
4429                 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
4430                 if (ret != LDB_SUCCESS) {
4431                         return ret;
4432                 }
4433         }
4434
4435         /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
4436         if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
4437                 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
4438                 if (ret != LDB_SUCCESS) {
4439                         return ret;
4440                 }
4441         }
4442
4443         if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
4444                 /* 
4445                  * This must not be critical, as it will only be
4446                  * handled (and need to be handled) if the other
4447                  * attributes in the request bring password_hash into
4448                  * action
4449                  */
4450                 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
4451                 if (ret != LDB_SUCCESS) {
4452                         return ret;
4453                 }
4454         }
4455
4456         if (dsdb_flags & DSDB_REPLMD_VANISH_LINKS) {
4457                 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLMD_VANISH_LINKS, true, NULL);
4458                 if (ret != LDB_SUCCESS) {
4459                         return ret;
4460                 }
4461         }
4462
4463         if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
4464                 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
4465                 if (ret != LDB_SUCCESS) {
4466                         return ret;
4467                 }
4468         }
4469
4470         if (dsdb_flags & DSDB_FLAG_REPLICATED_UPDATE) {
4471                 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
4472                 if (ret != LDB_SUCCESS) {
4473                         return ret;
4474                 }
4475         }
4476
4477         return LDB_SUCCESS;
4478 }
4479
4480 /*
4481    returns true if a control with the specified "oid" exists
4482 */
4483 bool dsdb_request_has_control(struct ldb_request *req, const char *oid)
4484 {
4485         return (ldb_request_get_control(req, oid) != NULL);
4486 }
4487
4488 /*
4489   an add with a set of controls
4490 */
4491 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
4492              uint32_t dsdb_flags)
4493 {
4494         struct ldb_request *req;
4495         int ret;
4496
4497         ret = ldb_build_add_req(&req, ldb, ldb,
4498                                 message,
4499                                 NULL,
4500                                 NULL,
4501                                 ldb_op_default_callback,
4502                                 NULL);
4503
4504         if (ret != LDB_SUCCESS) return ret;
4505
4506         ret = dsdb_request_add_controls(req, dsdb_flags);
4507         if (ret != LDB_SUCCESS) {
4508                 talloc_free(req);
4509                 return ret;
4510         }
4511
4512         ret = dsdb_autotransaction_request(ldb, req);
4513
4514         talloc_free(req);
4515         return ret;
4516 }
4517
4518 /*
4519   a modify with a set of controls
4520 */
4521 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
4522                 uint32_t dsdb_flags)
4523 {
4524         struct ldb_request *req;
4525         int ret;
4526
4527         ret = ldb_build_mod_req(&req, ldb, ldb,
4528                                 message,
4529                                 NULL,
4530                                 NULL,
4531                                 ldb_op_default_callback,
4532                                 NULL);
4533
4534         if (ret != LDB_SUCCESS) return ret;
4535
4536         ret = dsdb_request_add_controls(req, dsdb_flags);
4537         if (ret != LDB_SUCCESS) {
4538                 talloc_free(req);
4539                 return ret;
4540         }
4541
4542         ret = dsdb_autotransaction_request(ldb, req);
4543
4544         talloc_free(req);
4545         return ret;
4546 }
4547
4548 /*
4549   a delete with a set of flags
4550 */
4551 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
4552                 uint32_t dsdb_flags)
4553 {
4554         struct ldb_request *req;
4555         int ret;
4556
4557         ret = ldb_build_del_req(&req, ldb, ldb,
4558                                 dn,
4559                                 NULL,
4560                                 NULL,
4561                                 ldb_op_default_callback,
4562                                 NULL);
4563
4564         if (ret != LDB_SUCCESS) return ret;
4565
4566         ret = dsdb_request_add_controls(req, dsdb_flags);
4567         if (ret != LDB_SUCCESS) {
4568                 talloc_free(req);
4569                 return ret;
4570         }
4571
4572         ret = dsdb_autotransaction_request(ldb, req);
4573
4574         talloc_free(req);
4575         return ret;
4576 }
4577
4578 /*
4579   like dsdb_modify() but set all the element flags to
4580   LDB_FLAG_MOD_REPLACE
4581  */
4582 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
4583 {
4584         unsigned int i;
4585
4586         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
4587         for (i=0;i<msg->num_elements;i++) {
4588                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
4589         }
4590
4591         return dsdb_modify(ldb, msg, dsdb_flags);
4592 }
4593
4594
4595 /*
4596   search for attrs on one DN, allowing for dsdb_flags controls
4597  */
4598 int dsdb_search_dn(struct ldb_context *ldb,
4599                    TALLOC_CTX *mem_ctx,
4600                    struct ldb_result **_result,
4601                    struct ldb_dn *basedn,
4602                    const char * const *attrs,
4603                    uint32_t dsdb_flags)
4604 {
4605         int ret;
4606         struct ldb_request *req;
4607         struct ldb_result *res;
4608
4609         res = talloc_zero(mem_ctx, struct ldb_result);
4610         if (!res) {
4611                 return ldb_oom(ldb);
4612         }
4613
4614         ret = ldb_build_search_req(&req, ldb, res,
4615                                    basedn,
4616                                    LDB_SCOPE_BASE,
4617                                    NULL,
4618                                    attrs,
4619                                    NULL,
4620                                    res,
4621                                    ldb_search_default_callback,
4622                                    NULL);
4623         if (ret != LDB_SUCCESS) {
4624                 talloc_free(res);
4625                 return ret;
4626         }
4627
4628         ret = dsdb_request_add_controls(req, dsdb_flags);
4629         if (ret != LDB_SUCCESS) {
4630                 talloc_free(res);
4631                 return ret;
4632         }
4633
4634         ret = ldb_request(ldb, req);
4635         if (ret == LDB_SUCCESS) {
4636                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4637         }
4638
4639         talloc_free(req);
4640         if (ret != LDB_SUCCESS) {
4641                 talloc_free(res);
4642                 return ret;
4643         }
4644
4645         *_result = res;
4646         return LDB_SUCCESS;
4647 }
4648
4649 /*
4650   search for attrs on one DN, by the GUID of the DN, allowing for
4651   dsdb_flags controls
4652  */
4653 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
4654                            TALLOC_CTX *mem_ctx,
4655                            struct ldb_result **_result,
4656                            const struct GUID *guid,
4657                            const char * const *attrs,
4658                            uint32_t dsdb_flags)
4659 {
4660         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4661         struct ldb_dn *dn;
4662         int ret;
4663
4664         dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
4665         if (dn == NULL) {
4666                 talloc_free(tmp_ctx);
4667                 return ldb_oom(ldb);
4668         }
4669
4670         ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
4671         talloc_free(tmp_ctx);
4672         return ret;
4673 }
4674
4675 /*
4676   general search with dsdb_flags for controls
4677  */
4678 int dsdb_search(struct ldb_context *ldb,
4679                 TALLOC_CTX *mem_ctx,
4680                 struct ldb_result **_result,
4681                 struct ldb_dn *basedn,
4682                 enum ldb_scope scope,
4683                 const char * const *attrs,
4684                 uint32_t dsdb_flags,
4685                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4686 {
4687         int ret;
4688         struct ldb_request *req;
4689         struct ldb_result *res;
4690         va_list ap;
4691         char *expression = NULL;
4692         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4693
4694         /* cross-partitions searches with a basedn break multi-domain support */
4695         SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
4696
4697         res = talloc_zero(tmp_ctx, struct ldb_result);
4698         if (!res) {
4699                 talloc_free(tmp_ctx);
4700                 return ldb_oom(ldb);
4701         }
4702
4703         if (exp_fmt) {
4704                 va_start(ap, exp_fmt);
4705                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4706                 va_end(ap);
4707
4708                 if (!expression) {
4709                         talloc_free(tmp_ctx);
4710                         return ldb_oom(ldb);
4711                 }
4712         }
4713
4714         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
4715                                    basedn,
4716                                    scope,
4717                                    expression,
4718                                    attrs,
4719                                    NULL,
4720                                    res,
4721                                    ldb_search_default_callback,
4722                                    NULL);
4723         if (ret != LDB_SUCCESS) {
4724                 talloc_free(tmp_ctx);
4725                 return ret;
4726         }
4727
4728         ret = dsdb_request_add_controls(req, dsdb_flags);
4729         if (ret != LDB_SUCCESS) {
4730                 talloc_free(tmp_ctx);
4731                 ldb_reset_err_string(ldb);
4732                 return ret;
4733         }
4734
4735         ret = ldb_request(ldb, req);
4736         if (ret == LDB_SUCCESS) {
4737                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4738         }
4739
4740         if (ret != LDB_SUCCESS) {
4741                 talloc_free(tmp_ctx);
4742                 return ret;
4743         }
4744
4745         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
4746                 if (res->count == 0) {
4747                         talloc_free(tmp_ctx);
4748                         ldb_reset_err_string(ldb);
4749                         return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4750                 }
4751                 if (res->count != 1) {
4752                         talloc_free(tmp_ctx);
4753                         ldb_reset_err_string(ldb);
4754                         return LDB_ERR_CONSTRAINT_VIOLATION;
4755                 }
4756         }
4757
4758         *_result = talloc_steal(mem_ctx, res);
4759         talloc_free(tmp_ctx);
4760
4761         return LDB_SUCCESS;
4762 }
4763
4764
4765 /*
4766   general search with dsdb_flags for controls
4767   returns exactly 1 record or an error
4768  */
4769 int dsdb_search_one(struct ldb_context *ldb,
4770                     TALLOC_CTX *mem_ctx,
4771                     struct ldb_message **msg,
4772                     struct ldb_dn *basedn,
4773                     enum ldb_scope scope,
4774                     const char * const *attrs,
4775                     uint32_t dsdb_flags,
4776                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4777 {
4778         int ret;
4779         struct ldb_result *res;
4780         va_list ap;
4781         char *expression = NULL;
4782         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4783
4784         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4785
4786         res = talloc_zero(tmp_ctx, struct ldb_result);
4787         if (!res) {
4788                 talloc_free(tmp_ctx);
4789                 return ldb_oom(ldb);
4790         }
4791
4792         if (exp_fmt) {
4793                 va_start(ap, exp_fmt);
4794                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4795                 va_end(ap);
4796
4797                 if (!expression) {
4798                         talloc_free(tmp_ctx);
4799                         return ldb_oom(ldb);
4800                 }
4801                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4802                                   dsdb_flags, "%s", expression);
4803         } else {
4804                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4805                                   dsdb_flags, NULL);
4806         }
4807
4808         if (ret != LDB_SUCCESS) {
4809                 talloc_free(tmp_ctx);
4810                 return ret;
4811         }
4812
4813         *msg = talloc_steal(mem_ctx, res->msgs[0]);
4814         talloc_free(tmp_ctx);
4815
4816         return LDB_SUCCESS;
4817 }
4818
4819 /* returns back the forest DNS name */
4820 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4821 {
4822         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4823                                                           ldb_get_root_basedn(ldb));
4824         char *p;
4825
4826         if (forest_name == NULL) {
4827                 return NULL;
4828         }
4829
4830         p = strchr(forest_name, '/');
4831         if (p) {
4832                 *p = '\0';
4833         }
4834
4835         return forest_name;
4836 }
4837
4838 /* returns back the default domain DNS name */
4839 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4840 {
4841         const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4842                                                           ldb_get_default_basedn(ldb));
4843         char *p;
4844
4845         if (domain_name == NULL) {
4846                 return NULL;
4847         }
4848
4849         p = strchr(domain_name, '/');
4850         if (p) {
4851                 *p = '\0';
4852         }
4853
4854         return domain_name;
4855 }
4856
4857 /*
4858    validate that an DSA GUID belongs to the specified user sid.
4859    The user SID must be a domain controller account (either RODC or
4860    RWDC)
4861  */
4862 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4863                            const struct GUID *dsa_guid,
4864                            const struct dom_sid *sid)
4865 {
4866         /* strategy:
4867             - find DN of record with the DSA GUID in the
4868               configuration partition (objectGUID)
4869             - remove "NTDS Settings" component from DN
4870             - do a base search on that DN for serverReference with
4871               extended-dn enabled
4872             - extract objectSid from resulting serverReference
4873               attribute
4874             - check this sid matches the sid argument
4875         */
4876         struct ldb_dn *config_dn;
4877         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4878         struct ldb_message *msg;
4879         const char *attrs1[] = { NULL };
4880         const char *attrs2[] = { "serverReference", NULL };
4881         int ret;
4882         struct ldb_dn *dn, *account_dn;
4883         struct dom_sid sid2;
4884         NTSTATUS status;
4885
4886         config_dn = ldb_get_config_basedn(ldb);
4887
4888         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4889                               attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4890         if (ret != LDB_SUCCESS) {
4891                 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4892                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4893                 talloc_free(tmp_ctx);
4894                 return ldb_operr(ldb);
4895         }
4896         dn = msg->dn;
4897
4898         if (!ldb_dn_remove_child_components(dn, 1)) {
4899                 talloc_free(tmp_ctx);
4900                 return ldb_operr(ldb);
4901         }
4902
4903         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4904                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4905                               "(objectClass=server)");
4906         if (ret != LDB_SUCCESS) {
4907                 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4908                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4909                 talloc_free(tmp_ctx);
4910                 return ldb_operr(ldb);
4911         }
4912
4913         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4914         if (account_dn == NULL) {
4915                 DEBUG(1,(__location__ ": Failed to find account dn "
4916                          "(serverReference) for %s, parent of DSA with "
4917                          "objectGUID %s, sid %s\n",
4918                          ldb_dn_get_linearized(msg->dn),
4919                          GUID_string(tmp_ctx, dsa_guid),
4920                          dom_sid_string(tmp_ctx, sid)));
4921                 talloc_free(tmp_ctx);
4922                 return ldb_operr(ldb);
4923         }
4924
4925         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4926         if (!NT_STATUS_IS_OK(status)) {
4927                 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4928                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4929                 talloc_free(tmp_ctx);
4930                 return ldb_operr(ldb);
4931         }
4932
4933         if (!dom_sid_equal(sid, &sid2)) {
4934                 /* someone is trying to spoof another account */
4935                 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4936                          GUID_string(tmp_ctx, dsa_guid),
4937                          dom_sid_string(tmp_ctx, sid),
4938                          dom_sid_string(tmp_ctx, &sid2)));
4939                 talloc_free(tmp_ctx);
4940                 return ldb_operr(ldb);
4941         }
4942
4943         talloc_free(tmp_ctx);
4944         return LDB_SUCCESS;
4945 }
4946
4947 static const char * const secret_attributes[] = {
4948         DSDB_SECRET_ATTRIBUTES,
4949         NULL
4950 };
4951
4952 /*
4953   check if the attribute belongs to the RODC filtered attribute set
4954   Note that attributes that are in the filtered attribute set are the
4955   ones that _are_ always sent to a RODC
4956 */
4957 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4958 {
4959         /* they never get secret attributes */
4960         if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4961                 return false;
4962         }
4963
4964         /* they do get non-secret critical attributes */
4965         if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4966                 return true;
4967         }
4968
4969         /* they do get non-secret attributes marked as being in the FAS  */
4970         if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4971                 return true;
4972         }
4973
4974         /* other attributes are denied */
4975         return false;
4976 }
4977
4978 /* return fsmo role dn and role owner dn for a particular role*/
4979 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4980                                struct ldb_context *ldb,
4981                                uint32_t role,
4982                                struct ldb_dn **fsmo_role_dn,
4983                                struct ldb_dn **role_owner_dn)
4984 {
4985         int ret;
4986         switch (role) {
4987         case DREPL_NAMING_MASTER:
4988                 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4989                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4990                 if (ret != LDB_SUCCESS) {
4991                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4992                                  ldb_errstring(ldb)));
4993                         talloc_free(tmp_ctx);
4994                         return WERR_DS_DRA_INTERNAL_ERROR;
4995                 }
4996                 break;
4997         case DREPL_INFRASTRUCTURE_MASTER:
4998                 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4999                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5000                 if (ret != LDB_SUCCESS) {
5001                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5002                                  ldb_errstring(ldb)));
5003                         talloc_free(tmp_ctx);
5004                         return WERR_DS_DRA_INTERNAL_ERROR;
5005                 }
5006                 break;
5007         case DREPL_RID_MASTER:
5008                 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
5009                 if (ret != LDB_SUCCESS) {
5010                         DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
5011                         talloc_free(tmp_ctx);
5012                         return WERR_DS_DRA_INTERNAL_ERROR;
5013                 }
5014
5015                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5016                 if (ret != LDB_SUCCESS) {
5017                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
5018                                  ldb_errstring(ldb)));
5019                         talloc_free(tmp_ctx);
5020                         return WERR_DS_DRA_INTERNAL_ERROR;
5021                 }
5022                 break;
5023         case DREPL_SCHEMA_MASTER:
5024                 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
5025                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5026                 if (ret != LDB_SUCCESS) {
5027                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5028                                  ldb_errstring(ldb)));
5029                         talloc_free(tmp_ctx);
5030                         return WERR_DS_DRA_INTERNAL_ERROR;
5031                 }
5032                 break;
5033         case DREPL_PDC_MASTER:
5034                 *fsmo_role_dn = ldb_get_default_basedn(ldb);
5035                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5036                 if (ret != LDB_SUCCESS) {
5037                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
5038                                  ldb_errstring(ldb)));
5039                         talloc_free(tmp_ctx);
5040                         return WERR_DS_DRA_INTERNAL_ERROR;
5041                 }
5042                 break;
5043         default:
5044                 return WERR_DS_DRA_INTERNAL_ERROR;
5045         }
5046         return WERR_OK;
5047 }
5048
5049 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
5050                                     TALLOC_CTX *mem_ctx,
5051                                     struct ldb_dn *server_dn)
5052 {
5053         int ldb_ret;
5054         struct ldb_result *res = NULL;
5055         const char * const attrs[] = { "dNSHostName", NULL};
5056
5057         ldb_ret = ldb_search(ldb, mem_ctx, &res,
5058                              server_dn,
5059                              LDB_SCOPE_BASE,
5060                              attrs, NULL);
5061         if (ldb_ret != LDB_SUCCESS) {
5062                 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
5063                           ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
5064                 return NULL;
5065         }
5066
5067         return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
5068 }
5069
5070 /*
5071   returns true if an attribute is in the filter,
5072   false otherwise, provided that attribute value is provided with the expression
5073 */
5074 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
5075                              const char *attr)
5076 {
5077        unsigned int i;
5078        switch (tree->operation) {
5079        case LDB_OP_AND:
5080        case LDB_OP_OR:
5081                for (i=0;i<tree->u.list.num_elements;i++) {
5082                        if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
5083                                                        attr))
5084                                return true;
5085                }
5086                return false;
5087        case LDB_OP_NOT:
5088                return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
5089        case LDB_OP_EQUALITY:
5090        case LDB_OP_GREATER:
5091        case LDB_OP_LESS:
5092        case LDB_OP_APPROX:
5093                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
5094                        return true;
5095                }
5096                return false;
5097        case LDB_OP_SUBSTRING:
5098                if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
5099                        return true;
5100                }
5101                return false;
5102        case LDB_OP_PRESENT:
5103                /* (attrname=*) is not filtered out */
5104                return false;
5105        case LDB_OP_EXTENDED:
5106                if (tree->u.extended.attr &&
5107                    ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
5108                        return true;
5109                }
5110                return false;
5111        }
5112        return false;
5113 }
5114
5115 bool is_attr_in_list(const char * const * attrs, const char *attr)
5116 {
5117         unsigned int i;
5118
5119         for (i = 0; attrs[i]; i++) {
5120                 if (ldb_attr_cmp(attrs[i], attr) == 0)
5121                         return true;
5122         }
5123
5124         return false;
5125 }
5126
5127 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
5128                    const char *location, const char *func,
5129                    const char *reason)
5130 {
5131         if (reason == NULL) {
5132                 reason = win_errstr(werr);
5133         }
5134         ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
5135                                W_ERROR_V(werr), reason, location, func);
5136         return ldb_ecode;
5137 }
5138
5139 /*
5140   map an ldb error code to an approximate NTSTATUS code
5141  */
5142 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
5143 {
5144         switch (err) {
5145         case LDB_SUCCESS:
5146                 return NT_STATUS_OK;
5147
5148         case LDB_ERR_PROTOCOL_ERROR:
5149                 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
5150
5151         case LDB_ERR_TIME_LIMIT_EXCEEDED:
5152                 return NT_STATUS_IO_TIMEOUT;
5153
5154         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
5155                 return NT_STATUS_BUFFER_TOO_SMALL;
5156
5157         case LDB_ERR_COMPARE_FALSE:
5158         case LDB_ERR_COMPARE_TRUE:
5159                 return NT_STATUS_REVISION_MISMATCH;
5160
5161         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
5162                 return NT_STATUS_NOT_SUPPORTED;
5163
5164         case LDB_ERR_STRONG_AUTH_REQUIRED:
5165         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
5166         case LDB_ERR_SASL_BIND_IN_PROGRESS:
5167         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
5168         case LDB_ERR_INVALID_CREDENTIALS:
5169         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
5170         case LDB_ERR_UNWILLING_TO_PERFORM:
5171                 return NT_STATUS_ACCESS_DENIED;
5172
5173         case LDB_ERR_NO_SUCH_OBJECT:
5174                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
5175
5176         case LDB_ERR_REFERRAL:
5177         case LDB_ERR_NO_SUCH_ATTRIBUTE:
5178                 return NT_STATUS_NOT_FOUND;
5179
5180         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
5181                 return NT_STATUS_NOT_SUPPORTED;
5182
5183         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
5184                 return NT_STATUS_BUFFER_TOO_SMALL;
5185
5186         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
5187         case LDB_ERR_INAPPROPRIATE_MATCHING:
5188         case LDB_ERR_CONSTRAINT_VIOLATION:
5189         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
5190         case LDB_ERR_INVALID_DN_SYNTAX:
5191         case LDB_ERR_NAMING_VIOLATION:
5192         case LDB_ERR_OBJECT_CLASS_VIOLATION:
5193         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
5194         case LDB_ERR_NOT_ALLOWED_ON_RDN:
5195                 return NT_STATUS_INVALID_PARAMETER;
5196
5197         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
5198         case LDB_ERR_ENTRY_ALREADY_EXISTS:
5199                 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
5200
5201         case LDB_ERR_BUSY:
5202                 return NT_STATUS_NETWORK_BUSY;
5203
5204         case LDB_ERR_ALIAS_PROBLEM:
5205         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
5206         case LDB_ERR_UNAVAILABLE:
5207         case LDB_ERR_LOOP_DETECT:
5208         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
5209         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
5210         case LDB_ERR_OTHER:
5211         case LDB_ERR_OPERATIONS_ERROR:
5212                 break;
5213         }
5214         return NT_STATUS_UNSUCCESSFUL;
5215 }
5216
5217
5218 /*
5219   create a new naming context that will hold a partial replica
5220  */
5221 int dsdb_create_partial_replica_NC(struct ldb_context *ldb,  struct ldb_dn *dn)
5222 {
5223         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5224         struct ldb_message *msg;
5225         int ret;
5226
5227         msg = ldb_msg_new(tmp_ctx);
5228         if (msg == NULL) {
5229                 talloc_free(tmp_ctx);
5230                 return ldb_oom(ldb);
5231         }
5232
5233         msg->dn = dn;
5234         ret = ldb_msg_add_string(msg, "objectClass", "top");
5235         if (ret != LDB_SUCCESS) {
5236                 talloc_free(tmp_ctx);
5237                 return ldb_oom(ldb);
5238         }
5239
5240         /* [MS-DRSR] implies that we should only add the 'top'
5241          * objectclass, but that would cause lots of problems with our
5242          * objectclass code as top is not structural, so we add
5243          * 'domainDNS' as well to keep things sane. We're expecting
5244          * this new NC to be of objectclass domainDNS after
5245          * replication anyway
5246          */
5247         ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
5248         if (ret != LDB_SUCCESS) {
5249                 talloc_free(tmp_ctx);
5250                 return ldb_oom(ldb);
5251         }
5252
5253         ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
5254                               INSTANCE_TYPE_IS_NC_HEAD|
5255                               INSTANCE_TYPE_NC_ABOVE|
5256                               INSTANCE_TYPE_UNINSTANT);
5257         if (ret != LDB_SUCCESS) {
5258                 talloc_free(tmp_ctx);
5259                 return ldb_oom(ldb);
5260         }
5261
5262         ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
5263         if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
5264                 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
5265                          ldb_dn_get_linearized(dn),
5266                          ldb_errstring(ldb), ldb_strerror(ret)));
5267                 talloc_free(tmp_ctx);
5268                 return ret;
5269         }
5270
5271         DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
5272
5273         talloc_free(tmp_ctx);
5274         return LDB_SUCCESS;
5275 }
5276
5277 /**
5278   build a GUID from a string
5279 */
5280 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
5281 {
5282         NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
5283         uint32_t time_low;
5284         uint32_t time_mid, time_hi_and_version;
5285         uint32_t clock_seq[2];
5286         uint32_t node[6];
5287         int i;
5288
5289         if (s == NULL) {
5290                 return NT_STATUS_INVALID_PARAMETER;
5291         }
5292
5293         status =  parse_guid_string(s,
5294                                     &time_low,
5295                                     &time_mid,
5296                                     &time_hi_and_version,
5297                                     clock_seq,
5298                                     node);
5299
5300         if (!NT_STATUS_IS_OK(status)) {
5301                 return status;
5302         }
5303
5304         guid->time_low = time_low;
5305         guid->time_mid = time_mid;
5306         guid->time_hi_and_version = time_hi_and_version;
5307         guid->clock_seq[0] = clock_seq[0];
5308         guid->clock_seq[1] = clock_seq[1];
5309         for (i=0;i<6;i++) {
5310                 guid->node[i] = node[i];
5311         }
5312
5313         return NT_STATUS_OK;
5314 }
5315
5316 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
5317 {
5318         return talloc_asprintf(mem_ctx, 
5319                                "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5320                                guid->time_low, guid->time_mid,
5321                                guid->time_hi_and_version,
5322                                guid->clock_seq[0],
5323                                guid->clock_seq[1],
5324                                guid->node[0], guid->node[1],
5325                                guid->node[2], guid->node[3],
5326                                guid->node[4], guid->node[5]);
5327 }
5328
5329 /*
5330  * Return the effective badPwdCount
5331  *
5332  * This requires that the user_msg have (if present):
5333  *  - badPasswordTime
5334  *  - badPwdCount
5335  *
5336  * This also requires that the domain_msg have (if present):
5337  *  - lockOutObservationWindow
5338  */
5339 static int dsdb_effective_badPwdCount(const struct ldb_message *user_msg,
5340                                       int64_t lockOutObservationWindow,
5341                                       NTTIME now)
5342 {
5343         int64_t badPasswordTime;
5344         badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
5345
5346         if (badPasswordTime - lockOutObservationWindow >= now) {
5347                 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
5348         } else {
5349                 return 0;
5350         }
5351 }
5352
5353 /*
5354  * Returns a user's PSO, or NULL if none was found
5355  */
5356 static struct ldb_result *lookup_user_pso(struct ldb_context *sam_ldb,
5357                                           TALLOC_CTX *mem_ctx,
5358                                           const struct ldb_message *user_msg,
5359                                           const char * const *attrs)
5360 {
5361         struct ldb_result *res = NULL;
5362         struct ldb_dn *pso_dn = NULL;
5363         int ret;
5364
5365         /* if the user has a PSO that applies, then use the PSO's setting */
5366         pso_dn = ldb_msg_find_attr_as_dn(sam_ldb, mem_ctx, user_msg,
5367                                          "msDS-ResultantPSO");
5368
5369         if (pso_dn != NULL) {
5370
5371                 ret = dsdb_search_dn(sam_ldb, mem_ctx, &res, pso_dn, attrs, 0);
5372                 if (ret != LDB_SUCCESS) {
5373
5374                         /*
5375                          * log the error. The caller should fallback to using
5376                          * the default domain password settings
5377                          */
5378                         DBG_ERR("Error retrieving msDS-ResultantPSO %s for %s",
5379                                 ldb_dn_get_linearized(pso_dn),
5380                                 ldb_dn_get_linearized(user_msg->dn));
5381                 }
5382                 talloc_free(pso_dn);
5383         }
5384         return res;
5385 }
5386
5387 /*
5388  * Return the effective badPwdCount
5389  *
5390  * This requires that the user_msg have (if present):
5391  *  - badPasswordTime
5392  *  - badPwdCount
5393  *  - msDS-ResultantPSO
5394  */
5395 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
5396                                        TALLOC_CTX *mem_ctx,
5397                                        struct ldb_dn *domain_dn,
5398                                        const struct ldb_message *user_msg)
5399 {
5400         struct timeval tv_now = timeval_current();
5401         NTTIME now = timeval_to_nttime(&tv_now);
5402         int64_t lockOutObservationWindow;
5403         struct ldb_result *res = NULL;
5404         const char *attrs[] = { "msDS-LockoutObservationWindow",
5405                                 NULL };
5406
5407         res = lookup_user_pso(sam_ldb, mem_ctx, user_msg, attrs);
5408
5409         if (res != NULL) {
5410                 lockOutObservationWindow =
5411                         ldb_msg_find_attr_as_int64(res->msgs[0],
5412                                                    "msDS-LockoutObservationWindow",
5413                                                     DEFAULT_OBSERVATION_WINDOW);
5414                 talloc_free(res);
5415         } else {
5416
5417                 /* no PSO was found, lookup the default domain setting */
5418                 lockOutObservationWindow =
5419                          samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
5420                                             "lockOutObservationWindow", NULL);
5421         }
5422
5423         return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5424 }
5425
5426 /*
5427  * Returns the lockoutThreshold that applies. If a PSO is specified, then that
5428  * setting is used over the domain defaults
5429  */
5430 static int64_t get_lockout_threshold(struct ldb_message *domain_msg,
5431                                      struct ldb_message *pso_msg)
5432 {
5433         if (pso_msg != NULL) {
5434                 return ldb_msg_find_attr_as_int(pso_msg,
5435                                                 "msDS-LockoutThreshold", 0);
5436         } else {
5437                 return ldb_msg_find_attr_as_int(domain_msg,
5438                                                 "lockoutThreshold", 0);
5439         }
5440 }
5441
5442 /*
5443  * Returns the lockOutObservationWindow that applies. If a PSO is specified,
5444  * then that setting is used over the domain defaults
5445  */
5446 static int64_t get_lockout_observation_window(struct ldb_message *domain_msg,
5447                                               struct ldb_message *pso_msg)
5448 {
5449         if (pso_msg != NULL) {
5450                 return ldb_msg_find_attr_as_int64(pso_msg,
5451                                                   "msDS-LockoutObservationWindow",
5452                                                    DEFAULT_OBSERVATION_WINDOW);
5453         } else {
5454                 return ldb_msg_find_attr_as_int64(domain_msg,
5455                                                   "lockOutObservationWindow",
5456                                                    DEFAULT_OBSERVATION_WINDOW);
5457         }
5458 }
5459
5460 /*
5461  * Prepare an update to the badPwdCount and associated attributes.
5462  *
5463  * This requires that the user_msg have (if present):
5464  *  - objectSid
5465  *  - badPasswordTime
5466  *  - badPwdCount
5467  *
5468  * This also requires that the domain_msg have (if present):
5469  *  - pwdProperties
5470  *  - lockoutThreshold
5471  *  - lockOutObservationWindow
5472  *
5473  * This also requires that the pso_msg have (if present):
5474  *  - msDS-LockoutThreshold
5475  *  - msDS-LockoutObservationWindow
5476  */
5477 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
5478                                    struct ldb_context *sam_ctx,
5479                                    struct ldb_message *user_msg,
5480                                    struct ldb_message *domain_msg,
5481                                    struct ldb_message *pso_msg,
5482                                    struct ldb_message **_mod_msg)
5483 {
5484         int i, ret, badPwdCount;
5485         int64_t lockoutThreshold, lockOutObservationWindow;
5486         struct dom_sid *sid;
5487         struct timeval tv_now = timeval_current();
5488         NTTIME now = timeval_to_nttime(&tv_now);
5489         NTSTATUS status;
5490         uint32_t pwdProperties, rid = 0;
5491         struct ldb_message *mod_msg;
5492
5493         sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
5494
5495         pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
5496                                                   "pwdProperties", -1);
5497         if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
5498                 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
5499                 if (!NT_STATUS_IS_OK(status)) {
5500                         /*
5501                          * This can't happen anyway, but always try
5502                          * and update the badPwdCount on failure
5503                          */
5504                         rid = 0;
5505                 }
5506         }
5507         TALLOC_FREE(sid);
5508
5509         /*
5510          * Work out if we are doing password lockout on the domain.
5511          * Also, the built in administrator account is exempt:
5512          * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
5513          */
5514         lockoutThreshold = get_lockout_threshold(domain_msg, pso_msg);
5515         if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
5516                 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
5517                           ldb_dn_get_linearized(user_msg->dn)));
5518                 return NT_STATUS_OK;
5519         }
5520
5521         mod_msg = ldb_msg_new(mem_ctx);
5522         if (mod_msg == NULL) {
5523                 return NT_STATUS_NO_MEMORY;
5524         }
5525         mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
5526         if (mod_msg->dn == NULL) {
5527                 TALLOC_FREE(mod_msg);
5528                 return NT_STATUS_NO_MEMORY;
5529         }
5530
5531         lockOutObservationWindow = get_lockout_observation_window(domain_msg,
5532                                                                   pso_msg);
5533
5534         badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5535
5536         badPwdCount++;
5537
5538         ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
5539         if (ret != LDB_SUCCESS) {
5540                 TALLOC_FREE(mod_msg);
5541                 return NT_STATUS_NO_MEMORY;
5542         }
5543         ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
5544         if (ret != LDB_SUCCESS) {
5545                 TALLOC_FREE(mod_msg);
5546                 return NT_STATUS_NO_MEMORY;
5547         }
5548
5549         if (badPwdCount >= lockoutThreshold) {
5550                 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
5551                 if (ret != LDB_SUCCESS) {
5552                         TALLOC_FREE(mod_msg);
5553                         return NT_STATUS_NO_MEMORY;
5554                 }
5555                 DEBUGC( DBGC_AUTH, 1, ("Locked out user %s after %d wrong passwords\n",
5556                           ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5557         } else {
5558                 DEBUGC( DBGC_AUTH, 5, ("Updated badPwdCount on %s after %d wrong passwords\n",
5559                           ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5560         }
5561
5562         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5563         for (i=0; i< mod_msg->num_elements; i++) {
5564                 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5565         }
5566
5567         *_mod_msg = mod_msg;
5568         return NT_STATUS_OK;
5569 }
5570
5571 /**
5572  * Sets defaults for a User object
5573  * List of default attributes set:
5574  *      accountExpires, badPasswordTime, badPwdCount,
5575  *      codePage, countryCode, lastLogoff, lastLogon
5576  *      logonCount, pwdLastSet
5577  */
5578 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
5579                                struct ldb_message *usr_obj,
5580                                struct ldb_request *req)
5581 {
5582         int i, ret;
5583         const struct attribute_values {
5584                 const char *name;
5585                 const char *value;
5586                 const char *add_value;
5587                 const char *mod_value;
5588                 const char *control;
5589                 unsigned add_flags;
5590                 unsigned mod_flags;
5591         } map[] = {
5592                 {
5593                         .name = "accountExpires",
5594                         .add_value = "9223372036854775807",
5595                         .mod_value = "0",
5596                 },
5597                 {
5598                         .name = "badPasswordTime",
5599                         .value = "0"
5600                 },
5601                 {
5602                         .name = "badPwdCount",
5603                         .value = "0"
5604                 },
5605                 {
5606                         .name = "codePage",
5607                         .value = "0"
5608                 },
5609                 {
5610                         .name = "countryCode",
5611                         .value = "0"
5612                 },
5613                 {
5614                         .name = "lastLogoff",
5615                         .value = "0"
5616                 },
5617                 {
5618                         .name = "lastLogon",
5619                         .value = "0"
5620                 },
5621                 {
5622                         .name = "logonCount",
5623                         .value = "0"
5624                 },
5625                 {
5626                         .name = "logonHours",
5627                         .add_flags = DSDB_FLAG_INTERNAL_FORCE_META_DATA,
5628                 },
5629                 {
5630                         .name = "pwdLastSet",
5631                         .value = "0",
5632                         .control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
5633                 },
5634                 {
5635                         .name = "adminCount",
5636                         .mod_value = "0",
5637                 },
5638                 {
5639                         .name = "operatorCount",
5640                         .mod_value = "0",
5641                 },
5642         };
5643
5644         for (i = 0; i < ARRAY_SIZE(map); i++) {
5645                 bool added = false;
5646                 const char *value = NULL;
5647                 unsigned flags = 0;
5648
5649                 if (req != NULL && req->operation == LDB_ADD) {
5650                         value = map[i].add_value;
5651                         flags = map[i].add_flags;
5652                 } else {
5653                         value = map[i].mod_value;
5654                         flags = map[i].mod_flags;
5655                 }
5656
5657                 if (value == NULL) {
5658                         value = map[i].value;
5659                 }
5660
5661                 if (value != NULL) {
5662                         flags |= LDB_FLAG_MOD_ADD;
5663                 }
5664
5665                 if (flags == 0) {
5666                         continue;
5667                 }
5668
5669                 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
5670                                                      map[i].name,
5671                                                      value, flags,
5672                                                      &added);
5673                 if (ret != LDB_SUCCESS) {
5674                         return ret;
5675                 }
5676
5677                 if (req != NULL && added && map[i].control != NULL) {
5678                         ret = ldb_request_add_control(req,
5679                                                       map[i].control,
5680                                                       false, NULL);
5681                         if (ret != LDB_SUCCESS) {
5682                                 return ret;
5683                         }
5684                 }
5685         }
5686
5687         return LDB_SUCCESS;
5688 }
5689
5690 /**
5691  * Sets 'sAMAccountType on user object based on userAccountControl
5692  * @param ldb Current ldb_context
5693  * @param usr_obj ldb_message representing User object
5694  * @param user_account_control Value for userAccountControl flags
5695  * @param account_type_p Optional pointer to account_type to return
5696  * @return LDB_SUCCESS or LDB_ERR* code on failure
5697  */
5698 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
5699                                    uint32_t user_account_control, uint32_t *account_type_p)
5700 {
5701         int ret;
5702         uint32_t account_type;
5703         struct ldb_message_element *el;
5704
5705         account_type = ds_uf2atype(user_account_control);
5706         if (account_type == 0) {
5707                 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
5708                 return LDB_ERR_UNWILLING_TO_PERFORM;
5709         }
5710         ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5711                                  "sAMAccountType",
5712                                  account_type);
5713         if (ret != LDB_SUCCESS) {
5714                 return ret;
5715         }
5716         el = ldb_msg_find_element(usr_obj, "sAMAccountType");
5717         el->flags = LDB_FLAG_MOD_REPLACE;
5718
5719         if (account_type_p) {
5720                 *account_type_p = account_type;
5721         }
5722
5723         return LDB_SUCCESS;
5724 }
5725
5726 /**
5727  * Determine and set primaryGroupID based on userAccountControl value
5728  * @param ldb Current ldb_context
5729  * @param usr_obj ldb_message representing User object
5730  * @param user_account_control Value for userAccountControl flags
5731  * @param group_rid_p Optional pointer to group RID to return
5732  * @return LDB_SUCCESS or LDB_ERR* code on failure
5733  */
5734 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
5735                                        uint32_t user_account_control, uint32_t *group_rid_p)
5736 {
5737         int ret;
5738         uint32_t rid;
5739         struct ldb_message_element *el;
5740
5741         rid = ds_uf2prim_group_rid(user_account_control);
5742
5743         ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5744                                  "primaryGroupID", rid);
5745         if (ret != LDB_SUCCESS) {
5746                 return ret;
5747         }
5748         el = ldb_msg_find_element(usr_obj, "primaryGroupID");
5749         el->flags = LDB_FLAG_MOD_REPLACE;
5750
5751         if (group_rid_p) {
5752                 *group_rid_p = rid;
5753         }
5754
5755         return LDB_SUCCESS;
5756 }
5757
5758 /**
5759  * Returns True if the source and target DNs both have the same naming context,
5760  * i.e. they're both in the same partition.
5761  */
5762 bool dsdb_objects_have_same_nc(struct ldb_context *ldb,
5763                                TALLOC_CTX *mem_ctx,
5764                                struct ldb_dn *source_dn,
5765                                struct ldb_dn *target_dn)
5766 {
5767         TALLOC_CTX *tmp_ctx;
5768         struct ldb_dn *source_nc;
5769         struct ldb_dn *target_nc;
5770         int ret;
5771         bool same_nc = true;
5772
5773         tmp_ctx = talloc_new(mem_ctx);
5774
5775         ret = dsdb_find_nc_root(ldb, tmp_ctx, source_dn, &source_nc);
5776         if (ret != LDB_SUCCESS) {
5777                 DBG_ERR("Failed to find base DN for source %s\n",
5778                         ldb_dn_get_linearized(source_dn));
5779                 talloc_free(tmp_ctx);
5780                 return true;
5781         }
5782
5783         ret = dsdb_find_nc_root(ldb, tmp_ctx, target_dn, &target_nc);
5784         if (ret != LDB_SUCCESS) {
5785                 DBG_ERR("Failed to find base DN for target %s\n",
5786                         ldb_dn_get_linearized(target_dn));
5787                 talloc_free(tmp_ctx);
5788                 return true;
5789         }
5790
5791         same_nc = (ldb_dn_compare(source_nc, target_nc) == 0);
5792
5793         talloc_free(tmp_ctx);
5794
5795         return same_nc;
5796 }
5797 /*
5798  * Context for dsdb_count_domain_callback
5799  */
5800 struct dsdb_count_domain_context {
5801         /*
5802          * Number of matching records
5803          */
5804         size_t count;
5805         /*
5806          * sid of the domain that the records must belong to.
5807          * if NULL records can belong to any domain.
5808          */
5809         struct dom_sid *dom_sid;
5810 };
5811
5812 /*
5813  * @brief ldb aysnc callback for dsdb_domain_count.
5814  *
5815  * count the number of records in the database matching an LDAP query,
5816  * optionally filtering for domain membership.
5817  *
5818  * @param [in,out] req the ldb request being processed
5819  *                    req->context contains:
5820  *                        count   The number of matching records
5821  *                        dom_sid The domain sid, if present records must belong
5822  *                                to the domain to be counted.
5823  *@param [in,out] ares The query result.
5824  *
5825  * @return an LDB error code
5826  *
5827  */
5828 static int dsdb_count_domain_callback(
5829         struct ldb_request *req,
5830         struct ldb_reply *ares)
5831 {
5832
5833         if (ares == NULL) {
5834                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
5835         }
5836         if (ares->error != LDB_SUCCESS) {
5837                 int error = ares->error;
5838                 TALLOC_FREE(ares);
5839                 return ldb_request_done(req, error);
5840         }
5841
5842         switch (ares->type) {
5843         case LDB_REPLY_ENTRY:
5844         {
5845                 struct dsdb_count_domain_context *context = NULL;
5846                 bool ok, in_domain;
5847                 struct dom_sid sid;
5848                 const struct ldb_val *v;
5849
5850                 context = req->context;
5851                 if (context->dom_sid == NULL) {
5852                         context->count++;
5853                         break;
5854                 }
5855
5856                 v = ldb_msg_find_ldb_val(ares->message, "objectSid");
5857                 if (v == NULL) {
5858                         break;
5859                 }
5860
5861                 ok = sid_parse(v->data, v->length, &sid);
5862                 if (!ok) {
5863                         break;
5864                 }
5865
5866                 in_domain = dom_sid_in_domain(context->dom_sid, &sid);
5867                 if (!in_domain) {
5868                         break;
5869                 }
5870
5871                 context->count++;
5872                 break;
5873         }
5874         case LDB_REPLY_REFERRAL:
5875                 break;
5876
5877         case LDB_REPLY_DONE:
5878                 TALLOC_FREE(ares);
5879                 return ldb_request_done(req, LDB_SUCCESS);
5880         }
5881
5882         TALLOC_FREE(ares);
5883
5884         return LDB_SUCCESS;
5885 }
5886
5887 /*
5888  * @brief Count the number of records matching a query.
5889  *
5890  * Count the number of entries in the database matching the supplied query,
5891  * optionally filtering only those entries belonging to the supplied domain.
5892  *
5893  * @param ldb [in] Current ldb context
5894  * @param count [out] Pointer to the count
5895  * @param base [in] The base dn for the quey
5896  * @param dom_sid [in] The domain sid, if non NULL records that are not a member
5897  *                     of the domain are ignored.
5898  * @param scope [in] Search scope.
5899  * @param exp_fmt [in] format string for the query.
5900  *
5901  * @return LDB_STATUS code.
5902  */
5903 int dsdb_domain_count(
5904         struct ldb_context *ldb,
5905         size_t *count,
5906         struct ldb_dn *base,
5907         struct dom_sid *dom_sid,
5908         enum ldb_scope scope,
5909         const char *exp_fmt, ...)
5910 {
5911         TALLOC_CTX *tmp_ctx = NULL;
5912         struct ldb_request *req = NULL;
5913         struct dsdb_count_domain_context *context = NULL;
5914         char *expression = NULL;
5915         const char *object_sid[] = {"objectSid", NULL};
5916         const char *none[] = {NULL};
5917         va_list ap;
5918         int ret;
5919
5920         *count = 0;
5921         tmp_ctx = talloc_new(ldb);
5922
5923         context = talloc_zero(tmp_ctx, struct dsdb_count_domain_context);
5924         if (context == NULL) {
5925                 return LDB_ERR_OPERATIONS_ERROR;
5926         }
5927         context->dom_sid = dom_sid;
5928
5929         if (exp_fmt) {
5930                 va_start(ap, exp_fmt);
5931                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
5932                 va_end(ap);
5933
5934                 if (expression == NULL) {
5935                         TALLOC_FREE(context);
5936                         TALLOC_FREE(tmp_ctx);
5937                         return LDB_ERR_OPERATIONS_ERROR;
5938                 }
5939         }
5940
5941         ret = ldb_build_search_req(
5942                 &req,
5943                 ldb,
5944                 tmp_ctx,
5945                 base,
5946                 scope,
5947                 expression,
5948                 (dom_sid == NULL) ? none : object_sid,
5949                 NULL,
5950                 context,
5951                 dsdb_count_domain_callback,
5952                 NULL);
5953         ldb_req_set_location(req, "dsdb_domain_count");
5954
5955         if (ret != LDB_SUCCESS) goto done;
5956
5957         ret = ldb_request(ldb, req);
5958
5959         if (ret == LDB_SUCCESS) {
5960                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
5961                 if (ret == LDB_SUCCESS) {
5962                         *count = context->count;
5963                 }
5964         }
5965
5966
5967 done:
5968         TALLOC_FREE(expression);
5969         TALLOC_FREE(req);
5970         TALLOC_FREE(context);
5971         TALLOC_FREE(tmp_ctx);
5972
5973         return ret;
5974 }