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