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