s4:dsdb:util: export SAMBA_CPS_{ACCOUNT,USER_PRINCIPAL,FULL}_NAME for check password...
[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 char *account_name,
2087                                                 const char *user_principal_name,
2088                                                 const char *full_name,
2089                                                 const DATA_BLOB *utf8_blob,
2090                                                 const uint32_t pwdProperties,
2091                                                 const uint32_t minPwdLength)
2092 {
2093         const char *utf8_pw = (const char *)utf8_blob->data;
2094         size_t utf8_len = strlen_m(utf8_pw);
2095         char *password_script = NULL;
2096
2097         /* checks if the "minPwdLength" property is satisfied */
2098         if (minPwdLength > utf8_len) {
2099                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2100         }
2101
2102         /* checks the password complexity */
2103         if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
2104                 return SAMR_VALIDATION_STATUS_SUCCESS;
2105         }
2106
2107         if (utf8_len == 0) {
2108                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2109         }
2110
2111         password_script = lpcfg_check_password_script(lp_ctx, mem_ctx);
2112         if (password_script != NULL && *password_script != '\0') {
2113                 int check_ret = 0;
2114                 int error = 0;
2115                 struct tevent_context *event_ctx = NULL;
2116                 struct tevent_req *req = NULL;
2117                 int cps_stdin = -1;
2118                 const char * const cmd[4] = {
2119                         "/bin/sh", "-c",
2120                         password_script,
2121                         NULL
2122                 };
2123
2124                 event_ctx = tevent_context_init(mem_ctx);
2125                 if (event_ctx == NULL) {
2126                         TALLOC_FREE(password_script);
2127                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2128                 }
2129
2130                 /* Gives a warning after 1 second, terminates after 10 */
2131                 tevent_add_timer(event_ctx, event_ctx,
2132                                  tevent_timeval_current_ofs(1, 0),
2133                                  pwd_timeout_debug, NULL);
2134
2135                 check_ret = setenv("SAMBA_CPS_ACCOUNT_NAME", account_name, 1);
2136                 if (check_ret != 0) {
2137                         TALLOC_FREE(password_script);
2138                         TALLOC_FREE(event_ctx);
2139                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2140                 }
2141                 if (user_principal_name != NULL) {
2142                         check_ret = setenv("SAMBA_CPS_USER_PRINCIPAL_NAME",
2143                                            user_principal_name, 1);
2144                 } else {
2145                         unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2146                 }
2147                 if (check_ret != 0) {
2148                         TALLOC_FREE(password_script);
2149                         TALLOC_FREE(event_ctx);
2150                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2151                 }
2152                 if (full_name != NULL) {
2153                         check_ret = setenv("SAMBA_CPS_FULL_NAME", full_name, 1);
2154                 } else {
2155                         unsetenv("SAMBA_CPS_FULL_NAME");
2156                 }
2157                 if (check_ret != 0) {
2158                         TALLOC_FREE(password_script);
2159                         TALLOC_FREE(event_ctx);
2160                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2161                 }
2162
2163                 req = samba_runcmd_send(event_ctx, event_ctx,
2164                                         tevent_timeval_current_ofs(10, 0),
2165                                         100, 100, cmd, NULL);
2166                 unsetenv("SAMBA_CPS_ACCOUNT_NAME");
2167                 unsetenv("SAMBA_CPS_USER_PRINCIPAL_NAME");
2168                 unsetenv("SAMBA_CPS_FULL_NAME");
2169                 if (req == NULL) {
2170                         TALLOC_FREE(password_script);
2171                         TALLOC_FREE(event_ctx);
2172                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2173                 }
2174
2175                 cps_stdin = samba_runcmd_export_stdin(req);
2176
2177                 if (write(cps_stdin, utf8_pw, utf8_len) != utf8_len) {
2178                         close(cps_stdin);
2179                         cps_stdin = -1;
2180                         TALLOC_FREE(password_script);
2181                         TALLOC_FREE(event_ctx);
2182                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2183                 }
2184
2185                 close(cps_stdin);
2186                 cps_stdin = -1;
2187
2188                 if (!tevent_req_poll(req, event_ctx)) {
2189                         TALLOC_FREE(password_script);
2190                         TALLOC_FREE(event_ctx);
2191                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2192                 }
2193
2194                 check_ret = samba_runcmd_recv(req, &error);
2195                 TALLOC_FREE(event_ctx);
2196
2197                 if (error == ETIMEDOUT) {
2198                         DEBUG(0, ("check_password_complexity: check password script took too long!\n"));
2199                         TALLOC_FREE(password_script);
2200                         return SAMR_VALIDATION_STATUS_PASSWORD_FILTER_ERROR;
2201                 }
2202                 DEBUG(5,("check_password_complexity: check password script (%s) "
2203                          "returned [%d]\n", password_script, check_ret));
2204
2205                 if (check_ret != 0) {
2206                         DEBUG(1,("check_password_complexity: "
2207                                  "check password script said new password is not good "
2208                                  "enough!\n"));
2209                         TALLOC_FREE(password_script);
2210                         return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2211                 }
2212
2213                 TALLOC_FREE(password_script);
2214                 return SAMR_VALIDATION_STATUS_SUCCESS;
2215         }
2216
2217         TALLOC_FREE(password_script);
2218
2219         /*
2220          * Here are the standard AD password quality rules, which we
2221          * run after the script.
2222          */
2223
2224         if (!check_password_quality(utf8_pw)) {
2225                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2226         }
2227
2228         return SAMR_VALIDATION_STATUS_SUCCESS;
2229 }
2230
2231 /*
2232  * Callback for "samdb_set_password" password change
2233  */
2234 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2235 {
2236         int ret;
2237
2238         if (!ares) {
2239                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2240         }
2241
2242         if (ares->error != LDB_SUCCESS) {
2243                 ret = ares->error;
2244                 req->context = talloc_steal(req,
2245                                             ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2246                 talloc_free(ares);
2247                 return ldb_request_done(req, ret);
2248         }
2249
2250         if (ares->type != LDB_REPLY_DONE) {
2251                 talloc_free(ares);
2252                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2253         }
2254
2255         req->context = talloc_steal(req,
2256                                     ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2257         talloc_free(ares);
2258         return ldb_request_done(req, LDB_SUCCESS);
2259 }
2260
2261 /*
2262  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2263  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2264  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2265  * user change or not. The "rejectReason" gives some more information if the
2266  * change failed.
2267  *
2268  * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2269  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2270  */
2271 static NTSTATUS samdb_set_password_internal(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2272                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2273                             const DATA_BLOB *new_password,
2274                             const struct samr_Password *lmNewHash,
2275                             const struct samr_Password *ntNewHash,
2276                             const struct samr_Password *lmOldHash,
2277                             const struct samr_Password *ntOldHash,
2278                             enum samPwdChangeReason *reject_reason,
2279                             struct samr_DomInfo1 **_dominfo,
2280                             bool permit_interdomain_trust)
2281 {
2282         struct ldb_message *msg;
2283         struct ldb_message_element *el;
2284         struct ldb_request *req;
2285         struct dsdb_control_password_change_status *pwd_stat = NULL;
2286         int ret;
2287         bool hash_values = false;
2288         NTSTATUS status = NT_STATUS_OK;
2289
2290 #define CHECK_RET(x) \
2291         if (x != LDB_SUCCESS) { \
2292                 talloc_free(msg); \
2293                 return NT_STATUS_NO_MEMORY; \
2294         }
2295
2296         msg = ldb_msg_new(mem_ctx);
2297         if (msg == NULL) {
2298                 return NT_STATUS_NO_MEMORY;
2299         }
2300         msg->dn = user_dn;
2301         if ((new_password != NULL)
2302                         && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2303                 /* we have the password as plaintext UTF16 */
2304                 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2305                                             new_password, NULL));
2306                 el = ldb_msg_find_element(msg, "clearTextPassword");
2307                 el->flags = LDB_FLAG_MOD_REPLACE;
2308         } else if ((new_password == NULL)
2309                         && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2310                 /* we have a password as LM and/or NT hash */
2311                 if (lmNewHash != NULL) {
2312                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2313                                 "dBCSPwd", lmNewHash));
2314                         el = ldb_msg_find_element(msg, "dBCSPwd");
2315                         el->flags = LDB_FLAG_MOD_REPLACE;
2316                 }
2317                 if (ntNewHash != NULL) {
2318                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2319                                 "unicodePwd", ntNewHash));
2320                         el = ldb_msg_find_element(msg, "unicodePwd");
2321                         el->flags = LDB_FLAG_MOD_REPLACE;
2322                 }
2323                 hash_values = true;
2324         } else {
2325                 /* the password wasn't specified correctly */
2326                 talloc_free(msg);
2327                 return NT_STATUS_INVALID_PARAMETER;
2328         }
2329
2330         /* build modify request */
2331         ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2332                                 samdb_set_password_callback, NULL);
2333         if (ret != LDB_SUCCESS) {
2334                 talloc_free(msg);
2335                 return NT_STATUS_NO_MEMORY;
2336         }
2337
2338         /* A password change operation */
2339         if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2340                 struct dsdb_control_password_change *change;
2341
2342                 change = talloc(req, struct dsdb_control_password_change);
2343                 if (change == NULL) {
2344                         talloc_free(req);
2345                         talloc_free(msg);
2346                         return NT_STATUS_NO_MEMORY;
2347                 }
2348
2349                 change->old_nt_pwd_hash = ntOldHash;
2350                 change->old_lm_pwd_hash = lmOldHash;
2351
2352                 ret = ldb_request_add_control(req,
2353                                               DSDB_CONTROL_PASSWORD_CHANGE_OID,
2354                                               true, change);
2355                 if (ret != LDB_SUCCESS) {
2356                         talloc_free(req);
2357                         talloc_free(msg);
2358                         return NT_STATUS_NO_MEMORY;
2359                 }
2360         }
2361         if (hash_values) {
2362                 ret = ldb_request_add_control(req,
2363                                               DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2364                                               true, NULL);
2365                 if (ret != LDB_SUCCESS) {
2366                         talloc_free(req);
2367                         talloc_free(msg);
2368                         return NT_STATUS_NO_MEMORY;
2369                 }
2370         }
2371         if (permit_interdomain_trust) {
2372                 ret = ldb_request_add_control(req,
2373                                               DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
2374                                               false, NULL);
2375                 if (ret != LDB_SUCCESS) {
2376                         talloc_free(req);
2377                         talloc_free(msg);
2378                         return NT_STATUS_NO_MEMORY;
2379                 }
2380         }
2381         ret = ldb_request_add_control(req,
2382                                       DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2383                                       true, NULL);
2384         if (ret != LDB_SUCCESS) {
2385                 talloc_free(req);
2386                 talloc_free(msg);
2387                 return NT_STATUS_NO_MEMORY;
2388         }
2389
2390         ret = dsdb_autotransaction_request(ldb, req);
2391
2392         if (req->context != NULL) {
2393                 struct ldb_control *control = talloc_get_type_abort(req->context,
2394                                                                     struct ldb_control);
2395                 pwd_stat = talloc_get_type_abort(control->data,
2396                                                  struct dsdb_control_password_change_status);
2397                 talloc_steal(mem_ctx, pwd_stat);
2398         }
2399
2400         talloc_free(req);
2401         talloc_free(msg);
2402
2403         /* Sets the domain info (if requested) */
2404         if (_dominfo != NULL) {
2405                 struct samr_DomInfo1 *dominfo;
2406
2407                 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2408                 if (dominfo == NULL) {
2409                         return NT_STATUS_NO_MEMORY;
2410                 }
2411
2412                 if (pwd_stat != NULL) {
2413                         dominfo->min_password_length     = pwd_stat->domain_data.minPwdLength;
2414                         dominfo->password_properties     = pwd_stat->domain_data.pwdProperties;
2415                         dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2416                         dominfo->max_password_age        = pwd_stat->domain_data.maxPwdAge;
2417                         dominfo->min_password_age        = pwd_stat->domain_data.minPwdAge;
2418                 }
2419
2420                 *_dominfo = dominfo;
2421         }
2422
2423         if (reject_reason != NULL) {
2424                 if (pwd_stat != NULL) {
2425                         *reject_reason = pwd_stat->reject_reason;
2426                 } else {
2427                         *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2428                 }
2429         }
2430
2431         if (pwd_stat != NULL) {
2432                 talloc_free(pwd_stat);
2433         }
2434
2435         if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2436                 const char *errmsg = ldb_errstring(ldb);
2437                 char *endptr = NULL;
2438                 WERROR werr = WERR_GEN_FAILURE;
2439                 status = NT_STATUS_UNSUCCESSFUL;
2440                 if (errmsg != NULL) {
2441                         werr = W_ERROR(strtol(errmsg, &endptr, 16));
2442                         DBG_WARNING("%s\n", errmsg);
2443                 }
2444                 if (endptr != errmsg) {
2445                         if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2446                                 status = NT_STATUS_WRONG_PASSWORD;
2447                         }
2448                         if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2449                                 status = NT_STATUS_PASSWORD_RESTRICTION;
2450                         }
2451                 }
2452         } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2453                 /* don't let the caller know if an account doesn't exist */
2454                 status = NT_STATUS_WRONG_PASSWORD;
2455         } else if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
2456                 status = NT_STATUS_ACCESS_DENIED;
2457         } else if (ret != LDB_SUCCESS) {
2458                 DEBUG(1, ("Failed to set password on %s: %s\n",
2459                           ldb_dn_get_linearized(user_dn),
2460                           ldb_errstring(ldb)));
2461                 status = NT_STATUS_UNSUCCESSFUL;
2462         }
2463
2464         return status;
2465 }
2466
2467 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2468                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2469                             const DATA_BLOB *new_password,
2470                             const struct samr_Password *lmNewHash,
2471                             const struct samr_Password *ntNewHash,
2472                             const struct samr_Password *lmOldHash,
2473                             const struct samr_Password *ntOldHash,
2474                             enum samPwdChangeReason *reject_reason,
2475                             struct samr_DomInfo1 **_dominfo)
2476 {
2477         return samdb_set_password_internal(ldb, mem_ctx,
2478                             user_dn, domain_dn,
2479                             new_password,
2480                             lmNewHash, ntNewHash,
2481                             lmOldHash, ntOldHash,
2482                             reject_reason, _dominfo,
2483                             false); /* reject trusts */
2484 }
2485
2486 /*
2487  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2488  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2489  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2490  * user change or not. The "rejectReason" gives some more information if the
2491  * change failed.
2492  *
2493  * This wrapper function for "samdb_set_password" takes a SID as input rather
2494  * than a user DN.
2495  *
2496  * This call encapsulates a new LDB transaction for changing the password;
2497  * therefore the user hasn't to start a new one.
2498  *
2499  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2500  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2501  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2502  *   NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2503  */
2504 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2505                                 const struct dom_sid *user_sid,
2506                                 const uint32_t *new_version, /* optional for trusts */
2507                                 const DATA_BLOB *new_password,
2508                                 const struct samr_Password *lmNewHash,
2509                                 const struct samr_Password *ntNewHash,
2510                                 const struct samr_Password *lmOldHash,
2511                                 const struct samr_Password *ntOldHash,
2512                                 enum samPwdChangeReason *reject_reason,
2513                                 struct samr_DomInfo1 **_dominfo) 
2514 {
2515         TALLOC_CTX *frame = talloc_stackframe();
2516         NTSTATUS nt_status;
2517         const char * const user_attrs[] = {
2518                 "userAccountControl",
2519                 "sAMAccountName",
2520                 NULL
2521         };
2522         struct ldb_message *user_msg = NULL;
2523         int ret;
2524         uint32_t uac = 0;
2525
2526         ret = ldb_transaction_start(ldb);
2527         if (ret != LDB_SUCCESS) {
2528                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2529                 TALLOC_FREE(frame);
2530                 return NT_STATUS_TRANSACTION_ABORTED;
2531         }
2532
2533         ret = dsdb_search_one(ldb, frame, &user_msg, ldb_get_default_basedn(ldb),
2534                               LDB_SCOPE_SUBTREE, user_attrs, 0,
2535                               "(&(objectSid=%s)(objectClass=user))",
2536                               ldap_encode_ndr_dom_sid(frame, user_sid));
2537         if (ret != LDB_SUCCESS) {
2538                 ldb_transaction_cancel(ldb);
2539                 DEBUG(3, ("samdb_set_password_sid: SID[%s] not found in samdb %s - %s, "
2540                           "returning NO_SUCH_USER\n",
2541                           dom_sid_string(frame, user_sid),
2542                           ldb_strerror(ret), ldb_errstring(ldb)));
2543                 TALLOC_FREE(frame);
2544                 return NT_STATUS_NO_SUCH_USER;
2545         }
2546
2547         uac = ldb_msg_find_attr_as_uint(user_msg, "userAccountControl", 0);
2548         if (!(uac & UF_ACCOUNT_TYPE_MASK)) {
2549                 ldb_transaction_cancel(ldb);
2550                 DEBUG(1, ("samdb_set_password_sid: invalid "
2551                           "userAccountControl[0x%08X] for SID[%s] DN[%s], "
2552                           "returning NO_SUCH_USER\n",
2553                           (unsigned)uac, dom_sid_string(frame, user_sid),
2554                           ldb_dn_get_linearized(user_msg->dn)));
2555                 TALLOC_FREE(frame);
2556                 return NT_STATUS_NO_SUCH_USER;
2557         }
2558
2559         if (uac & UF_INTERDOMAIN_TRUST_ACCOUNT) {
2560                 const char * const tdo_attrs[] = {
2561                         "trustAuthIncoming",
2562                         "trustDirection",
2563                         NULL
2564                 };
2565                 struct ldb_message *tdo_msg = NULL;
2566                 const char *account_name = NULL;
2567                 uint32_t trust_direction;
2568                 uint32_t i;
2569                 const struct ldb_val *old_val = NULL;
2570                 struct trustAuthInOutBlob old_blob = {
2571                         .count = 0,
2572                 };
2573                 uint32_t old_version = 0;
2574                 struct AuthenticationInformation *old_version_a = NULL;
2575                 uint32_t _new_version = 0;
2576                 struct trustAuthInOutBlob new_blob = {
2577                         .count = 0,
2578                 };
2579                 struct ldb_val new_val = {
2580                         .length = 0,
2581                 };
2582                 struct timeval tv = timeval_current();
2583                 NTTIME now = timeval_to_nttime(&tv);
2584                 enum ndr_err_code ndr_err;
2585
2586                 if (new_password == NULL && ntNewHash == NULL) {
2587                         ldb_transaction_cancel(ldb);
2588                         DEBUG(1, ("samdb_set_password_sid: "
2589                                   "no new password provided "
2590                                   "sAMAccountName for SID[%s] DN[%s], "
2591                                   "returning INVALID_PARAMETER\n",
2592                                   dom_sid_string(frame, user_sid),
2593                                   ldb_dn_get_linearized(user_msg->dn)));
2594                         TALLOC_FREE(frame);
2595                         return NT_STATUS_INVALID_PARAMETER;
2596                 }
2597
2598                 if (new_password != NULL && ntNewHash != NULL) {
2599                         ldb_transaction_cancel(ldb);
2600                         DEBUG(1, ("samdb_set_password_sid: "
2601                                   "two new passwords provided "
2602                                   "sAMAccountName for SID[%s] DN[%s], "
2603                                   "returning INVALID_PARAMETER\n",
2604                                   dom_sid_string(frame, user_sid),
2605                                   ldb_dn_get_linearized(user_msg->dn)));
2606                         TALLOC_FREE(frame);
2607                         return NT_STATUS_INVALID_PARAMETER;
2608                 }
2609
2610                 if (new_password != NULL && (new_password->length % 2)) {
2611                         ldb_transaction_cancel(ldb);
2612                         DEBUG(2, ("samdb_set_password_sid: "
2613                                   "invalid utf16 length (%zu) "
2614                                   "sAMAccountName for SID[%s] DN[%s], "
2615                                   "returning WRONG_PASSWORD\n",
2616                                   new_password->length,
2617                                   dom_sid_string(frame, user_sid),
2618                                   ldb_dn_get_linearized(user_msg->dn)));
2619                         TALLOC_FREE(frame);
2620                         return NT_STATUS_WRONG_PASSWORD;
2621                 }
2622
2623                 if (new_password != NULL && new_password->length >= 500) {
2624                         ldb_transaction_cancel(ldb);
2625                         DEBUG(2, ("samdb_set_password_sid: "
2626                                   "utf16 password too long (%zu) "
2627                                   "sAMAccountName for SID[%s] DN[%s], "
2628                                   "returning WRONG_PASSWORD\n",
2629                                   new_password->length,
2630                                   dom_sid_string(frame, user_sid),
2631                                   ldb_dn_get_linearized(user_msg->dn)));
2632                         TALLOC_FREE(frame);
2633                         return NT_STATUS_WRONG_PASSWORD;
2634                 }
2635
2636                 account_name = ldb_msg_find_attr_as_string(user_msg,
2637                                                         "sAMAccountName", NULL);
2638                 if (account_name == NULL) {
2639                         ldb_transaction_cancel(ldb);
2640                         DEBUG(1, ("samdb_set_password_sid: missing "
2641                                   "sAMAccountName for SID[%s] DN[%s], "
2642                                   "returning NO_SUCH_USER\n",
2643                                   dom_sid_string(frame, user_sid),
2644                                   ldb_dn_get_linearized(user_msg->dn)));
2645                         TALLOC_FREE(frame);
2646                         return NT_STATUS_NO_SUCH_USER;
2647                 }
2648
2649                 nt_status = dsdb_trust_search_tdo_by_type(ldb,
2650                                                           SEC_CHAN_DOMAIN,
2651                                                           account_name,
2652                                                           tdo_attrs,
2653                                                           frame, &tdo_msg);
2654                 if (!NT_STATUS_IS_OK(nt_status)) {
2655                         ldb_transaction_cancel(ldb);
2656                         DEBUG(1, ("samdb_set_password_sid: dsdb_trust_search_tdo "
2657                                   "failed(%s) for sAMAccountName[%s] SID[%s] DN[%s], "
2658                                   "returning INTERNAL_DB_CORRUPTION\n",
2659                                   nt_errstr(nt_status), account_name,
2660                                   dom_sid_string(frame, user_sid),
2661                                   ldb_dn_get_linearized(user_msg->dn)));
2662                         TALLOC_FREE(frame);
2663                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
2664                 }
2665
2666                 trust_direction = ldb_msg_find_attr_as_int(tdo_msg,
2667                                                            "trustDirection", 0);
2668                 if (!(trust_direction & LSA_TRUST_DIRECTION_INBOUND)) {
2669                         ldb_transaction_cancel(ldb);
2670                         DEBUG(1, ("samdb_set_password_sid: direction[0x%08X] is "
2671                                   "not inbound for sAMAccountName[%s] "
2672                                   "DN[%s] TDO[%s], "
2673                                   "returning INTERNAL_DB_CORRUPTION\n",
2674                                   (unsigned)trust_direction,
2675                                   account_name,
2676                                   ldb_dn_get_linearized(user_msg->dn),
2677                                   ldb_dn_get_linearized(tdo_msg->dn)));
2678                         TALLOC_FREE(frame);
2679                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
2680                 }
2681
2682                 old_val = ldb_msg_find_ldb_val(tdo_msg, "trustAuthIncoming");
2683                 if (old_val != NULL) {
2684                         ndr_err = ndr_pull_struct_blob(old_val, frame, &old_blob,
2685                                         (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2686                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2687                                 ldb_transaction_cancel(ldb);
2688                                 DEBUG(1, ("samdb_set_password_sid: "
2689                                           "failed(%s) to parse "
2690                                           "trustAuthOutgoing sAMAccountName[%s] "
2691                                           "DN[%s] TDO[%s], "
2692                                           "returning INTERNAL_DB_CORRUPTION\n",
2693                                           ndr_map_error2string(ndr_err),
2694                                           account_name,
2695                                           ldb_dn_get_linearized(user_msg->dn),
2696                                           ldb_dn_get_linearized(tdo_msg->dn)));
2697
2698                                 TALLOC_FREE(frame);
2699                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2700                         }
2701                 }
2702
2703                 for (i = old_blob.current.count; i > 0; i--) {
2704                         struct AuthenticationInformation *a =
2705                                 &old_blob.current.array[i - 1];
2706
2707                         switch (a->AuthType) {
2708                         case TRUST_AUTH_TYPE_NONE:
2709                                 if (i == old_blob.current.count) {
2710                                         /*
2711                                          * remove TRUST_AUTH_TYPE_NONE at the
2712                                          * end
2713                                          */
2714                                         old_blob.current.count--;
2715                                 }
2716                                 break;
2717
2718                         case TRUST_AUTH_TYPE_VERSION:
2719                                 old_version_a = a;
2720                                 old_version = a->AuthInfo.version.version;
2721                                 break;
2722
2723                         case TRUST_AUTH_TYPE_CLEAR:
2724                                 break;
2725
2726                         case TRUST_AUTH_TYPE_NT4OWF:
2727                                 break;
2728                         }
2729                 }
2730
2731                 if (new_version == NULL) {
2732                         _new_version = 0;
2733                         new_version = &_new_version;
2734                 }
2735
2736                 if (old_version_a != NULL && *new_version != (old_version + 1)) {
2737                         old_version_a->LastUpdateTime = now;
2738                         old_version_a->AuthType = TRUST_AUTH_TYPE_NONE;
2739                 }
2740
2741                 new_blob.count = MAX(old_blob.current.count, 2);
2742                 new_blob.current.array = talloc_zero_array(frame,
2743                                                 struct AuthenticationInformation,
2744                                                 new_blob.count);
2745                 if (new_blob.current.array == NULL) {
2746                         ldb_transaction_cancel(ldb);
2747                         TALLOC_FREE(frame);
2748                         return NT_STATUS_NO_MEMORY;
2749                 }
2750                 new_blob.previous.array = talloc_zero_array(frame,
2751                                                 struct AuthenticationInformation,
2752                                                 new_blob.count);
2753                 if (new_blob.current.array == NULL) {
2754                         ldb_transaction_cancel(ldb);
2755                         TALLOC_FREE(frame);
2756                         return NT_STATUS_NO_MEMORY;
2757                 }
2758
2759                 for (i = 0; i < old_blob.current.count; i++) {
2760                         struct AuthenticationInformation *o =
2761                                 &old_blob.current.array[i];
2762                         struct AuthenticationInformation *p =
2763                                 &new_blob.previous.array[i];
2764
2765                         *p = *o;
2766                         new_blob.previous.count++;
2767                 }
2768                 for (; i < new_blob.count; i++) {
2769                         struct AuthenticationInformation *pi =
2770                                 &new_blob.previous.array[i];
2771
2772                         if (i == 0) {
2773                                 /*
2774                                  * new_blob.previous is still empty so
2775                                  * we'll do new_blob.previous = new_blob.current
2776                                  * below.
2777                                  */
2778                                 break;
2779                         }
2780
2781                         pi->LastUpdateTime = now;
2782                         pi->AuthType = TRUST_AUTH_TYPE_NONE;
2783                         new_blob.previous.count++;
2784                 }
2785
2786                 for (i = 0; i < new_blob.count; i++) {
2787                         struct AuthenticationInformation *ci =
2788                                 &new_blob.current.array[i];
2789
2790                         ci->LastUpdateTime = now;
2791                         switch (i) {
2792                         case 0:
2793                                 if (ntNewHash != NULL) {
2794                                         ci->AuthType = TRUST_AUTH_TYPE_NT4OWF;
2795                                         ci->AuthInfo.nt4owf.password = *ntNewHash;
2796                                         break;
2797                                 }
2798
2799                                 ci->AuthType = TRUST_AUTH_TYPE_CLEAR;
2800                                 ci->AuthInfo.clear.size = new_password->length;
2801                                 ci->AuthInfo.clear.password = new_password->data;
2802                                 break;
2803                         case 1:
2804                                 ci->AuthType = TRUST_AUTH_TYPE_VERSION;
2805                                 ci->AuthInfo.version.version = *new_version;
2806                                 break;
2807                         default:
2808                                 ci->AuthType = TRUST_AUTH_TYPE_NONE;
2809                                 break;
2810                         }
2811
2812                         new_blob.current.count++;
2813                 }
2814
2815                 if (new_blob.previous.count == 0) {
2816                         TALLOC_FREE(new_blob.previous.array);
2817                         new_blob.previous = new_blob.current;
2818                 }
2819
2820                 ndr_err = ndr_push_struct_blob(&new_val, frame, &new_blob,
2821                                 (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2822                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2823                         ldb_transaction_cancel(ldb);
2824                         DEBUG(1, ("samdb_set_password_sid: "
2825                                   "failed(%s) to generate "
2826                                   "trustAuthOutgoing sAMAccountName[%s] "
2827                                   "DN[%s] TDO[%s], "
2828                                   "returning UNSUCCESSFUL\n",
2829                                   ndr_map_error2string(ndr_err),
2830                                   account_name,
2831                                   ldb_dn_get_linearized(user_msg->dn),
2832                                   ldb_dn_get_linearized(tdo_msg->dn)));
2833                         TALLOC_FREE(frame);
2834                         return NT_STATUS_UNSUCCESSFUL;
2835                 }
2836
2837                 tdo_msg->num_elements = 0;
2838                 TALLOC_FREE(tdo_msg->elements);
2839
2840                 ret = ldb_msg_add_empty(tdo_msg, "trustAuthIncoming",
2841                                         LDB_FLAG_MOD_REPLACE, NULL);
2842                 if (ret != LDB_SUCCESS) {
2843                         ldb_transaction_cancel(ldb);
2844                         TALLOC_FREE(frame);
2845                         return NT_STATUS_NO_MEMORY;
2846                 }
2847                 ret = ldb_msg_add_value(tdo_msg, "trustAuthIncoming",
2848                                         &new_val, NULL);
2849                 if (ret != LDB_SUCCESS) {
2850                         ldb_transaction_cancel(ldb);
2851                         TALLOC_FREE(frame);
2852                         return NT_STATUS_NO_MEMORY;
2853                 }
2854
2855                 ret = ldb_modify(ldb, tdo_msg);
2856                 if (ret != LDB_SUCCESS) {
2857                         nt_status = dsdb_ldb_err_to_ntstatus(ret);
2858                         ldb_transaction_cancel(ldb);
2859                         DEBUG(1, ("samdb_set_password_sid: "
2860                                   "failed to replace "
2861                                   "trustAuthOutgoing sAMAccountName[%s] "
2862                                   "DN[%s] TDO[%s], "
2863                                   "%s - %s\n",
2864                                   account_name,
2865                                   ldb_dn_get_linearized(user_msg->dn),
2866                                   ldb_dn_get_linearized(tdo_msg->dn),
2867                                   nt_errstr(nt_status), ldb_errstring(ldb)));
2868                         TALLOC_FREE(frame);
2869                         return nt_status;
2870                 }
2871         }
2872
2873         nt_status = samdb_set_password_internal(ldb, mem_ctx,
2874                                                 user_msg->dn, NULL,
2875                                                 new_password,
2876                                                 lmNewHash, ntNewHash,
2877                                                 lmOldHash, ntOldHash,
2878                                                 reject_reason, _dominfo,
2879                                                 true); /* permit trusts */
2880         if (!NT_STATUS_IS_OK(nt_status)) {
2881                 ldb_transaction_cancel(ldb);
2882                 TALLOC_FREE(frame);
2883                 return nt_status;
2884         }
2885
2886         ret = ldb_transaction_commit(ldb);
2887         if (ret != LDB_SUCCESS) {
2888                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2889                          ldb_dn_get_linearized(user_msg->dn),
2890                          ldb_errstring(ldb)));
2891                 TALLOC_FREE(frame);
2892                 return NT_STATUS_TRANSACTION_ABORTED;
2893         }
2894
2895         TALLOC_FREE(frame);
2896         return NT_STATUS_OK;
2897 }
2898
2899
2900 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2901                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2902 {
2903         struct ldb_message *msg;
2904         struct ldb_dn *basedn;
2905         char *sidstr;
2906         int ret;
2907
2908         sidstr = dom_sid_string(mem_ctx, sid);
2909         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2910
2911         /* We might have to create a ForeignSecurityPrincipal, even if this user
2912          * is in our own domain */
2913
2914         msg = ldb_msg_new(sidstr);
2915         if (msg == NULL) {
2916                 talloc_free(sidstr);
2917                 return NT_STATUS_NO_MEMORY;
2918         }
2919
2920         ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2921                                 ldb_get_default_basedn(sam_ctx),
2922                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2923                                 &basedn);
2924         if (ret != LDB_SUCCESS) {
2925                 DEBUG(0, ("Failed to find DN for "
2926                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2927                 talloc_free(sidstr);
2928                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2929         }
2930
2931         /* add core elements to the ldb_message for the alias */
2932         msg->dn = basedn;
2933         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2934                 talloc_free(sidstr);
2935                 return NT_STATUS_NO_MEMORY;
2936         }
2937
2938         ret = ldb_msg_add_string(msg, "objectClass",
2939                                  "foreignSecurityPrincipal");
2940         if (ret != LDB_SUCCESS) {
2941                 talloc_free(sidstr);
2942                 return NT_STATUS_NO_MEMORY;
2943         }
2944
2945         /* create the alias */
2946         ret = ldb_add(sam_ctx, msg);
2947         if (ret != LDB_SUCCESS) {
2948                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2949                          "record %s: %s\n", 
2950                          ldb_dn_get_linearized(msg->dn),
2951                          ldb_errstring(sam_ctx)));
2952                 talloc_free(sidstr);
2953                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2954         }
2955
2956         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2957         talloc_free(sidstr);
2958
2959         return NT_STATUS_OK;
2960 }
2961
2962
2963 /*
2964   Find the DN of a domain, assuming it to be a dotted.dns name
2965 */
2966
2967 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2968 {
2969         unsigned int i;
2970         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2971         const char *binary_encoded;
2972         const char * const *split_realm;
2973         struct ldb_dn *dn;
2974
2975         if (!tmp_ctx) {
2976                 return NULL;
2977         }
2978
2979         split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
2980         if (!split_realm) {
2981                 talloc_free(tmp_ctx);
2982                 return NULL;
2983         }
2984         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2985         for (i=0; split_realm[i]; i++) {
2986                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2987                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2988                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2989                                   binary_encoded, ldb_dn_get_linearized(dn)));
2990                         talloc_free(tmp_ctx);
2991                         return NULL;
2992                 }
2993         }
2994         if (!ldb_dn_validate(dn)) {
2995                 DEBUG(2, ("Failed to validated DN %s\n",
2996                           ldb_dn_get_linearized(dn)));
2997                 talloc_free(tmp_ctx);
2998                 return NULL;
2999         }
3000         talloc_free(tmp_ctx);
3001         return dn;
3002 }
3003
3004
3005 /*
3006   Find the DNS equivalent of a DN, in dotted DNS form
3007 */
3008 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
3009 {
3010         int i, num_components = ldb_dn_get_comp_num(dn);
3011         char *dns_name = talloc_strdup(mem_ctx, "");
3012         if (dns_name == NULL) {
3013                 return NULL;
3014         }
3015
3016         for (i=0; i<num_components; i++) {
3017                 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
3018                 char *s;
3019                 if (v == NULL) {
3020                         talloc_free(dns_name);
3021                         return NULL;
3022                 }
3023                 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
3024                                                   (int)v->length, (int)v->length, (char *)v->data);
3025                 if (s == NULL) {
3026                         talloc_free(dns_name);
3027                         return NULL;
3028                 }
3029                 dns_name = s;
3030         }
3031
3032         /* remove the last '.' */
3033         if (dns_name[0] != 0) {
3034                 dns_name[strlen(dns_name)-1] = 0;
3035         }
3036
3037         return dns_name;
3038 }
3039
3040 /*
3041   Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
3042   name is based on the forest DNS name
3043 */
3044 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
3045                                 TALLOC_CTX *mem_ctx,
3046                                 const struct GUID *ntds_guid)
3047 {
3048         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3049         const char *guid_str;
3050         struct ldb_dn *forest_dn;
3051         const char *dnsforest;
3052         char *ret;
3053
3054         guid_str = GUID_string(tmp_ctx, ntds_guid);
3055         if (guid_str == NULL) {
3056                 talloc_free(tmp_ctx);
3057                 return NULL;
3058         }
3059         forest_dn = ldb_get_root_basedn(samdb);
3060         if (forest_dn == NULL) {
3061                 talloc_free(tmp_ctx);
3062                 return NULL;
3063         }
3064         dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
3065         if (dnsforest == NULL) {
3066                 talloc_free(tmp_ctx);
3067                 return NULL;
3068         }
3069         ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
3070         talloc_free(tmp_ctx);
3071         return ret;
3072 }
3073
3074
3075 /*
3076   Find the DN of a domain, be it the netbios or DNS name 
3077 */
3078 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
3079                                   const char *domain_name) 
3080 {
3081         const char * const domain_ref_attrs[] = {
3082                 "ncName", NULL
3083         };
3084         const char * const domain_ref2_attrs[] = {
3085                 NULL
3086         };
3087         struct ldb_result *res_domain_ref;
3088         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
3089         /* find the domain's DN */
3090         int ret_domain = ldb_search(ldb, mem_ctx,
3091                                             &res_domain_ref, 
3092                                             samdb_partitions_dn(ldb, mem_ctx), 
3093                                             LDB_SCOPE_ONELEVEL, 
3094                                             domain_ref_attrs,
3095                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
3096                                             escaped_domain);
3097         if (ret_domain != LDB_SUCCESS) {
3098                 return NULL;
3099         }
3100
3101         if (res_domain_ref->count == 0) {
3102                 ret_domain = ldb_search(ldb, mem_ctx,
3103                                                 &res_domain_ref, 
3104                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
3105                                                 LDB_SCOPE_BASE,
3106                                                 domain_ref2_attrs,
3107                                                 "(objectclass=domain)");
3108                 if (ret_domain != LDB_SUCCESS) {
3109                         return NULL;
3110                 }
3111
3112                 if (res_domain_ref->count == 1) {
3113                         return res_domain_ref->msgs[0]->dn;
3114                 }
3115                 return NULL;
3116         }
3117
3118         if (res_domain_ref->count > 1) {
3119                 DEBUG(0,("Found %d records matching domain [%s]\n", 
3120                          ret_domain, domain_name));
3121                 return NULL;
3122         }
3123
3124         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
3125
3126 }
3127
3128
3129 /*
3130   use a GUID to find a DN
3131  */
3132 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
3133                          TALLOC_CTX *mem_ctx,
3134                          const struct GUID *guid,
3135                          uint32_t dsdb_flags,
3136                          struct ldb_dn **dn)
3137 {
3138         int ret;
3139         struct ldb_result *res;
3140         const char *attrs[] = { NULL };
3141         char *guid_str = GUID_string(mem_ctx, guid);
3142
3143         if (!guid_str) {
3144                 return ldb_operr(ldb);
3145         }
3146
3147         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3148                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3149                           DSDB_SEARCH_SHOW_EXTENDED_DN |
3150                           DSDB_SEARCH_ONE_ONLY | dsdb_flags,
3151                           "objectGUID=%s", guid_str);
3152         talloc_free(guid_str);
3153         if (ret != LDB_SUCCESS) {
3154                 return ret;
3155         }
3156
3157         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3158         talloc_free(res);
3159
3160         return LDB_SUCCESS;
3161 }
3162
3163 /*
3164   use a DN to find a GUID with a given attribute name
3165  */
3166 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
3167                               struct ldb_dn *dn, const char *attribute,
3168                               struct GUID *guid)
3169 {
3170         int ret;
3171         struct ldb_result *res;
3172         const char *attrs[2];
3173         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3174
3175         attrs[0] = attribute;
3176         attrs[1] = NULL;
3177
3178         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3179                              DSDB_SEARCH_SHOW_DELETED |
3180                              DSDB_SEARCH_SHOW_RECYCLED);
3181         if (ret != LDB_SUCCESS) {
3182                 talloc_free(tmp_ctx);
3183                 return ret;
3184         }
3185         if (res->count < 1) {
3186                 talloc_free(tmp_ctx);
3187                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3188         }
3189         *guid = samdb_result_guid(res->msgs[0], attribute);
3190         talloc_free(tmp_ctx);
3191         return LDB_SUCCESS;
3192 }
3193
3194 /*
3195   use a DN to find a GUID
3196  */
3197 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
3198                          struct ldb_dn *dn, struct GUID *guid)
3199 {
3200         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
3201 }
3202
3203
3204
3205 /*
3206  adds the given GUID to the given ldb_message. This value is added
3207  for the given attr_name (may be either "objectGUID" or "parentGUID").
3208  */
3209 int dsdb_msg_add_guid(struct ldb_message *msg,
3210                 struct GUID *guid,
3211                 const char *attr_name)
3212 {
3213         int ret;
3214         struct ldb_val v;
3215         NTSTATUS status;
3216         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
3217
3218         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
3219         if (!NT_STATUS_IS_OK(status)) {
3220                 ret = LDB_ERR_OPERATIONS_ERROR;
3221                 goto done;
3222         }
3223
3224         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
3225         if (ret != LDB_SUCCESS) {
3226                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
3227                                          attr_name));
3228                 goto done;
3229         }
3230
3231         ret = LDB_SUCCESS;
3232
3233 done:
3234         talloc_free(tmp_ctx);
3235         return ret;
3236
3237 }
3238
3239
3240 /*
3241   use a DN to find a SID
3242  */
3243 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
3244                         struct ldb_dn *dn, struct dom_sid *sid)
3245 {
3246         int ret;
3247         struct ldb_result *res;
3248         const char *attrs[] = { "objectSid", NULL };
3249         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3250         struct dom_sid *s;
3251
3252         ZERO_STRUCTP(sid);
3253
3254         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
3255                              DSDB_SEARCH_SHOW_DELETED |
3256                              DSDB_SEARCH_SHOW_RECYCLED);
3257         if (ret != LDB_SUCCESS) {
3258                 talloc_free(tmp_ctx);
3259                 return ret;
3260         }
3261         if (res->count < 1) {
3262                 talloc_free(tmp_ctx);
3263                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3264         }
3265         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
3266         if (s == NULL) {
3267                 talloc_free(tmp_ctx);
3268                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3269         }
3270         *sid = *s;
3271         talloc_free(tmp_ctx);
3272         return LDB_SUCCESS;
3273 }
3274
3275 /*
3276   use a SID to find a DN
3277  */
3278 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
3279                         TALLOC_CTX *mem_ctx,
3280                         struct dom_sid *sid, struct ldb_dn **dn)
3281 {
3282         int ret;
3283         struct ldb_result *res;
3284         const char *attrs[] = { NULL };
3285         char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
3286
3287         if (!sid_str) {
3288                 return ldb_operr(ldb);
3289         }
3290
3291         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3292                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3293                           DSDB_SEARCH_SHOW_EXTENDED_DN |
3294                           DSDB_SEARCH_ONE_ONLY,
3295                           "objectSid=%s", sid_str);
3296         talloc_free(sid_str);
3297         if (ret != LDB_SUCCESS) {
3298                 return ret;
3299         }
3300
3301         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
3302         talloc_free(res);
3303
3304         return LDB_SUCCESS;
3305 }
3306
3307 /*
3308   load a repsFromTo blob list for a given partition GUID
3309   attr must be "repsFrom" or "repsTo"
3310  */
3311 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3312                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
3313 {
3314         const char *attrs[] = { attr, NULL };
3315         struct ldb_result *res = NULL;
3316         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3317         unsigned int i;
3318         struct ldb_message_element *el;
3319         int ret;
3320
3321         *r = NULL;
3322         *count = 0;
3323
3324         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
3325         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3326                 /* partition hasn't been replicated yet */
3327                 return WERR_OK;
3328         }
3329         if (ret != LDB_SUCCESS) {
3330                 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
3331                 talloc_free(tmp_ctx);
3332                 return WERR_DS_DRA_INTERNAL_ERROR;
3333         }
3334
3335         el = ldb_msg_find_element(res->msgs[0], attr);
3336         if (el == NULL) {
3337                 /* it's OK to be empty */
3338                 talloc_free(tmp_ctx);
3339                 return WERR_OK;
3340         }
3341
3342         *count = el->num_values;
3343         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
3344         if (*r == NULL) {
3345                 talloc_free(tmp_ctx);
3346                 return WERR_DS_DRA_INTERNAL_ERROR;
3347         }
3348
3349         for (i=0; i<(*count); i++) {
3350                 enum ndr_err_code ndr_err;
3351                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
3352                                                mem_ctx, 
3353                                                &(*r)[i], 
3354                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3355                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3356                         talloc_free(tmp_ctx);
3357                         return WERR_DS_DRA_INTERNAL_ERROR;
3358                 }
3359         }
3360
3361         talloc_free(tmp_ctx);
3362         
3363         return WERR_OK;
3364 }
3365
3366 /*
3367   save the repsFromTo blob list for a given partition GUID
3368   attr must be "repsFrom" or "repsTo"
3369  */
3370 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3371                      const char *attr, struct repsFromToBlob *r, uint32_t count)
3372 {
3373         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3374         struct ldb_message *msg;
3375         struct ldb_message_element *el;
3376         unsigned int i;
3377
3378         msg = ldb_msg_new(tmp_ctx);
3379         msg->dn = dn;
3380         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
3381                 goto failed;
3382         }
3383
3384         el->values = talloc_array(msg, struct ldb_val, count);
3385         if (!el->values) {
3386                 goto failed;
3387         }
3388
3389         for (i=0; i<count; i++) {
3390                 struct ldb_val v;
3391                 enum ndr_err_code ndr_err;
3392
3393                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, 
3394                                                &r[i], 
3395                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3396                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3397                         goto failed;
3398                 }
3399
3400                 el->num_values++;
3401                 el->values[i] = v;
3402         }
3403
3404         if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
3405                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
3406                 goto failed;
3407         }
3408
3409         talloc_free(tmp_ctx);
3410         
3411         return WERR_OK;
3412
3413 failed:
3414         talloc_free(tmp_ctx);
3415         return WERR_DS_DRA_INTERNAL_ERROR;
3416 }
3417
3418
3419 /*
3420   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
3421   object for a partition
3422  */
3423 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
3424                                 uint64_t *uSN, uint64_t *urgent_uSN)
3425 {
3426         struct ldb_request *req;
3427         int ret;
3428         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3429         struct dsdb_control_current_partition *p_ctrl;
3430         struct ldb_result *res;
3431
3432         res = talloc_zero(tmp_ctx, struct ldb_result);
3433         if (!res) {
3434                 talloc_free(tmp_ctx);
3435                 return ldb_oom(ldb);
3436         }
3437
3438         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3439                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
3440                                    LDB_SCOPE_BASE,
3441                                    NULL, NULL,
3442                                    NULL,
3443                                    res, ldb_search_default_callback,
3444                                    NULL);
3445         if (ret != LDB_SUCCESS) {
3446                 talloc_free(tmp_ctx);
3447                 return ret;
3448         }
3449
3450         p_ctrl = talloc(req, struct dsdb_control_current_partition);
3451         if (p_ctrl == NULL) {
3452                 talloc_free(tmp_ctx);
3453                 return ldb_oom(ldb);
3454         }
3455         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
3456         p_ctrl->dn = dn;
3457         
3458         ret = ldb_request_add_control(req,
3459                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
3460                                       false, p_ctrl);
3461         if (ret != LDB_SUCCESS) {
3462                 talloc_free(tmp_ctx);
3463                 return ret;
3464         }
3465         
3466         /* Run the new request */
3467         ret = ldb_request(ldb, req);
3468         
3469         if (ret == LDB_SUCCESS) {
3470                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3471         }
3472
3473         if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
3474                 /* it hasn't been created yet, which means
3475                    an implicit value of zero */
3476                 *uSN = 0;
3477                 talloc_free(tmp_ctx);
3478                 return LDB_SUCCESS;
3479         }
3480
3481         if (ret != LDB_SUCCESS) {
3482                 talloc_free(tmp_ctx);
3483                 return ret;
3484         }
3485
3486         if (res->count < 1) {
3487                 *uSN = 0;
3488                 if (urgent_uSN) {
3489                         *urgent_uSN = 0;
3490                 }
3491         } else {
3492                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
3493                 if (urgent_uSN) {
3494                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
3495                 }
3496         }
3497
3498         talloc_free(tmp_ctx);
3499
3500         return LDB_SUCCESS;     
3501 }
3502
3503 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
3504                                                    const struct drsuapi_DsReplicaCursor2 *c2)
3505 {
3506         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3507 }
3508
3509 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
3510                                     const struct drsuapi_DsReplicaCursor *c2)
3511 {
3512         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
3513 }
3514
3515
3516 /*
3517   see if a computer identified by its invocationId is a RODC
3518 */
3519 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
3520 {
3521         /* 1) find the DN for this servers NTDSDSA object
3522            2) search for the msDS-isRODC attribute
3523            3) if not present then not a RODC
3524            4) if present and TRUE then is a RODC
3525         */
3526         struct ldb_dn *config_dn;
3527         const char *attrs[] = { "msDS-isRODC", NULL };
3528         int ret;
3529         struct ldb_result *res;
3530         TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
3531
3532         config_dn = ldb_get_config_basedn(sam_ctx);
3533         if (!config_dn) {
3534                 talloc_free(tmp_ctx);
3535                 return ldb_operr(sam_ctx);
3536         }
3537
3538         ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
3539                           DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
3540
3541         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
3542                 *is_rodc = false;
3543                 talloc_free(tmp_ctx);
3544                 return LDB_SUCCESS;
3545         }
3546
3547         if (ret != LDB_SUCCESS) {
3548                 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
3549                          GUID_string(tmp_ctx, objectGUID)));
3550                 *is_rodc = false;
3551                 talloc_free(tmp_ctx);
3552                 return ret;
3553         }
3554
3555         ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
3556         *is_rodc = (ret == 1);
3557
3558         talloc_free(tmp_ctx);
3559         return LDB_SUCCESS;
3560 }
3561
3562
3563 /*
3564   see if we are a RODC
3565 */
3566 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
3567 {
3568         const struct GUID *objectGUID;
3569         int ret;
3570         bool *cached;
3571
3572         /* see if we have a cached copy */
3573         cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
3574         if (cached) {
3575                 *am_rodc = *cached;
3576                 return LDB_SUCCESS;
3577         }
3578
3579         objectGUID = samdb_ntds_objectGUID(sam_ctx);
3580         if (!objectGUID) {
3581                 return ldb_operr(sam_ctx);
3582         }
3583
3584         ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
3585         if (ret != LDB_SUCCESS) {
3586                 return ret;
3587         }
3588
3589         cached = talloc(sam_ctx, bool);
3590         if (cached == NULL) {
3591                 return ldb_oom(sam_ctx);
3592         }
3593         *cached = *am_rodc;
3594
3595         ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
3596         if (ret != LDB_SUCCESS) {
3597                 talloc_free(cached);
3598                 return ldb_operr(sam_ctx);
3599         }
3600
3601         return LDB_SUCCESS;
3602 }
3603
3604 int samdb_dns_host_name(struct ldb_context *sam_ctx, const char **host_name)
3605 {
3606         const char *_host_name = NULL;
3607         const char *attrs[] = { "dnsHostName", NULL };
3608         TALLOC_CTX *tmp_ctx = NULL;
3609         int ret;
3610         struct ldb_result *res = NULL;
3611
3612         _host_name = (const char *)ldb_get_opaque(sam_ctx, "cache.dns_host_name");
3613         if (_host_name != NULL) {
3614                 *host_name = _host_name;
3615                 return LDB_SUCCESS;
3616         }
3617
3618         tmp_ctx = talloc_new(sam_ctx);
3619
3620         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, NULL, attrs, 0);
3621
3622         if (res->count != 1 || ret != LDB_SUCCESS) {
3623                 DEBUG(0, ("Failed to get rootDSE for dnsHostName: %s",
3624                           ldb_errstring(sam_ctx)));
3625                 TALLOC_FREE(tmp_ctx);
3626                 return ret;
3627         }
3628
3629
3630         _host_name = ldb_msg_find_attr_as_string(res->msgs[0],
3631                                                  "dnsHostName",
3632                                                  NULL);
3633         if (_host_name == NULL) {
3634                 DEBUG(0, ("Failed to get dnsHostName from rootDSE"));
3635                 TALLOC_FREE(tmp_ctx);
3636                 return LDB_ERR_OPERATIONS_ERROR;
3637         }
3638         ret = ldb_set_opaque(sam_ctx, "cache.dns_host_name",
3639                              discard_const_p(char *, _host_name));
3640         if (ret != LDB_SUCCESS) {
3641                 TALLOC_FREE(tmp_ctx);
3642                 return ldb_operr(sam_ctx);
3643         }
3644
3645         *host_name = talloc_steal(sam_ctx, _host_name);
3646
3647         TALLOC_FREE(tmp_ctx);
3648         return LDB_SUCCESS;
3649 }
3650
3651 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3652 {
3653         TALLOC_CTX *tmp_ctx;
3654         bool *cached;
3655
3656         tmp_ctx = talloc_new(ldb);
3657         if (tmp_ctx == NULL) {
3658                 goto failed;
3659         }
3660
3661         cached = talloc(tmp_ctx, bool);
3662         if (!cached) {
3663                 goto failed;
3664         }
3665
3666         *cached = am_rodc;
3667         if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3668                 goto failed;
3669         }
3670
3671         talloc_steal(ldb, cached);
3672         talloc_free(tmp_ctx);
3673         return true;
3674
3675 failed:
3676         DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3677         talloc_free(tmp_ctx);
3678         return false;
3679 }
3680
3681
3682 /*
3683  * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3684  * flags are DS_NTDSSETTINGS_OPT_*
3685  */
3686 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3687                                         uint32_t *options)
3688 {
3689         int rc;
3690         TALLOC_CTX *tmp_ctx;
3691         struct ldb_result *res;
3692         struct ldb_dn *site_dn;
3693         const char *attrs[] = { "options", NULL };
3694
3695         tmp_ctx = talloc_new(ldb_ctx);
3696         if (tmp_ctx == NULL)
3697                 goto failed;
3698
3699         /* Retrieve the site dn for the ldb that we
3700          * have open.  This is our local site.
3701          */
3702         site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3703         if (site_dn == NULL)
3704                 goto failed;
3705
3706         /* Perform a one level (child) search from the local
3707          * site distinguided name.   We're looking for the
3708          * "options" attribute within the nTDSSiteSettings
3709          * object
3710          */
3711         rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3712                         LDB_SCOPE_ONELEVEL, attrs,
3713                         "objectClass=nTDSSiteSettings");
3714
3715         if (rc != LDB_SUCCESS || res->count != 1)
3716                 goto failed;
3717
3718         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3719
3720         talloc_free(tmp_ctx);
3721
3722         return LDB_SUCCESS;
3723
3724 failed:
3725         DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3726         talloc_free(tmp_ctx);
3727         return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
3728 }
3729
3730 /*
3731   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
3732
3733   flags are DS_NTDS_OPTION_*
3734 */
3735 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3736 {
3737         TALLOC_CTX *tmp_ctx;
3738         const char *attrs[] = { "options", NULL };
3739         int ret;
3740         struct ldb_result *res;
3741
3742         tmp_ctx = talloc_new(ldb);
3743         if (tmp_ctx == NULL) {
3744                 goto failed;
3745         }
3746
3747         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3748         if (ret != LDB_SUCCESS) {
3749                 goto failed;
3750         }
3751
3752         if (res->count != 1) {
3753                 goto failed;
3754         }
3755
3756         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3757
3758         talloc_free(tmp_ctx);
3759
3760         return LDB_SUCCESS;
3761
3762 failed:
3763         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3764         talloc_free(tmp_ctx);
3765         return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3766 }
3767
3768 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3769 {
3770         const char *attrs[] = { "objectCategory", NULL };
3771         int ret;
3772         struct ldb_result *res;
3773
3774         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3775         if (ret != LDB_SUCCESS) {
3776                 goto failed;
3777         }
3778
3779         if (res->count != 1) {
3780                 goto failed;
3781         }
3782
3783         return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3784
3785 failed:
3786         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3787         return NULL;
3788 }
3789
3790 /*
3791  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3792  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3793  */
3794 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3795 {
3796         char **tokens, *ret;
3797         size_t i;
3798
3799         tokens = str_list_make(mem_ctx, cn, " -_");
3800         if (tokens == NULL || tokens[0] == NULL) {
3801                 return NULL;
3802         }
3803
3804         /* "tolower()" and "toupper()" should also work properly on 0x00 */
3805         tokens[0][0] = tolower(tokens[0][0]);
3806         for (i = 1; tokens[i] != NULL; i++)
3807                 tokens[i][0] = toupper(tokens[i][0]);
3808
3809         ret = talloc_strdup(mem_ctx, tokens[0]);
3810         for (i = 1; tokens[i] != NULL; i++)
3811                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3812
3813         talloc_free(tokens);
3814
3815         return ret;
3816 }
3817
3818 /*
3819  * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3820  */
3821 int dsdb_functional_level(struct ldb_context *ldb)
3822 {
3823         int *domainFunctionality =
3824                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3825         if (!domainFunctionality) {
3826                 /* this is expected during initial provision */
3827                 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3828                 return DS_DOMAIN_FUNCTION_2000;
3829         }
3830         return *domainFunctionality;
3831 }
3832
3833 /*
3834  * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3835  */
3836 int dsdb_forest_functional_level(struct ldb_context *ldb)
3837 {
3838         int *forestFunctionality =
3839                 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3840         if (!forestFunctionality) {
3841                 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3842                 return DS_DOMAIN_FUNCTION_2000;
3843         }
3844         return *forestFunctionality;
3845 }
3846
3847 /*
3848   set a GUID in an extended DN structure
3849  */
3850 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3851 {
3852         struct ldb_val v;
3853         NTSTATUS status;
3854         int ret;
3855
3856         status = GUID_to_ndr_blob(guid, dn, &v);
3857         if (!NT_STATUS_IS_OK(status)) {
3858                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3859         }
3860
3861         ret = ldb_dn_set_extended_component(dn, component_name, &v);
3862         data_blob_free(&v);
3863         return ret;
3864 }
3865
3866 /*
3867   return a GUID from a extended DN structure
3868  */
3869 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3870 {
3871         const struct ldb_val *v;
3872
3873         v = ldb_dn_get_extended_component(dn, component_name);
3874         if (v == NULL) {
3875                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3876         }
3877
3878         return GUID_from_ndr_blob(v, guid);
3879 }
3880
3881 /*
3882   return a uint64_t from a extended DN structure
3883  */
3884 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3885 {
3886         const struct ldb_val *v;
3887
3888         v = ldb_dn_get_extended_component(dn, component_name);
3889         if (v == NULL) {
3890                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3891         }
3892
3893         /* Just check we don't allow the caller to fill our stack */
3894         if (v->length >= 64) {
3895                 return NT_STATUS_INVALID_PARAMETER;
3896         } else {
3897                 char s[v->length+1];
3898                 memcpy(s, v->data, v->length);
3899                 s[v->length] = 0;
3900
3901                 *val = strtoull(s, NULL, 0);
3902         }
3903         return NT_STATUS_OK;
3904 }
3905
3906 /*
3907   return a NTTIME from a extended DN structure
3908  */
3909 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3910 {
3911         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3912 }
3913
3914 /*
3915   return a uint32_t from a extended DN structure
3916  */
3917 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3918 {
3919         const struct ldb_val *v;
3920
3921         v = ldb_dn_get_extended_component(dn, component_name);
3922         if (v == NULL) {
3923                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3924         }
3925
3926         /* Just check we don't allow the caller to fill our stack */
3927         if (v->length >= 32) {
3928                 return NT_STATUS_INVALID_PARAMETER;
3929         } else {
3930                 char s[v->length + 1];
3931                 memcpy(s, v->data, v->length);
3932                 s[v->length] = 0;
3933                 *val = strtoul(s, NULL, 0);
3934         }
3935
3936         return NT_STATUS_OK;
3937 }
3938
3939 /*
3940   return a dom_sid from a extended DN structure
3941  */
3942 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3943 {
3944         const struct ldb_val *sid_blob;
3945         enum ndr_err_code ndr_err;
3946
3947         sid_blob = ldb_dn_get_extended_component(dn, component_name);
3948         if (!sid_blob) {
3949                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3950         }
3951
3952         ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
3953                                                    (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3954         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3955                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3956                 return status;
3957         }
3958
3959         return NT_STATUS_OK;
3960 }
3961
3962
3963 /*
3964   return RMD_FLAGS directly from a ldb_dn
3965   returns 0 if not found
3966  */
3967 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3968 {
3969         uint32_t rmd_flags = 0;
3970         NTSTATUS status = dsdb_get_extended_dn_uint32(dn, &rmd_flags,
3971                                                       "RMD_FLAGS");
3972         if (NT_STATUS_IS_OK(status)) {
3973                 return rmd_flags;
3974         }
3975         return 0;
3976 }
3977
3978 /*
3979   return RMD_FLAGS directly from a ldb_val for a DN
3980   returns 0 if RMD_FLAGS is not found
3981  */
3982 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3983 {
3984         const char *p;
3985         uint32_t flags;
3986         char *end;
3987
3988         if (val->length < 13) {
3989                 return 0;
3990         }
3991         p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3992         if (!p) {
3993                 return 0;
3994         }
3995         flags = strtoul(p+11, &end, 10);
3996         if (!end || *end != '>') {
3997                 /* it must end in a > */
3998                 return 0;
3999         }
4000         return flags;
4001 }
4002
4003 /*
4004   return true if a ldb_val containing a DN in storage form is deleted
4005  */
4006 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
4007 {
4008         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
4009 }
4010
4011 /*
4012   return true if a ldb_val containing a DN in storage form is
4013   in the upgraded w2k3 linked attribute format
4014  */
4015 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
4016 {
4017         return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
4018 }
4019
4020 /*
4021   return a DN for a wellknown GUID
4022  */
4023 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
4024                       struct ldb_dn *nc_root, const char *wk_guid,
4025                       struct ldb_dn **wkguid_dn)
4026 {
4027         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4028         const char *attrs[] = { NULL };
4029         int ret;
4030         struct ldb_dn *dn;
4031         struct ldb_result *res;
4032
4033         /* construct the magic WKGUID DN */
4034         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
4035                             wk_guid, ldb_dn_get_linearized(nc_root));
4036         if (!wkguid_dn) {
4037                 talloc_free(tmp_ctx);
4038                 return ldb_operr(samdb);
4039         }
4040
4041         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
4042                              DSDB_SEARCH_SHOW_DELETED |
4043                              DSDB_SEARCH_SHOW_RECYCLED);
4044         if (ret != LDB_SUCCESS) {
4045                 talloc_free(tmp_ctx);
4046                 return ret;
4047         }
4048
4049         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
4050         talloc_free(tmp_ctx);
4051         return LDB_SUCCESS;
4052 }
4053
4054
4055 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
4056 {
4057         return ldb_dn_compare(*dn1, *dn2);
4058 }
4059
4060 /*
4061   find a NC root given a DN within the NC
4062  */
4063 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
4064                       struct ldb_dn **nc_root)
4065 {
4066         const char *root_attrs[] = { "namingContexts", NULL };
4067         TALLOC_CTX *tmp_ctx;
4068         int ret;
4069         struct ldb_message_element *el;
4070         struct ldb_result *root_res;
4071         unsigned int i;
4072         struct ldb_dn **nc_dns;
4073
4074         tmp_ctx = talloc_new(samdb);
4075         if (tmp_ctx == NULL) {
4076                 return ldb_oom(samdb);
4077         }
4078
4079         ret = ldb_search(samdb, tmp_ctx, &root_res,
4080                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
4081         if (ret != LDB_SUCCESS || root_res->count == 0) {
4082                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
4083                 talloc_free(tmp_ctx);
4084                 return ret;
4085         }
4086
4087         el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
4088         if ((el == NULL) || (el->num_values < 3)) {
4089                 struct ldb_message *tmp_msg;
4090
4091                 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list.\n"));
4092
4093                 /* This generates a temporary list of NCs in order to let the
4094                  * provisioning work. */
4095                 tmp_msg = ldb_msg_new(tmp_ctx);
4096                 if (tmp_msg == NULL) {
4097                         talloc_free(tmp_ctx);
4098                         return ldb_oom(samdb);
4099                 }
4100                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4101                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
4102                 if (ret != LDB_SUCCESS) {
4103                         talloc_free(tmp_ctx);
4104                         return ret;
4105                 }
4106                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4107                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
4108                 if (ret != LDB_SUCCESS) {
4109                         talloc_free(tmp_ctx);
4110                         return ret;
4111                 }
4112                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
4113                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
4114                 if (ret != LDB_SUCCESS) {
4115                         talloc_free(tmp_ctx);
4116                         return ret;
4117                 }
4118                 el = &tmp_msg->elements[0];
4119         }
4120
4121        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
4122        if (!nc_dns) {
4123                talloc_free(tmp_ctx);
4124                return ldb_oom(samdb);
4125        }
4126
4127        for (i=0; i<el->num_values; i++) {
4128                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
4129                if (nc_dns[i] == NULL) {
4130                        talloc_free(tmp_ctx);
4131                        return ldb_operr(samdb);
4132                }
4133        }
4134
4135        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
4136
4137        for (i=0; i<el->num_values; i++) {
4138                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
4139                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
4140                        talloc_free(tmp_ctx);
4141                        return LDB_SUCCESS;
4142                }
4143        }
4144
4145        talloc_free(tmp_ctx);
4146        return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4147 }
4148
4149
4150 /*
4151   find the deleted objects DN for any object, by looking for the NC
4152   root, then looking up the wellknown GUID
4153  */
4154 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
4155                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
4156                                 struct ldb_dn **do_dn)
4157 {
4158         struct ldb_dn *nc_root;
4159         int ret;
4160
4161         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
4162         if (ret != LDB_SUCCESS) {
4163                 return ret;
4164         }
4165
4166         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
4167         talloc_free(nc_root);
4168         return ret;
4169 }
4170
4171 /*
4172   return the tombstoneLifetime, in days
4173  */
4174 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
4175 {
4176         struct ldb_dn *dn;
4177         dn = ldb_get_config_basedn(ldb);
4178         if (!dn) {
4179                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4180         }
4181         dn = ldb_dn_copy(ldb, dn);
4182         if (!dn) {
4183                 return ldb_operr(ldb);
4184         }
4185         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
4186          be a wellknown GUID for this */
4187         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
4188                 talloc_free(dn);
4189                 return ldb_operr(ldb);
4190         }
4191
4192         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
4193         talloc_free(dn);
4194         return LDB_SUCCESS;
4195 }
4196
4197 /*
4198   compare a ldb_val to a string case insensitively
4199  */
4200 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
4201 {
4202         size_t len = strlen(s);
4203         int ret;
4204         if (len > v->length) return 1;
4205         ret = strncasecmp(s, (const char *)v->data, v->length);
4206         if (ret != 0) return ret;
4207         if (v->length > len && v->data[len] != 0) {
4208                 return -1;
4209         }
4210         return 0;
4211 }
4212
4213
4214 /*
4215   load the UDV for a partition in v2 format
4216   The list is returned sorted, and with our local cursor added
4217  */
4218 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4219                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
4220 {
4221         static const char *attrs[] = { "replUpToDateVector", NULL };
4222         struct ldb_result *r;
4223         const struct ldb_val *ouv_value;
4224         unsigned int i;
4225         int ret;
4226         uint64_t highest_usn = 0;
4227         const struct GUID *our_invocation_id;
4228         static const struct timeval tv1970;
4229         NTTIME nt1970 = timeval_to_nttime(&tv1970);
4230
4231         ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
4232         if (ret != LDB_SUCCESS) {
4233                 return ret;
4234         }
4235
4236         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
4237         if (ouv_value) {
4238                 enum ndr_err_code ndr_err;
4239                 struct replUpToDateVectorBlob ouv;
4240
4241                 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
4242                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
4243                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4244                         talloc_free(r);
4245                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4246                 }
4247                 if (ouv.version != 2) {
4248                         /* we always store as version 2, and
4249                          * replUpToDateVector is not replicated
4250                          */
4251                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4252                 }
4253
4254                 *count = ouv.ctr.ctr2.count;
4255                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
4256         } else {
4257                 *count = 0;
4258                 *cursors = NULL;
4259         }
4260
4261         talloc_free(r);
4262
4263         our_invocation_id = samdb_ntds_invocation_id(samdb);
4264         if (!our_invocation_id) {
4265                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
4266                 talloc_free(*cursors);
4267                 return ldb_operr(samdb);
4268         }
4269
4270         ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
4271         if (ret != LDB_SUCCESS) {
4272                 /* nothing to add - this can happen after a vampire */
4273                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4274                 return LDB_SUCCESS;
4275         }
4276
4277         for (i=0; i<*count; i++) {
4278                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
4279                         (*cursors)[i].highest_usn = highest_usn;
4280                         (*cursors)[i].last_sync_success = nt1970;
4281                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4282                         return LDB_SUCCESS;
4283                 }
4284         }
4285
4286         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
4287         if (! *cursors) {
4288                 return ldb_oom(samdb);
4289         }
4290
4291         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
4292         (*cursors)[*count].highest_usn = highest_usn;
4293         (*cursors)[*count].last_sync_success = nt1970;
4294         (*count)++;
4295
4296         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4297
4298         return LDB_SUCCESS;
4299 }
4300
4301 /*
4302   load the UDV for a partition in version 1 format
4303   The list is returned sorted, and with our local cursor added
4304  */
4305 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4306                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
4307 {
4308         struct drsuapi_DsReplicaCursor2 *v2;
4309         uint32_t i;
4310         int ret;
4311
4312         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
4313         if (ret != LDB_SUCCESS) {
4314                 return ret;
4315         }
4316
4317         if (*count == 0) {
4318                 talloc_free(v2);
4319                 *cursors = NULL;
4320                 return LDB_SUCCESS;
4321         }
4322
4323         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
4324         if (*cursors == NULL) {
4325                 talloc_free(v2);
4326                 return ldb_oom(samdb);
4327         }
4328
4329         for (i=0; i<*count; i++) {
4330                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
4331                 (*cursors)[i].highest_usn = v2[i].highest_usn;
4332         }
4333         talloc_free(v2);
4334         return LDB_SUCCESS;
4335 }
4336
4337 /*
4338   add a set of controls to a ldb_request structure based on a set of
4339   flags. See util.h for a list of available flags
4340  */
4341 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
4342 {
4343         int ret;
4344         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
4345                 struct ldb_search_options_control *options;
4346                 /* Using the phantom root control allows us to search all partitions */
4347                 options = talloc(req, struct ldb_search_options_control);
4348                 if (options == NULL) {
4349                         return LDB_ERR_OPERATIONS_ERROR;
4350                 }
4351                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
4352
4353                 ret = ldb_request_add_control(req,
4354                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
4355                                               true, options);
4356                 if (ret != LDB_SUCCESS) {
4357                         return ret;
4358                 }
4359         }
4360
4361         if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
4362                 ret = ldb_request_add_control(req,
4363                                               DSDB_CONTROL_NO_GLOBAL_CATALOG,
4364                                               false, NULL);
4365                 if (ret != LDB_SUCCESS) {
4366                         return ret;
4367                 }
4368         }
4369
4370         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
4371                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
4372                 if (ret != LDB_SUCCESS) {
4373                         return ret;
4374                 }
4375         }
4376
4377         if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
4378                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
4379                 if (ret != LDB_SUCCESS) {
4380                         return ret;
4381                 }
4382         }
4383
4384         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
4385                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
4386                 if (ret != LDB_SUCCESS) {
4387                         return ret;
4388                 }
4389         }
4390
4391         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
4392                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
4393                 if (!extended_ctrl) {
4394                         return LDB_ERR_OPERATIONS_ERROR;
4395                 }
4396                 extended_ctrl->type = 1;
4397
4398                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
4399                 if (ret != LDB_SUCCESS) {
4400                         return ret;
4401                 }
4402         }
4403
4404         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
4405                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
4406                 if (ret != LDB_SUCCESS) {
4407                         return ret;
4408                 }
4409         }
4410
4411         if (dsdb_flags & DSDB_MODIFY_RELAX) {
4412                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
4413                 if (ret != LDB_SUCCESS) {
4414                         return ret;
4415                 }
4416         }
4417
4418         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
4419                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
4420                 if (ret != LDB_SUCCESS) {
4421                         return ret;
4422                 }
4423         }
4424
4425         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
4426                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
4427                 if (ret != LDB_SUCCESS) {
4428                         return ret;
4429                 }
4430         }
4431
4432         if (dsdb_flags & DSDB_TREE_DELETE) {
4433                 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
4434                 if (ret != LDB_SUCCESS) {
4435                         return ret;
4436                 }
4437         }
4438
4439         if (dsdb_flags & DSDB_PROVISION) {
4440                 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
4441                 if (ret != LDB_SUCCESS) {
4442                         return ret;
4443                 }
4444         }
4445
4446         /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
4447         if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
4448                 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
4449                 if (ret != LDB_SUCCESS) {
4450                         return ret;
4451                 }
4452         }
4453
4454         if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
4455                 /* 
4456                  * This must not be critical, as it will only be
4457                  * handled (and need to be handled) if the other
4458                  * attributes in the request bring password_hash into
4459                  * action
4460                  */
4461                 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
4462                 if (ret != LDB_SUCCESS) {
4463                         return ret;
4464                 }
4465         }
4466
4467         if (dsdb_flags & DSDB_REPLMD_VANISH_LINKS) {
4468                 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLMD_VANISH_LINKS, true, NULL);
4469                 if (ret != LDB_SUCCESS) {
4470                         return ret;
4471                 }
4472         }
4473
4474         if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
4475                 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
4476                 if (ret != LDB_SUCCESS) {
4477                         return ret;
4478                 }
4479         }
4480
4481         if (dsdb_flags & DSDB_FLAG_REPLICATED_UPDATE) {
4482                 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
4483                 if (ret != LDB_SUCCESS) {
4484                         return ret;
4485                 }
4486         }
4487
4488         return LDB_SUCCESS;
4489 }
4490
4491 /*
4492    returns true if a control with the specified "oid" exists
4493 */
4494 bool dsdb_request_has_control(struct ldb_request *req, const char *oid)
4495 {
4496         return (ldb_request_get_control(req, oid) != NULL);
4497 }
4498
4499 /*
4500   an add with a set of controls
4501 */
4502 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
4503              uint32_t dsdb_flags)
4504 {
4505         struct ldb_request *req;
4506         int ret;
4507
4508         ret = ldb_build_add_req(&req, ldb, ldb,
4509                                 message,
4510                                 NULL,
4511                                 NULL,
4512                                 ldb_op_default_callback,
4513                                 NULL);
4514
4515         if (ret != LDB_SUCCESS) return ret;
4516
4517         ret = dsdb_request_add_controls(req, dsdb_flags);
4518         if (ret != LDB_SUCCESS) {
4519                 talloc_free(req);
4520                 return ret;
4521         }
4522
4523         ret = dsdb_autotransaction_request(ldb, req);
4524
4525         talloc_free(req);
4526         return ret;
4527 }
4528
4529 /*
4530   a modify with a set of controls
4531 */
4532 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
4533                 uint32_t dsdb_flags)
4534 {
4535         struct ldb_request *req;
4536         int ret;
4537
4538         ret = ldb_build_mod_req(&req, ldb, ldb,
4539                                 message,
4540                                 NULL,
4541                                 NULL,
4542                                 ldb_op_default_callback,
4543                                 NULL);
4544
4545         if (ret != LDB_SUCCESS) return ret;
4546
4547         ret = dsdb_request_add_controls(req, dsdb_flags);
4548         if (ret != LDB_SUCCESS) {
4549                 talloc_free(req);
4550                 return ret;
4551         }
4552
4553         ret = dsdb_autotransaction_request(ldb, req);
4554
4555         talloc_free(req);
4556         return ret;
4557 }
4558
4559 /*
4560   a delete with a set of flags
4561 */
4562 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
4563                 uint32_t dsdb_flags)
4564 {
4565         struct ldb_request *req;
4566         int ret;
4567
4568         ret = ldb_build_del_req(&req, ldb, ldb,
4569                                 dn,
4570                                 NULL,
4571                                 NULL,
4572                                 ldb_op_default_callback,
4573                                 NULL);
4574
4575         if (ret != LDB_SUCCESS) return ret;
4576
4577         ret = dsdb_request_add_controls(req, dsdb_flags);
4578         if (ret != LDB_SUCCESS) {
4579                 talloc_free(req);
4580                 return ret;
4581         }
4582
4583         ret = dsdb_autotransaction_request(ldb, req);
4584
4585         talloc_free(req);
4586         return ret;
4587 }
4588
4589 /*
4590   like dsdb_modify() but set all the element flags to
4591   LDB_FLAG_MOD_REPLACE
4592  */
4593 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
4594 {
4595         unsigned int i;
4596
4597         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
4598         for (i=0;i<msg->num_elements;i++) {
4599                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
4600         }
4601
4602         return dsdb_modify(ldb, msg, dsdb_flags);
4603 }
4604
4605
4606 /*
4607   search for attrs on one DN, allowing for dsdb_flags controls
4608  */
4609 int dsdb_search_dn(struct ldb_context *ldb,
4610                    TALLOC_CTX *mem_ctx,
4611                    struct ldb_result **_result,
4612                    struct ldb_dn *basedn,
4613                    const char * const *attrs,
4614                    uint32_t dsdb_flags)
4615 {
4616         int ret;
4617         struct ldb_request *req;
4618         struct ldb_result *res;
4619
4620         res = talloc_zero(mem_ctx, struct ldb_result);
4621         if (!res) {
4622                 return ldb_oom(ldb);
4623         }
4624
4625         ret = ldb_build_search_req(&req, ldb, res,
4626                                    basedn,
4627                                    LDB_SCOPE_BASE,
4628                                    NULL,
4629                                    attrs,
4630                                    NULL,
4631                                    res,
4632                                    ldb_search_default_callback,
4633                                    NULL);
4634         if (ret != LDB_SUCCESS) {
4635                 talloc_free(res);
4636                 return ret;
4637         }
4638
4639         ret = dsdb_request_add_controls(req, dsdb_flags);
4640         if (ret != LDB_SUCCESS) {
4641                 talloc_free(res);
4642                 return ret;
4643         }
4644
4645         ret = ldb_request(ldb, req);
4646         if (ret == LDB_SUCCESS) {
4647                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4648         }
4649
4650         talloc_free(req);
4651         if (ret != LDB_SUCCESS) {
4652                 talloc_free(res);
4653                 return ret;
4654         }
4655
4656         *_result = res;
4657         return LDB_SUCCESS;
4658 }
4659
4660 /*
4661   search for attrs on one DN, by the GUID of the DN, allowing for
4662   dsdb_flags controls
4663  */
4664 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
4665                            TALLOC_CTX *mem_ctx,
4666                            struct ldb_result **_result,
4667                            const struct GUID *guid,
4668                            const char * const *attrs,
4669                            uint32_t dsdb_flags)
4670 {
4671         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4672         struct ldb_dn *dn;
4673         int ret;
4674
4675         dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
4676         if (dn == NULL) {
4677                 talloc_free(tmp_ctx);
4678                 return ldb_oom(ldb);
4679         }
4680
4681         ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
4682         talloc_free(tmp_ctx);
4683         return ret;
4684 }
4685
4686 /*
4687   general search with dsdb_flags for controls
4688  */
4689 int dsdb_search(struct ldb_context *ldb,
4690                 TALLOC_CTX *mem_ctx,
4691                 struct ldb_result **_result,
4692                 struct ldb_dn *basedn,
4693                 enum ldb_scope scope,
4694                 const char * const *attrs,
4695                 uint32_t dsdb_flags,
4696                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4697 {
4698         int ret;
4699         struct ldb_request *req;
4700         struct ldb_result *res;
4701         va_list ap;
4702         char *expression = NULL;
4703         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4704
4705         /* cross-partitions searches with a basedn break multi-domain support */
4706         SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
4707
4708         res = talloc_zero(tmp_ctx, struct ldb_result);
4709         if (!res) {
4710                 talloc_free(tmp_ctx);
4711                 return ldb_oom(ldb);
4712         }
4713
4714         if (exp_fmt) {
4715                 va_start(ap, exp_fmt);
4716                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4717                 va_end(ap);
4718
4719                 if (!expression) {
4720                         talloc_free(tmp_ctx);
4721                         return ldb_oom(ldb);
4722                 }
4723         }
4724
4725         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
4726                                    basedn,
4727                                    scope,
4728                                    expression,
4729                                    attrs,
4730                                    NULL,
4731                                    res,
4732                                    ldb_search_default_callback,
4733                                    NULL);
4734         if (ret != LDB_SUCCESS) {
4735                 talloc_free(tmp_ctx);
4736                 return ret;
4737         }
4738
4739         ret = dsdb_request_add_controls(req, dsdb_flags);
4740         if (ret != LDB_SUCCESS) {
4741                 talloc_free(tmp_ctx);
4742                 ldb_reset_err_string(ldb);
4743                 return ret;
4744         }
4745
4746         ret = ldb_request(ldb, req);
4747         if (ret == LDB_SUCCESS) {
4748                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4749         }
4750
4751         if (ret != LDB_SUCCESS) {
4752                 talloc_free(tmp_ctx);
4753                 return ret;
4754         }
4755
4756         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
4757                 if (res->count == 0) {
4758                         talloc_free(tmp_ctx);
4759                         ldb_reset_err_string(ldb);
4760                         return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4761                 }
4762                 if (res->count != 1) {
4763                         talloc_free(tmp_ctx);
4764                         ldb_reset_err_string(ldb);
4765                         return LDB_ERR_CONSTRAINT_VIOLATION;
4766                 }
4767         }
4768
4769         *_result = talloc_steal(mem_ctx, res);
4770         talloc_free(tmp_ctx);
4771
4772         return LDB_SUCCESS;
4773 }
4774
4775
4776 /*
4777   general search with dsdb_flags for controls
4778   returns exactly 1 record or an error
4779  */
4780 int dsdb_search_one(struct ldb_context *ldb,
4781                     TALLOC_CTX *mem_ctx,
4782                     struct ldb_message **msg,
4783                     struct ldb_dn *basedn,
4784                     enum ldb_scope scope,
4785                     const char * const *attrs,
4786                     uint32_t dsdb_flags,
4787                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4788 {
4789         int ret;
4790         struct ldb_result *res;
4791         va_list ap;
4792         char *expression = NULL;
4793         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4794
4795         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4796
4797         res = talloc_zero(tmp_ctx, struct ldb_result);
4798         if (!res) {
4799                 talloc_free(tmp_ctx);
4800                 return ldb_oom(ldb);
4801         }
4802
4803         if (exp_fmt) {
4804                 va_start(ap, exp_fmt);
4805                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4806                 va_end(ap);
4807
4808                 if (!expression) {
4809                         talloc_free(tmp_ctx);
4810                         return ldb_oom(ldb);
4811                 }
4812                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4813                                   dsdb_flags, "%s", expression);
4814         } else {
4815                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4816                                   dsdb_flags, NULL);
4817         }
4818
4819         if (ret != LDB_SUCCESS) {
4820                 talloc_free(tmp_ctx);
4821                 return ret;
4822         }
4823
4824         *msg = talloc_steal(mem_ctx, res->msgs[0]);
4825         talloc_free(tmp_ctx);
4826
4827         return LDB_SUCCESS;
4828 }
4829
4830 /* returns back the forest DNS name */
4831 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4832 {
4833         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4834                                                           ldb_get_root_basedn(ldb));
4835         char *p;
4836
4837         if (forest_name == NULL) {
4838                 return NULL;
4839         }
4840
4841         p = strchr(forest_name, '/');
4842         if (p) {
4843                 *p = '\0';
4844         }
4845
4846         return forest_name;
4847 }
4848
4849 /* returns back the default domain DNS name */
4850 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4851 {
4852         const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4853                                                           ldb_get_default_basedn(ldb));
4854         char *p;
4855
4856         if (domain_name == NULL) {
4857                 return NULL;
4858         }
4859
4860         p = strchr(domain_name, '/');
4861         if (p) {
4862                 *p = '\0';
4863         }
4864
4865         return domain_name;
4866 }
4867
4868 /*
4869    validate that an DSA GUID belongs to the specified user sid.
4870    The user SID must be a domain controller account (either RODC or
4871    RWDC)
4872  */
4873 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4874                            const struct GUID *dsa_guid,
4875                            const struct dom_sid *sid)
4876 {
4877         /* strategy:
4878             - find DN of record with the DSA GUID in the
4879               configuration partition (objectGUID)
4880             - remove "NTDS Settings" component from DN
4881             - do a base search on that DN for serverReference with
4882               extended-dn enabled
4883             - extract objectSid from resulting serverReference
4884               attribute
4885             - check this sid matches the sid argument
4886         */
4887         struct ldb_dn *config_dn;
4888         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4889         struct ldb_message *msg;
4890         const char *attrs1[] = { NULL };
4891         const char *attrs2[] = { "serverReference", NULL };
4892         int ret;
4893         struct ldb_dn *dn, *account_dn;
4894         struct dom_sid sid2;
4895         NTSTATUS status;
4896
4897         config_dn = ldb_get_config_basedn(ldb);
4898
4899         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4900                               attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4901         if (ret != LDB_SUCCESS) {
4902                 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4903                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4904                 talloc_free(tmp_ctx);
4905                 return ldb_operr(ldb);
4906         }
4907         dn = msg->dn;
4908
4909         if (!ldb_dn_remove_child_components(dn, 1)) {
4910                 talloc_free(tmp_ctx);
4911                 return ldb_operr(ldb);
4912         }
4913
4914         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4915                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4916                               "(objectClass=server)");
4917         if (ret != LDB_SUCCESS) {
4918                 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4919                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4920                 talloc_free(tmp_ctx);
4921                 return ldb_operr(ldb);
4922         }
4923
4924         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4925         if (account_dn == NULL) {
4926                 DEBUG(1,(__location__ ": Failed to find account dn "
4927                          "(serverReference) for %s, parent of DSA with "
4928                          "objectGUID %s, sid %s\n",
4929                          ldb_dn_get_linearized(msg->dn),
4930                          GUID_string(tmp_ctx, dsa_guid),
4931                          dom_sid_string(tmp_ctx, sid)));
4932                 talloc_free(tmp_ctx);
4933                 return ldb_operr(ldb);
4934         }
4935
4936         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4937         if (!NT_STATUS_IS_OK(status)) {
4938                 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4939                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4940                 talloc_free(tmp_ctx);
4941                 return ldb_operr(ldb);
4942         }
4943
4944         if (!dom_sid_equal(sid, &sid2)) {
4945                 /* someone is trying to spoof another account */
4946                 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4947                          GUID_string(tmp_ctx, dsa_guid),
4948                          dom_sid_string(tmp_ctx, sid),
4949                          dom_sid_string(tmp_ctx, &sid2)));
4950                 talloc_free(tmp_ctx);
4951                 return ldb_operr(ldb);
4952         }
4953
4954         talloc_free(tmp_ctx);
4955         return LDB_SUCCESS;
4956 }
4957
4958 static const char * const secret_attributes[] = {
4959         DSDB_SECRET_ATTRIBUTES,
4960         NULL
4961 };
4962
4963 /*
4964   check if the attribute belongs to the RODC filtered attribute set
4965   Note that attributes that are in the filtered attribute set are the
4966   ones that _are_ always sent to a RODC
4967 */
4968 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4969 {
4970         /* they never get secret attributes */
4971         if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4972                 return false;
4973         }
4974
4975         /* they do get non-secret critical attributes */
4976         if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4977                 return true;
4978         }
4979
4980         /* they do get non-secret attributes marked as being in the FAS  */
4981         if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4982                 return true;
4983         }
4984
4985         /* other attributes are denied */
4986         return false;
4987 }
4988
4989 /* return fsmo role dn and role owner dn for a particular role*/
4990 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4991                                struct ldb_context *ldb,
4992                                uint32_t role,
4993                                struct ldb_dn **fsmo_role_dn,
4994                                struct ldb_dn **role_owner_dn)
4995 {
4996         int ret;
4997         switch (role) {
4998         case DREPL_NAMING_MASTER:
4999                 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
5000                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5001                 if (ret != LDB_SUCCESS) {
5002                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
5003                                  ldb_errstring(ldb)));
5004                         talloc_free(tmp_ctx);
5005                         return WERR_DS_DRA_INTERNAL_ERROR;
5006                 }
5007                 break;
5008         case DREPL_INFRASTRUCTURE_MASTER:
5009                 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
5010                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5011                 if (ret != LDB_SUCCESS) {
5012                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5013                                  ldb_errstring(ldb)));
5014                         talloc_free(tmp_ctx);
5015                         return WERR_DS_DRA_INTERNAL_ERROR;
5016                 }
5017                 break;
5018         case DREPL_RID_MASTER:
5019                 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
5020                 if (ret != LDB_SUCCESS) {
5021                         DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
5022                         talloc_free(tmp_ctx);
5023                         return WERR_DS_DRA_INTERNAL_ERROR;
5024                 }
5025
5026                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5027                 if (ret != LDB_SUCCESS) {
5028                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
5029                                  ldb_errstring(ldb)));
5030                         talloc_free(tmp_ctx);
5031                         return WERR_DS_DRA_INTERNAL_ERROR;
5032                 }
5033                 break;
5034         case DREPL_SCHEMA_MASTER:
5035                 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
5036                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5037                 if (ret != LDB_SUCCESS) {
5038                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
5039                                  ldb_errstring(ldb)));
5040                         talloc_free(tmp_ctx);
5041                         return WERR_DS_DRA_INTERNAL_ERROR;
5042                 }
5043                 break;
5044         case DREPL_PDC_MASTER:
5045                 *fsmo_role_dn = ldb_get_default_basedn(ldb);
5046                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
5047                 if (ret != LDB_SUCCESS) {
5048                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
5049                                  ldb_errstring(ldb)));
5050                         talloc_free(tmp_ctx);
5051                         return WERR_DS_DRA_INTERNAL_ERROR;
5052                 }
5053                 break;
5054         default:
5055                 return WERR_DS_DRA_INTERNAL_ERROR;
5056         }
5057         return WERR_OK;
5058 }
5059
5060 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
5061                                     TALLOC_CTX *mem_ctx,
5062                                     struct ldb_dn *server_dn)
5063 {
5064         int ldb_ret;
5065         struct ldb_result *res = NULL;
5066         const char * const attrs[] = { "dNSHostName", NULL};
5067
5068         ldb_ret = ldb_search(ldb, mem_ctx, &res,
5069                              server_dn,
5070                              LDB_SCOPE_BASE,
5071                              attrs, NULL);
5072         if (ldb_ret != LDB_SUCCESS) {
5073                 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
5074                           ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
5075                 return NULL;
5076         }
5077
5078         return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
5079 }
5080
5081 /*
5082   returns true if an attribute is in the filter,
5083   false otherwise, provided that attribute value is provided with the expression
5084 */
5085 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
5086                              const char *attr)
5087 {
5088        unsigned int i;
5089        switch (tree->operation) {
5090        case LDB_OP_AND:
5091        case LDB_OP_OR:
5092                for (i=0;i<tree->u.list.num_elements;i++) {
5093                        if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
5094                                                        attr))
5095                                return true;
5096                }
5097                return false;
5098        case LDB_OP_NOT:
5099                return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
5100        case LDB_OP_EQUALITY:
5101        case LDB_OP_GREATER:
5102        case LDB_OP_LESS:
5103        case LDB_OP_APPROX:
5104                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
5105                        return true;
5106                }
5107                return false;
5108        case LDB_OP_SUBSTRING:
5109                if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
5110                        return true;
5111                }
5112                return false;
5113        case LDB_OP_PRESENT:
5114                /* (attrname=*) is not filtered out */
5115                return false;
5116        case LDB_OP_EXTENDED:
5117                if (tree->u.extended.attr &&
5118                    ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
5119                        return true;
5120                }
5121                return false;
5122        }
5123        return false;
5124 }
5125
5126 bool is_attr_in_list(const char * const * attrs, const char *attr)
5127 {
5128         unsigned int i;
5129
5130         for (i = 0; attrs[i]; i++) {
5131                 if (ldb_attr_cmp(attrs[i], attr) == 0)
5132                         return true;
5133         }
5134
5135         return false;
5136 }
5137
5138 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
5139                    const char *location, const char *func,
5140                    const char *reason)
5141 {
5142         if (reason == NULL) {
5143                 reason = win_errstr(werr);
5144         }
5145         ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
5146                                W_ERROR_V(werr), reason, location, func);
5147         return ldb_ecode;
5148 }
5149
5150 /*
5151   map an ldb error code to an approximate NTSTATUS code
5152  */
5153 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
5154 {
5155         switch (err) {
5156         case LDB_SUCCESS:
5157                 return NT_STATUS_OK;
5158
5159         case LDB_ERR_PROTOCOL_ERROR:
5160                 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
5161
5162         case LDB_ERR_TIME_LIMIT_EXCEEDED:
5163                 return NT_STATUS_IO_TIMEOUT;
5164
5165         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
5166                 return NT_STATUS_BUFFER_TOO_SMALL;
5167
5168         case LDB_ERR_COMPARE_FALSE:
5169         case LDB_ERR_COMPARE_TRUE:
5170                 return NT_STATUS_REVISION_MISMATCH;
5171
5172         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
5173                 return NT_STATUS_NOT_SUPPORTED;
5174
5175         case LDB_ERR_STRONG_AUTH_REQUIRED:
5176         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
5177         case LDB_ERR_SASL_BIND_IN_PROGRESS:
5178         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
5179         case LDB_ERR_INVALID_CREDENTIALS:
5180         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
5181         case LDB_ERR_UNWILLING_TO_PERFORM:
5182                 return NT_STATUS_ACCESS_DENIED;
5183
5184         case LDB_ERR_NO_SUCH_OBJECT:
5185                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
5186
5187         case LDB_ERR_REFERRAL:
5188         case LDB_ERR_NO_SUCH_ATTRIBUTE:
5189                 return NT_STATUS_NOT_FOUND;
5190
5191         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
5192                 return NT_STATUS_NOT_SUPPORTED;
5193
5194         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
5195                 return NT_STATUS_BUFFER_TOO_SMALL;
5196
5197         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
5198         case LDB_ERR_INAPPROPRIATE_MATCHING:
5199         case LDB_ERR_CONSTRAINT_VIOLATION:
5200         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
5201         case LDB_ERR_INVALID_DN_SYNTAX:
5202         case LDB_ERR_NAMING_VIOLATION:
5203         case LDB_ERR_OBJECT_CLASS_VIOLATION:
5204         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
5205         case LDB_ERR_NOT_ALLOWED_ON_RDN:
5206                 return NT_STATUS_INVALID_PARAMETER;
5207
5208         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
5209         case LDB_ERR_ENTRY_ALREADY_EXISTS:
5210                 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
5211
5212         case LDB_ERR_BUSY:
5213                 return NT_STATUS_NETWORK_BUSY;
5214
5215         case LDB_ERR_ALIAS_PROBLEM:
5216         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
5217         case LDB_ERR_UNAVAILABLE:
5218         case LDB_ERR_LOOP_DETECT:
5219         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
5220         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
5221         case LDB_ERR_OTHER:
5222         case LDB_ERR_OPERATIONS_ERROR:
5223                 break;
5224         }
5225         return NT_STATUS_UNSUCCESSFUL;
5226 }
5227
5228
5229 /*
5230   create a new naming context that will hold a partial replica
5231  */
5232 int dsdb_create_partial_replica_NC(struct ldb_context *ldb,  struct ldb_dn *dn)
5233 {
5234         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5235         struct ldb_message *msg;
5236         int ret;
5237
5238         msg = ldb_msg_new(tmp_ctx);
5239         if (msg == NULL) {
5240                 talloc_free(tmp_ctx);
5241                 return ldb_oom(ldb);
5242         }
5243
5244         msg->dn = dn;
5245         ret = ldb_msg_add_string(msg, "objectClass", "top");
5246         if (ret != LDB_SUCCESS) {
5247                 talloc_free(tmp_ctx);
5248                 return ldb_oom(ldb);
5249         }
5250
5251         /* [MS-DRSR] implies that we should only add the 'top'
5252          * objectclass, but that would cause lots of problems with our
5253          * objectclass code as top is not structural, so we add
5254          * 'domainDNS' as well to keep things sane. We're expecting
5255          * this new NC to be of objectclass domainDNS after
5256          * replication anyway
5257          */
5258         ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
5259         if (ret != LDB_SUCCESS) {
5260                 talloc_free(tmp_ctx);
5261                 return ldb_oom(ldb);
5262         }
5263
5264         ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
5265                               INSTANCE_TYPE_IS_NC_HEAD|
5266                               INSTANCE_TYPE_NC_ABOVE|
5267                               INSTANCE_TYPE_UNINSTANT);
5268         if (ret != LDB_SUCCESS) {
5269                 talloc_free(tmp_ctx);
5270                 return ldb_oom(ldb);
5271         }
5272
5273         ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
5274         if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
5275                 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
5276                          ldb_dn_get_linearized(dn),
5277                          ldb_errstring(ldb), ldb_strerror(ret)));
5278                 talloc_free(tmp_ctx);
5279                 return ret;
5280         }
5281
5282         DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
5283
5284         talloc_free(tmp_ctx);
5285         return LDB_SUCCESS;
5286 }
5287
5288 /**
5289   build a GUID from a string
5290 */
5291 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
5292 {
5293         NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
5294         uint32_t time_low;
5295         uint32_t time_mid, time_hi_and_version;
5296         uint32_t clock_seq[2];
5297         uint32_t node[6];
5298         int i;
5299
5300         if (s == NULL) {
5301                 return NT_STATUS_INVALID_PARAMETER;
5302         }
5303
5304         status =  parse_guid_string(s,
5305                                     &time_low,
5306                                     &time_mid,
5307                                     &time_hi_and_version,
5308                                     clock_seq,
5309                                     node);
5310
5311         if (!NT_STATUS_IS_OK(status)) {
5312                 return status;
5313         }
5314
5315         guid->time_low = time_low;
5316         guid->time_mid = time_mid;
5317         guid->time_hi_and_version = time_hi_and_version;
5318         guid->clock_seq[0] = clock_seq[0];
5319         guid->clock_seq[1] = clock_seq[1];
5320         for (i=0;i<6;i++) {
5321                 guid->node[i] = node[i];
5322         }
5323
5324         return NT_STATUS_OK;
5325 }
5326
5327 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
5328 {
5329         return talloc_asprintf(mem_ctx, 
5330                                "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5331                                guid->time_low, guid->time_mid,
5332                                guid->time_hi_and_version,
5333                                guid->clock_seq[0],
5334                                guid->clock_seq[1],
5335                                guid->node[0], guid->node[1],
5336                                guid->node[2], guid->node[3],
5337                                guid->node[4], guid->node[5]);
5338 }
5339
5340 /*
5341  * Return the effective badPwdCount
5342  *
5343  * This requires that the user_msg have (if present):
5344  *  - badPasswordTime
5345  *  - badPwdCount
5346  *
5347  * This also requires that the domain_msg have (if present):
5348  *  - lockOutObservationWindow
5349  */
5350 static int dsdb_effective_badPwdCount(const struct ldb_message *user_msg,
5351                                       int64_t lockOutObservationWindow,
5352                                       NTTIME now)
5353 {
5354         int64_t badPasswordTime;
5355         badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
5356
5357         if (badPasswordTime - lockOutObservationWindow >= now) {
5358                 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
5359         } else {
5360                 return 0;
5361         }
5362 }
5363
5364 /*
5365  * Returns a user's PSO, or NULL if none was found
5366  */
5367 static struct ldb_result *lookup_user_pso(struct ldb_context *sam_ldb,
5368                                           TALLOC_CTX *mem_ctx,
5369                                           const struct ldb_message *user_msg,
5370                                           const char * const *attrs)
5371 {
5372         struct ldb_result *res = NULL;
5373         struct ldb_dn *pso_dn = NULL;
5374         int ret;
5375
5376         /* if the user has a PSO that applies, then use the PSO's setting */
5377         pso_dn = ldb_msg_find_attr_as_dn(sam_ldb, mem_ctx, user_msg,
5378                                          "msDS-ResultantPSO");
5379
5380         if (pso_dn != NULL) {
5381
5382                 ret = dsdb_search_dn(sam_ldb, mem_ctx, &res, pso_dn, attrs, 0);
5383                 if (ret != LDB_SUCCESS) {
5384
5385                         /*
5386                          * log the error. The caller should fallback to using
5387                          * the default domain password settings
5388                          */
5389                         DBG_ERR("Error retrieving msDS-ResultantPSO %s for %s",
5390                                 ldb_dn_get_linearized(pso_dn),
5391                                 ldb_dn_get_linearized(user_msg->dn));
5392                 }
5393                 talloc_free(pso_dn);
5394         }
5395         return res;
5396 }
5397
5398 /*
5399  * Return the effective badPwdCount
5400  *
5401  * This requires that the user_msg have (if present):
5402  *  - badPasswordTime
5403  *  - badPwdCount
5404  *  - msDS-ResultantPSO
5405  */
5406 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
5407                                        TALLOC_CTX *mem_ctx,
5408                                        struct ldb_dn *domain_dn,
5409                                        const struct ldb_message *user_msg)
5410 {
5411         struct timeval tv_now = timeval_current();
5412         NTTIME now = timeval_to_nttime(&tv_now);
5413         int64_t lockOutObservationWindow;
5414         struct ldb_result *res = NULL;
5415         const char *attrs[] = { "msDS-LockoutObservationWindow",
5416                                 NULL };
5417
5418         res = lookup_user_pso(sam_ldb, mem_ctx, user_msg, attrs);
5419
5420         if (res != NULL) {
5421                 lockOutObservationWindow =
5422                         ldb_msg_find_attr_as_int64(res->msgs[0],
5423                                                    "msDS-LockoutObservationWindow",
5424                                                     DEFAULT_OBSERVATION_WINDOW);
5425                 talloc_free(res);
5426         } else {
5427
5428                 /* no PSO was found, lookup the default domain setting */
5429                 lockOutObservationWindow =
5430                          samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
5431                                             "lockOutObservationWindow", NULL);
5432         }
5433
5434         return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5435 }
5436
5437 /*
5438  * Returns the lockoutThreshold that applies. If a PSO is specified, then that
5439  * setting is used over the domain defaults
5440  */
5441 static int64_t get_lockout_threshold(struct ldb_message *domain_msg,
5442                                      struct ldb_message *pso_msg)
5443 {
5444         if (pso_msg != NULL) {
5445                 return ldb_msg_find_attr_as_int(pso_msg,
5446                                                 "msDS-LockoutThreshold", 0);
5447         } else {
5448                 return ldb_msg_find_attr_as_int(domain_msg,
5449                                                 "lockoutThreshold", 0);
5450         }
5451 }
5452
5453 /*
5454  * Returns the lockOutObservationWindow that applies. If a PSO is specified,
5455  * then that setting is used over the domain defaults
5456  */
5457 static int64_t get_lockout_observation_window(struct ldb_message *domain_msg,
5458                                               struct ldb_message *pso_msg)
5459 {
5460         if (pso_msg != NULL) {
5461                 return ldb_msg_find_attr_as_int64(pso_msg,
5462                                                   "msDS-LockoutObservationWindow",
5463                                                    DEFAULT_OBSERVATION_WINDOW);
5464         } else {
5465                 return ldb_msg_find_attr_as_int64(domain_msg,
5466                                                   "lockOutObservationWindow",
5467                                                    DEFAULT_OBSERVATION_WINDOW);
5468         }
5469 }
5470
5471 /*
5472  * Prepare an update to the badPwdCount and associated attributes.
5473  *
5474  * This requires that the user_msg have (if present):
5475  *  - objectSid
5476  *  - badPasswordTime
5477  *  - badPwdCount
5478  *
5479  * This also requires that the domain_msg have (if present):
5480  *  - pwdProperties
5481  *  - lockoutThreshold
5482  *  - lockOutObservationWindow
5483  *
5484  * This also requires that the pso_msg have (if present):
5485  *  - msDS-LockoutThreshold
5486  *  - msDS-LockoutObservationWindow
5487  */
5488 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
5489                                    struct ldb_context *sam_ctx,
5490                                    struct ldb_message *user_msg,
5491                                    struct ldb_message *domain_msg,
5492                                    struct ldb_message *pso_msg,
5493                                    struct ldb_message **_mod_msg)
5494 {
5495         int i, ret, badPwdCount;
5496         int64_t lockoutThreshold, lockOutObservationWindow;
5497         struct dom_sid *sid;
5498         struct timeval tv_now = timeval_current();
5499         NTTIME now = timeval_to_nttime(&tv_now);
5500         NTSTATUS status;
5501         uint32_t pwdProperties, rid = 0;
5502         struct ldb_message *mod_msg;
5503
5504         sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
5505
5506         pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
5507                                                   "pwdProperties", -1);
5508         if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
5509                 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
5510                 if (!NT_STATUS_IS_OK(status)) {
5511                         /*
5512                          * This can't happen anyway, but always try
5513                          * and update the badPwdCount on failure
5514                          */
5515                         rid = 0;
5516                 }
5517         }
5518         TALLOC_FREE(sid);
5519
5520         /*
5521          * Work out if we are doing password lockout on the domain.
5522          * Also, the built in administrator account is exempt:
5523          * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
5524          */
5525         lockoutThreshold = get_lockout_threshold(domain_msg, pso_msg);
5526         if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
5527                 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
5528                           ldb_dn_get_linearized(user_msg->dn)));
5529                 return NT_STATUS_OK;
5530         }
5531
5532         mod_msg = ldb_msg_new(mem_ctx);
5533         if (mod_msg == NULL) {
5534                 return NT_STATUS_NO_MEMORY;
5535         }
5536         mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
5537         if (mod_msg->dn == NULL) {
5538                 TALLOC_FREE(mod_msg);
5539                 return NT_STATUS_NO_MEMORY;
5540         }
5541
5542         lockOutObservationWindow = get_lockout_observation_window(domain_msg,
5543                                                                   pso_msg);
5544
5545         badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5546
5547         badPwdCount++;
5548
5549         ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
5550         if (ret != LDB_SUCCESS) {
5551                 TALLOC_FREE(mod_msg);
5552                 return NT_STATUS_NO_MEMORY;
5553         }
5554         ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
5555         if (ret != LDB_SUCCESS) {
5556                 TALLOC_FREE(mod_msg);
5557                 return NT_STATUS_NO_MEMORY;
5558         }
5559
5560         if (badPwdCount >= lockoutThreshold) {
5561                 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
5562                 if (ret != LDB_SUCCESS) {
5563                         TALLOC_FREE(mod_msg);
5564                         return NT_STATUS_NO_MEMORY;
5565                 }
5566                 DEBUGC( DBGC_AUTH, 1, ("Locked out user %s after %d wrong passwords\n",
5567                           ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5568         } else {
5569                 DEBUGC( DBGC_AUTH, 5, ("Updated badPwdCount on %s after %d wrong passwords\n",
5570                           ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5571         }
5572
5573         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5574         for (i=0; i< mod_msg->num_elements; i++) {
5575                 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5576         }
5577
5578         *_mod_msg = mod_msg;
5579         return NT_STATUS_OK;
5580 }
5581
5582 /**
5583  * Sets defaults for a User object
5584  * List of default attributes set:
5585  *      accountExpires, badPasswordTime, badPwdCount,
5586  *      codePage, countryCode, lastLogoff, lastLogon
5587  *      logonCount, pwdLastSet
5588  */
5589 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
5590                                struct ldb_message *usr_obj,
5591                                struct ldb_request *req)
5592 {
5593         int i, ret;
5594         const struct attribute_values {
5595                 const char *name;
5596                 const char *value;
5597                 const char *add_value;
5598                 const char *mod_value;
5599                 const char *control;
5600                 unsigned add_flags;
5601                 unsigned mod_flags;
5602         } map[] = {
5603                 {
5604                         .name = "accountExpires",
5605                         .add_value = "9223372036854775807",
5606                         .mod_value = "0",
5607                 },
5608                 {
5609                         .name = "badPasswordTime",
5610                         .value = "0"
5611                 },
5612                 {
5613                         .name = "badPwdCount",
5614                         .value = "0"
5615                 },
5616                 {
5617                         .name = "codePage",
5618                         .value = "0"
5619                 },
5620                 {
5621                         .name = "countryCode",
5622                         .value = "0"
5623                 },
5624                 {
5625                         .name = "lastLogoff",
5626                         .value = "0"
5627                 },
5628                 {
5629                         .name = "lastLogon",
5630                         .value = "0"
5631                 },
5632                 {
5633                         .name = "logonCount",
5634                         .value = "0"
5635                 },
5636                 {
5637                         .name = "logonHours",
5638                         .add_flags = DSDB_FLAG_INTERNAL_FORCE_META_DATA,
5639                 },
5640                 {
5641                         .name = "pwdLastSet",
5642                         .value = "0",
5643                         .control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
5644                 },
5645                 {
5646                         .name = "adminCount",
5647                         .mod_value = "0",
5648                 },
5649                 {
5650                         .name = "operatorCount",
5651                         .mod_value = "0",
5652                 },
5653         };
5654
5655         for (i = 0; i < ARRAY_SIZE(map); i++) {
5656                 bool added = false;
5657                 const char *value = NULL;
5658                 unsigned flags = 0;
5659
5660                 if (req != NULL && req->operation == LDB_ADD) {
5661                         value = map[i].add_value;
5662                         flags = map[i].add_flags;
5663                 } else {
5664                         value = map[i].mod_value;
5665                         flags = map[i].mod_flags;
5666                 }
5667
5668                 if (value == NULL) {
5669                         value = map[i].value;
5670                 }
5671
5672                 if (value != NULL) {
5673                         flags |= LDB_FLAG_MOD_ADD;
5674                 }
5675
5676                 if (flags == 0) {
5677                         continue;
5678                 }
5679
5680                 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
5681                                                      map[i].name,
5682                                                      value, flags,
5683                                                      &added);
5684                 if (ret != LDB_SUCCESS) {
5685                         return ret;
5686                 }
5687
5688                 if (req != NULL && added && map[i].control != NULL) {
5689                         ret = ldb_request_add_control(req,
5690                                                       map[i].control,
5691                                                       false, NULL);
5692                         if (ret != LDB_SUCCESS) {
5693                                 return ret;
5694                         }
5695                 }
5696         }
5697
5698         return LDB_SUCCESS;
5699 }
5700
5701 /**
5702  * Sets 'sAMAccountType on user object based on userAccountControl
5703  * @param ldb Current ldb_context
5704  * @param usr_obj ldb_message representing User object
5705  * @param user_account_control Value for userAccountControl flags
5706  * @param account_type_p Optional pointer to account_type to return
5707  * @return LDB_SUCCESS or LDB_ERR* code on failure
5708  */
5709 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
5710                                    uint32_t user_account_control, uint32_t *account_type_p)
5711 {
5712         int ret;
5713         uint32_t account_type;
5714         struct ldb_message_element *el;
5715
5716         account_type = ds_uf2atype(user_account_control);
5717         if (account_type == 0) {
5718                 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
5719                 return LDB_ERR_UNWILLING_TO_PERFORM;
5720         }
5721         ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5722                                  "sAMAccountType",
5723                                  account_type);
5724         if (ret != LDB_SUCCESS) {
5725                 return ret;
5726         }
5727         el = ldb_msg_find_element(usr_obj, "sAMAccountType");
5728         el->flags = LDB_FLAG_MOD_REPLACE;
5729
5730         if (account_type_p) {
5731                 *account_type_p = account_type;
5732         }
5733
5734         return LDB_SUCCESS;
5735 }
5736
5737 /**
5738  * Determine and set primaryGroupID based on userAccountControl value
5739  * @param ldb Current ldb_context
5740  * @param usr_obj ldb_message representing User object
5741  * @param user_account_control Value for userAccountControl flags
5742  * @param group_rid_p Optional pointer to group RID to return
5743  * @return LDB_SUCCESS or LDB_ERR* code on failure
5744  */
5745 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
5746                                        uint32_t user_account_control, uint32_t *group_rid_p)
5747 {
5748         int ret;
5749         uint32_t rid;
5750         struct ldb_message_element *el;
5751
5752         rid = ds_uf2prim_group_rid(user_account_control);
5753
5754         ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5755                                  "primaryGroupID", rid);
5756         if (ret != LDB_SUCCESS) {
5757                 return ret;
5758         }
5759         el = ldb_msg_find_element(usr_obj, "primaryGroupID");
5760         el->flags = LDB_FLAG_MOD_REPLACE;
5761
5762         if (group_rid_p) {
5763                 *group_rid_p = rid;
5764         }
5765
5766         return LDB_SUCCESS;
5767 }
5768
5769 /**
5770  * Returns True if the source and target DNs both have the same naming context,
5771  * i.e. they're both in the same partition.
5772  */
5773 bool dsdb_objects_have_same_nc(struct ldb_context *ldb,
5774                                TALLOC_CTX *mem_ctx,
5775                                struct ldb_dn *source_dn,
5776                                struct ldb_dn *target_dn)
5777 {
5778         TALLOC_CTX *tmp_ctx;
5779         struct ldb_dn *source_nc;
5780         struct ldb_dn *target_nc;
5781         int ret;
5782         bool same_nc = true;
5783
5784         tmp_ctx = talloc_new(mem_ctx);
5785
5786         ret = dsdb_find_nc_root(ldb, tmp_ctx, source_dn, &source_nc);
5787         if (ret != LDB_SUCCESS) {
5788                 DBG_ERR("Failed to find base DN for source %s\n",
5789                         ldb_dn_get_linearized(source_dn));
5790                 talloc_free(tmp_ctx);
5791                 return true;
5792         }
5793
5794         ret = dsdb_find_nc_root(ldb, tmp_ctx, target_dn, &target_nc);
5795         if (ret != LDB_SUCCESS) {
5796                 DBG_ERR("Failed to find base DN for target %s\n",
5797                         ldb_dn_get_linearized(target_dn));
5798                 talloc_free(tmp_ctx);
5799                 return true;
5800         }
5801
5802         same_nc = (ldb_dn_compare(source_nc, target_nc) == 0);
5803
5804         talloc_free(tmp_ctx);
5805
5806         return same_nc;
5807 }