dsdb: Ensure replication of renames works in schema partition
[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 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
3489 {
3490         TALLOC_CTX *tmp_ctx;
3491         bool *cached;
3492
3493         tmp_ctx = talloc_new(ldb);
3494         if (tmp_ctx == NULL) {
3495                 goto failed;
3496         }
3497
3498         cached = talloc(tmp_ctx, bool);
3499         if (!cached) {
3500                 goto failed;
3501         }
3502
3503         *cached = am_rodc;
3504         if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
3505                 goto failed;
3506         }
3507
3508         talloc_steal(ldb, cached);
3509         talloc_free(tmp_ctx);
3510         return true;
3511
3512 failed:
3513         DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
3514         talloc_free(tmp_ctx);
3515         return false;
3516 }
3517
3518
3519 /*
3520  * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
3521  * flags are DS_NTDSSETTINGS_OPT_*
3522  */
3523 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
3524                                         uint32_t *options)
3525 {
3526         int rc;
3527         TALLOC_CTX *tmp_ctx;
3528         struct ldb_result *res;
3529         struct ldb_dn *site_dn;
3530         const char *attrs[] = { "options", NULL };
3531
3532         tmp_ctx = talloc_new(ldb_ctx);
3533         if (tmp_ctx == NULL)
3534                 goto failed;
3535
3536         /* Retrieve the site dn for the ldb that we
3537          * have open.  This is our local site.
3538          */
3539         site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
3540         if (site_dn == NULL)
3541                 goto failed;
3542
3543         /* Perform a one level (child) search from the local
3544          * site distinguided name.   We're looking for the
3545          * "options" attribute within the nTDSSiteSettings
3546          * object
3547          */
3548         rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3549                         LDB_SCOPE_ONELEVEL, attrs,
3550                         "objectClass=nTDSSiteSettings");
3551
3552         if (rc != LDB_SUCCESS || res->count != 1)
3553                 goto failed;
3554
3555         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3556
3557         talloc_free(tmp_ctx);
3558
3559         return LDB_SUCCESS;
3560
3561 failed:
3562         DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3563         talloc_free(tmp_ctx);
3564         return ldb_error(ldb_ctx, LDB_ERR_NO_SUCH_OBJECT, __func__);
3565 }
3566
3567 /*
3568   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
3569
3570   flags are DS_NTDS_OPTION_*
3571 */
3572 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3573 {
3574         TALLOC_CTX *tmp_ctx;
3575         const char *attrs[] = { "options", NULL };
3576         int ret;
3577         struct ldb_result *res;
3578
3579         tmp_ctx = talloc_new(ldb);
3580         if (tmp_ctx == NULL) {
3581                 goto failed;
3582         }
3583
3584         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3585         if (ret != LDB_SUCCESS) {
3586                 goto failed;
3587         }
3588
3589         if (res->count != 1) {
3590                 goto failed;
3591         }
3592
3593         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3594
3595         talloc_free(tmp_ctx);
3596
3597         return LDB_SUCCESS;
3598
3599 failed:
3600         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3601         talloc_free(tmp_ctx);
3602         return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3603 }
3604
3605 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3606 {
3607         const char *attrs[] = { "objectCategory", NULL };
3608         int ret;
3609         struct ldb_result *res;
3610
3611         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3612         if (ret != LDB_SUCCESS) {
3613                 goto failed;
3614         }
3615
3616         if (res->count != 1) {
3617                 goto failed;
3618         }
3619
3620         return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3621
3622 failed:
3623         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3624         return NULL;
3625 }
3626
3627 /*
3628  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3629  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3630  */
3631 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3632 {
3633         char **tokens, *ret;
3634         size_t i;
3635
3636         tokens = str_list_make(mem_ctx, cn, " -_");
3637         if (tokens == NULL || tokens[0] == NULL) {
3638                 return NULL;
3639         }
3640
3641         /* "tolower()" and "toupper()" should also work properly on 0x00 */
3642         tokens[0][0] = tolower(tokens[0][0]);
3643         for (i = 1; tokens[i] != NULL; i++)
3644                 tokens[i][0] = toupper(tokens[i][0]);
3645
3646         ret = talloc_strdup(mem_ctx, tokens[0]);
3647         for (i = 1; tokens[i] != NULL; i++)
3648                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3649
3650         talloc_free(tokens);
3651
3652         return ret;
3653 }
3654
3655 /*
3656  * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3657  */
3658 int dsdb_functional_level(struct ldb_context *ldb)
3659 {
3660         int *domainFunctionality =
3661                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3662         if (!domainFunctionality) {
3663                 /* this is expected during initial provision */
3664                 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3665                 return DS_DOMAIN_FUNCTION_2000;
3666         }
3667         return *domainFunctionality;
3668 }
3669
3670 /*
3671  * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3672  */
3673 int dsdb_forest_functional_level(struct ldb_context *ldb)
3674 {
3675         int *forestFunctionality =
3676                 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3677         if (!forestFunctionality) {
3678                 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3679                 return DS_DOMAIN_FUNCTION_2000;
3680         }
3681         return *forestFunctionality;
3682 }
3683
3684 /*
3685   set a GUID in an extended DN structure
3686  */
3687 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3688 {
3689         struct ldb_val v;
3690         NTSTATUS status;
3691         int ret;
3692
3693         status = GUID_to_ndr_blob(guid, dn, &v);
3694         if (!NT_STATUS_IS_OK(status)) {
3695                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3696         }
3697
3698         ret = ldb_dn_set_extended_component(dn, component_name, &v);
3699         data_blob_free(&v);
3700         return ret;
3701 }
3702
3703 /*
3704   return a GUID from a extended DN structure
3705  */
3706 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3707 {
3708         const struct ldb_val *v;
3709
3710         v = ldb_dn_get_extended_component(dn, component_name);
3711         if (v == NULL) {
3712                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3713         }
3714
3715         return GUID_from_ndr_blob(v, guid);
3716 }
3717
3718 /*
3719   return a uint64_t from a extended DN structure
3720  */
3721 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3722 {
3723         const struct ldb_val *v;
3724
3725         v = ldb_dn_get_extended_component(dn, component_name);
3726         if (v == NULL) {
3727                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3728         }
3729
3730         /* Just check we don't allow the caller to fill our stack */
3731         if (v->length >= 64) {
3732                 return NT_STATUS_INVALID_PARAMETER;
3733         } else {
3734                 char s[v->length+1];
3735                 memcpy(s, v->data, v->length);
3736                 s[v->length] = 0;
3737
3738                 *val = strtoull(s, NULL, 0);
3739         }
3740         return NT_STATUS_OK;
3741 }
3742
3743 /*
3744   return a NTTIME from a extended DN structure
3745  */
3746 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3747 {
3748         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3749 }
3750
3751 /*
3752   return a uint32_t from a extended DN structure
3753  */
3754 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3755 {
3756         const struct ldb_val *v;
3757
3758         v = ldb_dn_get_extended_component(dn, component_name);
3759         if (v == NULL) {
3760                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3761         }
3762
3763         /* Just check we don't allow the caller to fill our stack */
3764         if (v->length >= 32) {
3765                 return NT_STATUS_INVALID_PARAMETER;
3766         } else {
3767                 char s[v->length + 1];
3768                 memcpy(s, v->data, v->length);
3769                 s[v->length] = 0;
3770                 *val = strtoul(s, NULL, 0);
3771         }
3772
3773         return NT_STATUS_OK;
3774 }
3775
3776 /*
3777   return a dom_sid from a extended DN structure
3778  */
3779 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3780 {
3781         const struct ldb_val *sid_blob;
3782         enum ndr_err_code ndr_err;
3783
3784         sid_blob = ldb_dn_get_extended_component(dn, component_name);
3785         if (!sid_blob) {
3786                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3787         }
3788
3789         ndr_err = ndr_pull_struct_blob_all_noalloc(sid_blob, sid,
3790                                                    (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3791         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3792                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3793                 return status;
3794         }
3795
3796         return NT_STATUS_OK;
3797 }
3798
3799
3800 /*
3801   return RMD_FLAGS directly from a ldb_dn
3802   returns 0 if not found
3803  */
3804 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3805 {
3806         uint32_t rmd_flags = 0;
3807         NTSTATUS status = dsdb_get_extended_dn_uint32(dn, &rmd_flags,
3808                                                       "RMD_FLAGS");
3809         if (NT_STATUS_IS_OK(status)) {
3810                 return rmd_flags;
3811         }
3812         return 0;
3813 }
3814
3815 /*
3816   return RMD_FLAGS directly from a ldb_val for a DN
3817   returns 0 if RMD_FLAGS is not found
3818  */
3819 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3820 {
3821         const char *p;
3822         uint32_t flags;
3823         char *end;
3824
3825         if (val->length < 13) {
3826                 return 0;
3827         }
3828         p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3829         if (!p) {
3830                 return 0;
3831         }
3832         flags = strtoul(p+11, &end, 10);
3833         if (!end || *end != '>') {
3834                 /* it must end in a > */
3835                 return 0;
3836         }
3837         return flags;
3838 }
3839
3840 /*
3841   return true if a ldb_val containing a DN in storage form is deleted
3842  */
3843 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3844 {
3845         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3846 }
3847
3848 /*
3849   return true if a ldb_val containing a DN in storage form is
3850   in the upgraded w2k3 linked attribute format
3851  */
3852 bool dsdb_dn_is_upgraded_link_val(const struct ldb_val *val)
3853 {
3854         return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
3855 }
3856
3857 /*
3858   return a DN for a wellknown GUID
3859  */
3860 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3861                       struct ldb_dn *nc_root, const char *wk_guid,
3862                       struct ldb_dn **wkguid_dn)
3863 {
3864         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3865         const char *attrs[] = { NULL };
3866         int ret;
3867         struct ldb_dn *dn;
3868         struct ldb_result *res;
3869
3870         /* construct the magic WKGUID DN */
3871         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3872                             wk_guid, ldb_dn_get_linearized(nc_root));
3873         if (!wkguid_dn) {
3874                 talloc_free(tmp_ctx);
3875                 return ldb_operr(samdb);
3876         }
3877
3878         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
3879                              DSDB_SEARCH_SHOW_DELETED |
3880                              DSDB_SEARCH_SHOW_RECYCLED);
3881         if (ret != LDB_SUCCESS) {
3882                 talloc_free(tmp_ctx);
3883                 return ret;
3884         }
3885
3886         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3887         talloc_free(tmp_ctx);
3888         return LDB_SUCCESS;
3889 }
3890
3891
3892 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3893 {
3894         return ldb_dn_compare(*dn1, *dn2);
3895 }
3896
3897 /*
3898   find a NC root given a DN within the NC
3899  */
3900 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3901                       struct ldb_dn **nc_root)
3902 {
3903         const char *root_attrs[] = { "namingContexts", NULL };
3904         TALLOC_CTX *tmp_ctx;
3905         int ret;
3906         struct ldb_message_element *el;
3907         struct ldb_result *root_res;
3908         unsigned int i;
3909         struct ldb_dn **nc_dns;
3910
3911         tmp_ctx = talloc_new(samdb);
3912         if (tmp_ctx == NULL) {
3913                 return ldb_oom(samdb);
3914         }
3915
3916         ret = ldb_search(samdb, tmp_ctx, &root_res,
3917                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3918         if (ret != LDB_SUCCESS || root_res->count == 0) {
3919                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3920                 talloc_free(tmp_ctx);
3921                 return ret;
3922         }
3923
3924         el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3925         if ((el == NULL) || (el->num_values < 3)) {
3926                 struct ldb_message *tmp_msg;
3927
3928                 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list."));
3929
3930                 /* This generates a temporary list of NCs in order to let the
3931                  * provisioning work. */
3932                 tmp_msg = ldb_msg_new(tmp_ctx);
3933                 if (tmp_msg == NULL) {
3934                         talloc_free(tmp_ctx);
3935                         return ldb_oom(samdb);
3936                 }
3937                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3938                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
3939                 if (ret != LDB_SUCCESS) {
3940                         talloc_free(tmp_ctx);
3941                         return ret;
3942                 }
3943                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3944                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
3945                 if (ret != LDB_SUCCESS) {
3946                         talloc_free(tmp_ctx);
3947                         return ret;
3948                 }
3949                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3950                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
3951                 if (ret != LDB_SUCCESS) {
3952                         talloc_free(tmp_ctx);
3953                         return ret;
3954                 }
3955                 el = &tmp_msg->elements[0];
3956         }
3957
3958        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3959        if (!nc_dns) {
3960                talloc_free(tmp_ctx);
3961                return ldb_oom(samdb);
3962        }
3963
3964        for (i=0; i<el->num_values; i++) {
3965                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3966                if (nc_dns[i] == NULL) {
3967                        talloc_free(tmp_ctx);
3968                        return ldb_operr(samdb);
3969                }
3970        }
3971
3972        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3973
3974        for (i=0; i<el->num_values; i++) {
3975                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3976                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3977                        talloc_free(tmp_ctx);
3978                        return LDB_SUCCESS;
3979                }
3980        }
3981
3982        talloc_free(tmp_ctx);
3983        return ldb_error(samdb, LDB_ERR_NO_SUCH_OBJECT, __func__);
3984 }
3985
3986
3987 /*
3988   find the deleted objects DN for any object, by looking for the NC
3989   root, then looking up the wellknown GUID
3990  */
3991 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3992                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3993                                 struct ldb_dn **do_dn)
3994 {
3995         struct ldb_dn *nc_root;
3996         int ret;
3997
3998         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3999         if (ret != LDB_SUCCESS) {
4000                 return ret;
4001         }
4002
4003         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
4004         talloc_free(nc_root);
4005         return ret;
4006 }
4007
4008 /*
4009   return the tombstoneLifetime, in days
4010  */
4011 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
4012 {
4013         struct ldb_dn *dn;
4014         dn = ldb_get_config_basedn(ldb);
4015         if (!dn) {
4016                 return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4017         }
4018         dn = ldb_dn_copy(ldb, dn);
4019         if (!dn) {
4020                 return ldb_operr(ldb);
4021         }
4022         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
4023          be a wellknown GUID for this */
4024         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
4025                 talloc_free(dn);
4026                 return ldb_operr(ldb);
4027         }
4028
4029         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
4030         talloc_free(dn);
4031         return LDB_SUCCESS;
4032 }
4033
4034 /*
4035   compare a ldb_val to a string case insensitively
4036  */
4037 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
4038 {
4039         size_t len = strlen(s);
4040         int ret;
4041         if (len > v->length) return 1;
4042         ret = strncasecmp(s, (const char *)v->data, v->length);
4043         if (ret != 0) return ret;
4044         if (v->length > len && v->data[len] != 0) {
4045                 return -1;
4046         }
4047         return 0;
4048 }
4049
4050
4051 /*
4052   load the UDV for a partition in v2 format
4053   The list is returned sorted, and with our local cursor added
4054  */
4055 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4056                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
4057 {
4058         static const char *attrs[] = { "replUpToDateVector", NULL };
4059         struct ldb_result *r;
4060         const struct ldb_val *ouv_value;
4061         unsigned int i;
4062         int ret;
4063         uint64_t highest_usn = 0;
4064         const struct GUID *our_invocation_id;
4065         static const struct timeval tv1970;
4066         NTTIME nt1970 = timeval_to_nttime(&tv1970);
4067
4068         ret = dsdb_search_dn(samdb, mem_ctx, &r, dn, attrs, DSDB_SEARCH_SHOW_RECYCLED|DSDB_SEARCH_SHOW_DELETED);
4069         if (ret != LDB_SUCCESS) {
4070                 return ret;
4071         }
4072
4073         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
4074         if (ouv_value) {
4075                 enum ndr_err_code ndr_err;
4076                 struct replUpToDateVectorBlob ouv;
4077
4078                 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
4079                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
4080                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4081                         talloc_free(r);
4082                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4083                 }
4084                 if (ouv.version != 2) {
4085                         /* we always store as version 2, and
4086                          * replUpToDateVector is not replicated
4087                          */
4088                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
4089                 }
4090
4091                 *count = ouv.ctr.ctr2.count;
4092                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
4093         } else {
4094                 *count = 0;
4095                 *cursors = NULL;
4096         }
4097
4098         talloc_free(r);
4099
4100         our_invocation_id = samdb_ntds_invocation_id(samdb);
4101         if (!our_invocation_id) {
4102                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
4103                 talloc_free(*cursors);
4104                 return ldb_operr(samdb);
4105         }
4106
4107         ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
4108         if (ret != LDB_SUCCESS) {
4109                 /* nothing to add - this can happen after a vampire */
4110                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4111                 return LDB_SUCCESS;
4112         }
4113
4114         for (i=0; i<*count; i++) {
4115                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
4116                         (*cursors)[i].highest_usn = highest_usn;
4117                         (*cursors)[i].last_sync_success = nt1970;
4118                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4119                         return LDB_SUCCESS;
4120                 }
4121         }
4122
4123         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
4124         if (! *cursors) {
4125                 return ldb_oom(samdb);
4126         }
4127
4128         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
4129         (*cursors)[*count].highest_usn = highest_usn;
4130         (*cursors)[*count].last_sync_success = nt1970;
4131         (*count)++;
4132
4133         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
4134
4135         return LDB_SUCCESS;
4136 }
4137
4138 /*
4139   load the UDV for a partition in version 1 format
4140   The list is returned sorted, and with our local cursor added
4141  */
4142 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
4143                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
4144 {
4145         struct drsuapi_DsReplicaCursor2 *v2;
4146         uint32_t i;
4147         int ret;
4148
4149         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
4150         if (ret != LDB_SUCCESS) {
4151                 return ret;
4152         }
4153
4154         if (*count == 0) {
4155                 talloc_free(v2);
4156                 *cursors = NULL;
4157                 return LDB_SUCCESS;
4158         }
4159
4160         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
4161         if (*cursors == NULL) {
4162                 talloc_free(v2);
4163                 return ldb_oom(samdb);
4164         }
4165
4166         for (i=0; i<*count; i++) {
4167                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
4168                 (*cursors)[i].highest_usn = v2[i].highest_usn;
4169         }
4170         talloc_free(v2);
4171         return LDB_SUCCESS;
4172 }
4173
4174 /*
4175   add a set of controls to a ldb_request structure based on a set of
4176   flags. See util.h for a list of available flags
4177  */
4178 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
4179 {
4180         int ret;
4181         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
4182                 struct ldb_search_options_control *options;
4183                 /* Using the phantom root control allows us to search all partitions */
4184                 options = talloc(req, struct ldb_search_options_control);
4185                 if (options == NULL) {
4186                         return LDB_ERR_OPERATIONS_ERROR;
4187                 }
4188                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
4189
4190                 ret = ldb_request_add_control(req,
4191                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
4192                                               true, options);
4193                 if (ret != LDB_SUCCESS) {
4194                         return ret;
4195                 }
4196         }
4197
4198         if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
4199                 ret = ldb_request_add_control(req,
4200                                               DSDB_CONTROL_NO_GLOBAL_CATALOG,
4201                                               false, NULL);
4202                 if (ret != LDB_SUCCESS) {
4203                         return ret;
4204                 }
4205         }
4206
4207         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
4208                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
4209                 if (ret != LDB_SUCCESS) {
4210                         return ret;
4211                 }
4212         }
4213
4214         if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
4215                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
4216                 if (ret != LDB_SUCCESS) {
4217                         return ret;
4218                 }
4219         }
4220
4221         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
4222                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
4223                 if (ret != LDB_SUCCESS) {
4224                         return ret;
4225                 }
4226         }
4227
4228         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
4229                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
4230                 if (!extended_ctrl) {
4231                         return LDB_ERR_OPERATIONS_ERROR;
4232                 }
4233                 extended_ctrl->type = 1;
4234
4235                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
4236                 if (ret != LDB_SUCCESS) {
4237                         return ret;
4238                 }
4239         }
4240
4241         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
4242                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
4243                 if (ret != LDB_SUCCESS) {
4244                         return ret;
4245                 }
4246         }
4247
4248         if (dsdb_flags & DSDB_MODIFY_RELAX) {
4249                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
4250                 if (ret != LDB_SUCCESS) {
4251                         return ret;
4252                 }
4253         }
4254
4255         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
4256                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
4257                 if (ret != LDB_SUCCESS) {
4258                         return ret;
4259                 }
4260         }
4261
4262         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
4263                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
4264                 if (ret != LDB_SUCCESS) {
4265                         return ret;
4266                 }
4267         }
4268
4269         if (dsdb_flags & DSDB_TREE_DELETE) {
4270                 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
4271                 if (ret != LDB_SUCCESS) {
4272                         return ret;
4273                 }
4274         }
4275
4276         if (dsdb_flags & DSDB_PROVISION) {
4277                 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
4278                 if (ret != LDB_SUCCESS) {
4279                         return ret;
4280                 }
4281         }
4282
4283         /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
4284         if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
4285                 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
4286                 if (ret != LDB_SUCCESS) {
4287                         return ret;
4288                 }
4289         }
4290
4291         if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
4292                 /* 
4293                  * This must not be critical, as it will only be
4294                  * handled (and need to be handled) if the other
4295                  * attributes in the request bring password_hash into
4296                  * action
4297                  */
4298                 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
4299                 if (ret != LDB_SUCCESS) {
4300                         return ret;
4301                 }
4302         }
4303
4304         if (dsdb_flags & DSDB_REPLMD_VANISH_LINKS) {
4305                 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLMD_VANISH_LINKS, true, NULL);
4306                 if (ret != LDB_SUCCESS) {
4307                         return ret;
4308                 }
4309         }
4310
4311         if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
4312                 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
4313                 if (ret != LDB_SUCCESS) {
4314                         return ret;
4315                 }
4316         }
4317
4318         if (dsdb_flags & DSDB_FLAG_REPLICATED_UPDATE) {
4319                 ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
4320                 if (ret != LDB_SUCCESS) {
4321                         return ret;
4322                 }
4323         }
4324
4325         return LDB_SUCCESS;
4326 }
4327
4328 /*
4329   an add with a set of controls
4330 */
4331 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
4332              uint32_t dsdb_flags)
4333 {
4334         struct ldb_request *req;
4335         int ret;
4336
4337         ret = ldb_build_add_req(&req, ldb, ldb,
4338                                 message,
4339                                 NULL,
4340                                 NULL,
4341                                 ldb_op_default_callback,
4342                                 NULL);
4343
4344         if (ret != LDB_SUCCESS) return ret;
4345
4346         ret = dsdb_request_add_controls(req, dsdb_flags);
4347         if (ret != LDB_SUCCESS) {
4348                 talloc_free(req);
4349                 return ret;
4350         }
4351
4352         ret = dsdb_autotransaction_request(ldb, req);
4353
4354         talloc_free(req);
4355         return ret;
4356 }
4357
4358 /*
4359   a modify with a set of controls
4360 */
4361 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
4362                 uint32_t dsdb_flags)
4363 {
4364         struct ldb_request *req;
4365         int ret;
4366
4367         ret = ldb_build_mod_req(&req, ldb, ldb,
4368                                 message,
4369                                 NULL,
4370                                 NULL,
4371                                 ldb_op_default_callback,
4372                                 NULL);
4373
4374         if (ret != LDB_SUCCESS) return ret;
4375
4376         ret = dsdb_request_add_controls(req, dsdb_flags);
4377         if (ret != LDB_SUCCESS) {
4378                 talloc_free(req);
4379                 return ret;
4380         }
4381
4382         ret = dsdb_autotransaction_request(ldb, req);
4383
4384         talloc_free(req);
4385         return ret;
4386 }
4387
4388 /*
4389   a delete with a set of flags
4390 */
4391 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
4392                 uint32_t dsdb_flags)
4393 {
4394         struct ldb_request *req;
4395         int ret;
4396
4397         ret = ldb_build_del_req(&req, ldb, ldb,
4398                                 dn,
4399                                 NULL,
4400                                 NULL,
4401                                 ldb_op_default_callback,
4402                                 NULL);
4403
4404         if (ret != LDB_SUCCESS) return ret;
4405
4406         ret = dsdb_request_add_controls(req, dsdb_flags);
4407         if (ret != LDB_SUCCESS) {
4408                 talloc_free(req);
4409                 return ret;
4410         }
4411
4412         ret = dsdb_autotransaction_request(ldb, req);
4413
4414         talloc_free(req);
4415         return ret;
4416 }
4417
4418 /*
4419   like dsdb_modify() but set all the element flags to
4420   LDB_FLAG_MOD_REPLACE
4421  */
4422 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
4423 {
4424         unsigned int i;
4425
4426         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
4427         for (i=0;i<msg->num_elements;i++) {
4428                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
4429         }
4430
4431         return dsdb_modify(ldb, msg, dsdb_flags);
4432 }
4433
4434
4435 /*
4436   search for attrs on one DN, allowing for dsdb_flags controls
4437  */
4438 int dsdb_search_dn(struct ldb_context *ldb,
4439                    TALLOC_CTX *mem_ctx,
4440                    struct ldb_result **_result,
4441                    struct ldb_dn *basedn,
4442                    const char * const *attrs,
4443                    uint32_t dsdb_flags)
4444 {
4445         int ret;
4446         struct ldb_request *req;
4447         struct ldb_result *res;
4448
4449         res = talloc_zero(mem_ctx, struct ldb_result);
4450         if (!res) {
4451                 return ldb_oom(ldb);
4452         }
4453
4454         ret = ldb_build_search_req(&req, ldb, res,
4455                                    basedn,
4456                                    LDB_SCOPE_BASE,
4457                                    NULL,
4458                                    attrs,
4459                                    NULL,
4460                                    res,
4461                                    ldb_search_default_callback,
4462                                    NULL);
4463         if (ret != LDB_SUCCESS) {
4464                 talloc_free(res);
4465                 return ret;
4466         }
4467
4468         ret = dsdb_request_add_controls(req, dsdb_flags);
4469         if (ret != LDB_SUCCESS) {
4470                 talloc_free(res);
4471                 return ret;
4472         }
4473
4474         ret = ldb_request(ldb, req);
4475         if (ret == LDB_SUCCESS) {
4476                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4477         }
4478
4479         talloc_free(req);
4480         if (ret != LDB_SUCCESS) {
4481                 talloc_free(res);
4482                 return ret;
4483         }
4484
4485         *_result = res;
4486         return LDB_SUCCESS;
4487 }
4488
4489 /*
4490   search for attrs on one DN, by the GUID of the DN, allowing for
4491   dsdb_flags controls
4492  */
4493 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
4494                            TALLOC_CTX *mem_ctx,
4495                            struct ldb_result **_result,
4496                            const struct GUID *guid,
4497                            const char * const *attrs,
4498                            uint32_t dsdb_flags)
4499 {
4500         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4501         struct ldb_dn *dn;
4502         int ret;
4503
4504         dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
4505         if (dn == NULL) {
4506                 talloc_free(tmp_ctx);
4507                 return ldb_oom(ldb);
4508         }
4509
4510         ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
4511         talloc_free(tmp_ctx);
4512         return ret;
4513 }
4514
4515 /*
4516   general search with dsdb_flags for controls
4517  */
4518 int dsdb_search(struct ldb_context *ldb,
4519                 TALLOC_CTX *mem_ctx,
4520                 struct ldb_result **_result,
4521                 struct ldb_dn *basedn,
4522                 enum ldb_scope scope,
4523                 const char * const *attrs,
4524                 uint32_t dsdb_flags,
4525                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4526 {
4527         int ret;
4528         struct ldb_request *req;
4529         struct ldb_result *res;
4530         va_list ap;
4531         char *expression = NULL;
4532         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4533
4534         /* cross-partitions searches with a basedn break multi-domain support */
4535         SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
4536
4537         res = talloc_zero(tmp_ctx, struct ldb_result);
4538         if (!res) {
4539                 talloc_free(tmp_ctx);
4540                 return ldb_oom(ldb);
4541         }
4542
4543         if (exp_fmt) {
4544                 va_start(ap, exp_fmt);
4545                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4546                 va_end(ap);
4547
4548                 if (!expression) {
4549                         talloc_free(tmp_ctx);
4550                         return ldb_oom(ldb);
4551                 }
4552         }
4553
4554         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
4555                                    basedn,
4556                                    scope,
4557                                    expression,
4558                                    attrs,
4559                                    NULL,
4560                                    res,
4561                                    ldb_search_default_callback,
4562                                    NULL);
4563         if (ret != LDB_SUCCESS) {
4564                 talloc_free(tmp_ctx);
4565                 return ret;
4566         }
4567
4568         ret = dsdb_request_add_controls(req, dsdb_flags);
4569         if (ret != LDB_SUCCESS) {
4570                 talloc_free(tmp_ctx);
4571                 ldb_reset_err_string(ldb);
4572                 return ret;
4573         }
4574
4575         ret = ldb_request(ldb, req);
4576         if (ret == LDB_SUCCESS) {
4577                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4578         }
4579
4580         if (ret != LDB_SUCCESS) {
4581                 talloc_free(tmp_ctx);
4582                 return ret;
4583         }
4584
4585         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
4586                 if (res->count == 0) {
4587                         talloc_free(tmp_ctx);
4588                         ldb_reset_err_string(ldb);
4589                         return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, __func__);
4590                 }
4591                 if (res->count != 1) {
4592                         talloc_free(tmp_ctx);
4593                         ldb_reset_err_string(ldb);
4594                         return LDB_ERR_CONSTRAINT_VIOLATION;
4595                 }
4596         }
4597
4598         *_result = talloc_steal(mem_ctx, res);
4599         talloc_free(tmp_ctx);
4600
4601         return LDB_SUCCESS;
4602 }
4603
4604
4605 /*
4606   general search with dsdb_flags for controls
4607   returns exactly 1 record or an error
4608  */
4609 int dsdb_search_one(struct ldb_context *ldb,
4610                     TALLOC_CTX *mem_ctx,
4611                     struct ldb_message **msg,
4612                     struct ldb_dn *basedn,
4613                     enum ldb_scope scope,
4614                     const char * const *attrs,
4615                     uint32_t dsdb_flags,
4616                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4617 {
4618         int ret;
4619         struct ldb_result *res;
4620         va_list ap;
4621         char *expression = NULL;
4622         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4623
4624         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4625
4626         res = talloc_zero(tmp_ctx, struct ldb_result);
4627         if (!res) {
4628                 talloc_free(tmp_ctx);
4629                 return ldb_oom(ldb);
4630         }
4631
4632         if (exp_fmt) {
4633                 va_start(ap, exp_fmt);
4634                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4635                 va_end(ap);
4636
4637                 if (!expression) {
4638                         talloc_free(tmp_ctx);
4639                         return ldb_oom(ldb);
4640                 }
4641                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4642                                   dsdb_flags, "%s", expression);
4643         } else {
4644                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4645                                   dsdb_flags, NULL);
4646         }
4647
4648         if (ret != LDB_SUCCESS) {
4649                 talloc_free(tmp_ctx);
4650                 return ret;
4651         }
4652
4653         *msg = talloc_steal(mem_ctx, res->msgs[0]);
4654         talloc_free(tmp_ctx);
4655
4656         return LDB_SUCCESS;
4657 }
4658
4659 /* returns back the forest DNS name */
4660 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4661 {
4662         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4663                                                           ldb_get_root_basedn(ldb));
4664         char *p;
4665
4666         if (forest_name == NULL) {
4667                 return NULL;
4668         }
4669
4670         p = strchr(forest_name, '/');
4671         if (p) {
4672                 *p = '\0';
4673         }
4674
4675         return forest_name;
4676 }
4677
4678 /* returns back the default domain DNS name */
4679 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4680 {
4681         const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4682                                                           ldb_get_default_basedn(ldb));
4683         char *p;
4684
4685         if (domain_name == NULL) {
4686                 return NULL;
4687         }
4688
4689         p = strchr(domain_name, '/');
4690         if (p) {
4691                 *p = '\0';
4692         }
4693
4694         return domain_name;
4695 }
4696
4697 /*
4698    validate that an DSA GUID belongs to the specified user sid.
4699    The user SID must be a domain controller account (either RODC or
4700    RWDC)
4701  */
4702 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4703                            const struct GUID *dsa_guid,
4704                            const struct dom_sid *sid)
4705 {
4706         /* strategy:
4707             - find DN of record with the DSA GUID in the
4708               configuration partition (objectGUID)
4709             - remove "NTDS Settings" component from DN
4710             - do a base search on that DN for serverReference with
4711               extended-dn enabled
4712             - extract objectSid from resulting serverReference
4713               attribute
4714             - check this sid matches the sid argument
4715         */
4716         struct ldb_dn *config_dn;
4717         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4718         struct ldb_message *msg;
4719         const char *attrs1[] = { NULL };
4720         const char *attrs2[] = { "serverReference", NULL };
4721         int ret;
4722         struct ldb_dn *dn, *account_dn;
4723         struct dom_sid sid2;
4724         NTSTATUS status;
4725
4726         config_dn = ldb_get_config_basedn(ldb);
4727
4728         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4729                               attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4730         if (ret != LDB_SUCCESS) {
4731                 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4732                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4733                 talloc_free(tmp_ctx);
4734                 return ldb_operr(ldb);
4735         }
4736         dn = msg->dn;
4737
4738         if (!ldb_dn_remove_child_components(dn, 1)) {
4739                 talloc_free(tmp_ctx);
4740                 return ldb_operr(ldb);
4741         }
4742
4743         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4744                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4745                               "(objectClass=server)");
4746         if (ret != LDB_SUCCESS) {
4747                 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4748                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4749                 talloc_free(tmp_ctx);
4750                 return ldb_operr(ldb);
4751         }
4752
4753         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4754         if (account_dn == NULL) {
4755                 DEBUG(1,(__location__ ": Failed to find account dn "
4756                          "(serverReference) for %s, parent of DSA with "
4757                          "objectGUID %s, sid %s\n",
4758                          ldb_dn_get_linearized(msg->dn),
4759                          GUID_string(tmp_ctx, dsa_guid),
4760                          dom_sid_string(tmp_ctx, sid)));
4761                 talloc_free(tmp_ctx);
4762                 return ldb_operr(ldb);
4763         }
4764
4765         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4766         if (!NT_STATUS_IS_OK(status)) {
4767                 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4768                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4769                 talloc_free(tmp_ctx);
4770                 return ldb_operr(ldb);
4771         }
4772
4773         if (!dom_sid_equal(sid, &sid2)) {
4774                 /* someone is trying to spoof another account */
4775                 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4776                          GUID_string(tmp_ctx, dsa_guid),
4777                          dom_sid_string(tmp_ctx, sid),
4778                          dom_sid_string(tmp_ctx, &sid2)));
4779                 talloc_free(tmp_ctx);
4780                 return ldb_operr(ldb);
4781         }
4782
4783         talloc_free(tmp_ctx);
4784         return LDB_SUCCESS;
4785 }
4786
4787 static const char * const secret_attributes[] = {
4788         DSDB_SECRET_ATTRIBUTES,
4789         NULL
4790 };
4791
4792 /*
4793   check if the attribute belongs to the RODC filtered attribute set
4794   Note that attributes that are in the filtered attribute set are the
4795   ones that _are_ always sent to a RODC
4796 */
4797 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4798 {
4799         /* they never get secret attributes */
4800         if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4801                 return false;
4802         }
4803
4804         /* they do get non-secret critical attributes */
4805         if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4806                 return true;
4807         }
4808
4809         /* they do get non-secret attributes marked as being in the FAS  */
4810         if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4811                 return true;
4812         }
4813
4814         /* other attributes are denied */
4815         return false;
4816 }
4817
4818 /* return fsmo role dn and role owner dn for a particular role*/
4819 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4820                                struct ldb_context *ldb,
4821                                uint32_t role,
4822                                struct ldb_dn **fsmo_role_dn,
4823                                struct ldb_dn **role_owner_dn)
4824 {
4825         int ret;
4826         switch (role) {
4827         case DREPL_NAMING_MASTER:
4828                 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4829                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4830                 if (ret != LDB_SUCCESS) {
4831                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4832                                  ldb_errstring(ldb)));
4833                         talloc_free(tmp_ctx);
4834                         return WERR_DS_DRA_INTERNAL_ERROR;
4835                 }
4836                 break;
4837         case DREPL_INFRASTRUCTURE_MASTER:
4838                 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4839                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4840                 if (ret != LDB_SUCCESS) {
4841                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4842                                  ldb_errstring(ldb)));
4843                         talloc_free(tmp_ctx);
4844                         return WERR_DS_DRA_INTERNAL_ERROR;
4845                 }
4846                 break;
4847         case DREPL_RID_MASTER:
4848                 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
4849                 if (ret != LDB_SUCCESS) {
4850                         DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
4851                         talloc_free(tmp_ctx);
4852                         return WERR_DS_DRA_INTERNAL_ERROR;
4853                 }
4854
4855                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4856                 if (ret != LDB_SUCCESS) {
4857                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
4858                                  ldb_errstring(ldb)));
4859                         talloc_free(tmp_ctx);
4860                         return WERR_DS_DRA_INTERNAL_ERROR;
4861                 }
4862                 break;
4863         case DREPL_SCHEMA_MASTER:
4864                 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
4865                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4866                 if (ret != LDB_SUCCESS) {
4867                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4868                                  ldb_errstring(ldb)));
4869                         talloc_free(tmp_ctx);
4870                         return WERR_DS_DRA_INTERNAL_ERROR;
4871                 }
4872                 break;
4873         case DREPL_PDC_MASTER:
4874                 *fsmo_role_dn = ldb_get_default_basedn(ldb);
4875                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4876                 if (ret != LDB_SUCCESS) {
4877                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
4878                                  ldb_errstring(ldb)));
4879                         talloc_free(tmp_ctx);
4880                         return WERR_DS_DRA_INTERNAL_ERROR;
4881                 }
4882                 break;
4883         default:
4884                 return WERR_DS_DRA_INTERNAL_ERROR;
4885         }
4886         return WERR_OK;
4887 }
4888
4889 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
4890                                     TALLOC_CTX *mem_ctx,
4891                                     struct ldb_dn *server_dn)
4892 {
4893         int ldb_ret;
4894         struct ldb_result *res = NULL;
4895         const char * const attrs[] = { "dNSHostName", NULL};
4896
4897         ldb_ret = ldb_search(ldb, mem_ctx, &res,
4898                              server_dn,
4899                              LDB_SCOPE_BASE,
4900                              attrs, NULL);
4901         if (ldb_ret != LDB_SUCCESS) {
4902                 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
4903                           ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
4904                 return NULL;
4905         }
4906
4907         return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
4908 }
4909
4910 /*
4911   returns true if an attribute is in the filter,
4912   false otherwise, provided that attribute value is provided with the expression
4913 */
4914 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
4915                              const char *attr)
4916 {
4917        unsigned int i;
4918        switch (tree->operation) {
4919        case LDB_OP_AND:
4920        case LDB_OP_OR:
4921                for (i=0;i<tree->u.list.num_elements;i++) {
4922                        if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
4923                                                        attr))
4924                                return true;
4925                }
4926                return false;
4927        case LDB_OP_NOT:
4928                return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
4929        case LDB_OP_EQUALITY:
4930        case LDB_OP_GREATER:
4931        case LDB_OP_LESS:
4932        case LDB_OP_APPROX:
4933                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
4934                        return true;
4935                }
4936                return false;
4937        case LDB_OP_SUBSTRING:
4938                if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
4939                        return true;
4940                }
4941                return false;
4942        case LDB_OP_PRESENT:
4943                /* (attrname=*) is not filtered out */
4944                return false;
4945        case LDB_OP_EXTENDED:
4946                if (tree->u.extended.attr &&
4947                    ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
4948                        return true;
4949                }
4950                return false;
4951        }
4952        return false;
4953 }
4954
4955 bool is_attr_in_list(const char * const * attrs, const char *attr)
4956 {
4957         unsigned int i;
4958
4959         for (i = 0; attrs[i]; i++) {
4960                 if (ldb_attr_cmp(attrs[i], attr) == 0)
4961                         return true;
4962         }
4963
4964         return false;
4965 }
4966
4967 int dsdb_werror_at(struct ldb_context *ldb, int ldb_ecode, WERROR werr,
4968                    const char *location, const char *func,
4969                    const char *reason)
4970 {
4971         if (reason == NULL) {
4972                 reason = win_errstr(werr);
4973         }
4974         ldb_asprintf_errstring(ldb, "%08X: %s at %s:%s",
4975                                W_ERROR_V(werr), reason, location, func);
4976         return ldb_ecode;
4977 }
4978
4979 /*
4980   map an ldb error code to an approximate NTSTATUS code
4981  */
4982 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
4983 {
4984         switch (err) {
4985         case LDB_SUCCESS:
4986                 return NT_STATUS_OK;
4987
4988         case LDB_ERR_PROTOCOL_ERROR:
4989                 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
4990
4991         case LDB_ERR_TIME_LIMIT_EXCEEDED:
4992                 return NT_STATUS_IO_TIMEOUT;
4993
4994         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
4995                 return NT_STATUS_BUFFER_TOO_SMALL;
4996
4997         case LDB_ERR_COMPARE_FALSE:
4998         case LDB_ERR_COMPARE_TRUE:
4999                 return NT_STATUS_REVISION_MISMATCH;
5000
5001         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
5002                 return NT_STATUS_NOT_SUPPORTED;
5003
5004         case LDB_ERR_STRONG_AUTH_REQUIRED:
5005         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
5006         case LDB_ERR_SASL_BIND_IN_PROGRESS:
5007         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
5008         case LDB_ERR_INVALID_CREDENTIALS:
5009         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
5010         case LDB_ERR_UNWILLING_TO_PERFORM:
5011                 return NT_STATUS_ACCESS_DENIED;
5012
5013         case LDB_ERR_NO_SUCH_OBJECT:
5014                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
5015
5016         case LDB_ERR_REFERRAL:
5017         case LDB_ERR_NO_SUCH_ATTRIBUTE:
5018                 return NT_STATUS_NOT_FOUND;
5019
5020         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
5021                 return NT_STATUS_NOT_SUPPORTED;
5022
5023         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
5024                 return NT_STATUS_BUFFER_TOO_SMALL;
5025
5026         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
5027         case LDB_ERR_INAPPROPRIATE_MATCHING:
5028         case LDB_ERR_CONSTRAINT_VIOLATION:
5029         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
5030         case LDB_ERR_INVALID_DN_SYNTAX:
5031         case LDB_ERR_NAMING_VIOLATION:
5032         case LDB_ERR_OBJECT_CLASS_VIOLATION:
5033         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
5034         case LDB_ERR_NOT_ALLOWED_ON_RDN:
5035                 return NT_STATUS_INVALID_PARAMETER;
5036
5037         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
5038         case LDB_ERR_ENTRY_ALREADY_EXISTS:
5039                 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
5040
5041         case LDB_ERR_BUSY:
5042                 return NT_STATUS_NETWORK_BUSY;
5043
5044         case LDB_ERR_ALIAS_PROBLEM:
5045         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
5046         case LDB_ERR_UNAVAILABLE:
5047         case LDB_ERR_LOOP_DETECT:
5048         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
5049         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
5050         case LDB_ERR_OTHER:
5051         case LDB_ERR_OPERATIONS_ERROR:
5052                 break;
5053         }
5054         return NT_STATUS_UNSUCCESSFUL;
5055 }
5056
5057
5058 /*
5059   create a new naming context that will hold a partial replica
5060  */
5061 int dsdb_create_partial_replica_NC(struct ldb_context *ldb,  struct ldb_dn *dn)
5062 {
5063         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
5064         struct ldb_message *msg;
5065         int ret;
5066
5067         msg = ldb_msg_new(tmp_ctx);
5068         if (msg == NULL) {
5069                 talloc_free(tmp_ctx);
5070                 return ldb_oom(ldb);
5071         }
5072
5073         msg->dn = dn;
5074         ret = ldb_msg_add_string(msg, "objectClass", "top");
5075         if (ret != LDB_SUCCESS) {
5076                 talloc_free(tmp_ctx);
5077                 return ldb_oom(ldb);
5078         }
5079
5080         /* [MS-DRSR] implies that we should only add the 'top'
5081          * objectclass, but that would cause lots of problems with our
5082          * objectclass code as top is not structural, so we add
5083          * 'domainDNS' as well to keep things sane. We're expecting
5084          * this new NC to be of objectclass domainDNS after
5085          * replication anyway
5086          */
5087         ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
5088         if (ret != LDB_SUCCESS) {
5089                 talloc_free(tmp_ctx);
5090                 return ldb_oom(ldb);
5091         }
5092
5093         ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
5094                               INSTANCE_TYPE_IS_NC_HEAD|
5095                               INSTANCE_TYPE_NC_ABOVE|
5096                               INSTANCE_TYPE_UNINSTANT);
5097         if (ret != LDB_SUCCESS) {
5098                 talloc_free(tmp_ctx);
5099                 return ldb_oom(ldb);
5100         }
5101
5102         ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
5103         if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
5104                 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
5105                          ldb_dn_get_linearized(dn),
5106                          ldb_errstring(ldb), ldb_strerror(ret)));
5107                 talloc_free(tmp_ctx);
5108                 return ret;
5109         }
5110
5111         DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
5112
5113         talloc_free(tmp_ctx);
5114         return LDB_SUCCESS;
5115 }
5116
5117 /**
5118   build a GUID from a string
5119 */
5120 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
5121 {
5122         NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
5123         uint32_t time_low;
5124         uint32_t time_mid, time_hi_and_version;
5125         uint32_t clock_seq[2];
5126         uint32_t node[6];
5127         int i;
5128
5129         if (s == NULL) {
5130                 return NT_STATUS_INVALID_PARAMETER;
5131         }
5132
5133         if (11 == sscanf(s, "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5134                          &time_low, &time_mid, &time_hi_and_version, 
5135                          &clock_seq[0], &clock_seq[1],
5136                          &node[0], &node[1], &node[2], &node[3], &node[4], &node[5])) {
5137                 status = NT_STATUS_OK;
5138         }
5139
5140         if (!NT_STATUS_IS_OK(status)) {
5141                 return status;
5142         }
5143
5144         guid->time_low = time_low;
5145         guid->time_mid = time_mid;
5146         guid->time_hi_and_version = time_hi_and_version;
5147         guid->clock_seq[0] = clock_seq[0];
5148         guid->clock_seq[1] = clock_seq[1];
5149         for (i=0;i<6;i++) {
5150                 guid->node[i] = node[i];
5151         }
5152
5153         return NT_STATUS_OK;
5154 }
5155
5156 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
5157 {
5158         return talloc_asprintf(mem_ctx, 
5159                                "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
5160                                guid->time_low, guid->time_mid,
5161                                guid->time_hi_and_version,
5162                                guid->clock_seq[0],
5163                                guid->clock_seq[1],
5164                                guid->node[0], guid->node[1],
5165                                guid->node[2], guid->node[3],
5166                                guid->node[4], guid->node[5]);
5167 }
5168
5169 /*
5170  * Return the effective badPwdCount
5171  *
5172  * This requires that the user_msg have (if present):
5173  *  - badPasswordTime
5174  *  - badPwdCount
5175  *
5176  * This also requires that the domain_msg have (if present):
5177  *  - lockOutObservationWindow
5178  */
5179 static int dsdb_effective_badPwdCount(const struct ldb_message *user_msg,
5180                                       int64_t lockOutObservationWindow,
5181                                       NTTIME now)
5182 {
5183         int64_t badPasswordTime;
5184         badPasswordTime = ldb_msg_find_attr_as_int64(user_msg, "badPasswordTime", 0);
5185
5186         if (badPasswordTime - lockOutObservationWindow >= now) {
5187                 return ldb_msg_find_attr_as_int(user_msg, "badPwdCount", 0);
5188         } else {
5189                 return 0;
5190         }
5191 }
5192
5193 /*
5194  * Return the effective badPwdCount
5195  *
5196  * This requires that the user_msg have (if present):
5197  *  - badPasswordTime
5198  *  - badPwdCount
5199  *
5200  */
5201 int samdb_result_effective_badPwdCount(struct ldb_context *sam_ldb,
5202                                        TALLOC_CTX *mem_ctx,
5203                                        struct ldb_dn *domain_dn,
5204                                        const struct ldb_message *user_msg)
5205 {
5206         struct timeval tv_now = timeval_current();
5207         NTTIME now = timeval_to_nttime(&tv_now);
5208         int64_t lockOutObservationWindow = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
5209                                                               "lockOutObservationWindow", NULL);
5210         return dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5211 }
5212
5213 /*
5214  * Prepare an update to the badPwdCount and associated attributes.
5215  *
5216  * This requires that the user_msg have (if present):
5217  *  - objectSid
5218  *  - badPasswordTime
5219  *  - badPwdCount
5220  *
5221  * This also requires that the domain_msg have (if present):
5222  *  - pwdProperties
5223  *  - lockoutThreshold
5224  *  - lockOutObservationWindow
5225  */
5226 NTSTATUS dsdb_update_bad_pwd_count(TALLOC_CTX *mem_ctx,
5227                                    struct ldb_context *sam_ctx,
5228                                    struct ldb_message *user_msg,
5229                                    struct ldb_message *domain_msg,
5230                                    struct ldb_message **_mod_msg)
5231 {
5232         int i, ret, badPwdCount;
5233         int64_t lockoutThreshold, lockOutObservationWindow;
5234         struct dom_sid *sid;
5235         struct timeval tv_now = timeval_current();
5236         NTTIME now = timeval_to_nttime(&tv_now);
5237         NTSTATUS status;
5238         uint32_t pwdProperties, rid = 0;
5239         struct ldb_message *mod_msg;
5240
5241         sid = samdb_result_dom_sid(mem_ctx, user_msg, "objectSid");
5242
5243         pwdProperties = ldb_msg_find_attr_as_uint(domain_msg,
5244                                                   "pwdProperties", -1);
5245         if (sid && !(pwdProperties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
5246                 status = dom_sid_split_rid(NULL, sid, NULL, &rid);
5247                 if (!NT_STATUS_IS_OK(status)) {
5248                         /*
5249                          * This can't happen anyway, but always try
5250                          * and update the badPwdCount on failure
5251                          */
5252                         rid = 0;
5253                 }
5254         }
5255         TALLOC_FREE(sid);
5256
5257         /*
5258          * Work out if we are doing password lockout on the domain.
5259          * Also, the built in administrator account is exempt:
5260          * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375371%28v=vs.85%29.aspx
5261          */
5262         lockoutThreshold = ldb_msg_find_attr_as_int(domain_msg,
5263                                                     "lockoutThreshold", 0);
5264         if (lockoutThreshold == 0 || (rid == DOMAIN_RID_ADMINISTRATOR)) {
5265                 DEBUG(5, ("Not updating badPwdCount on %s after wrong password\n",
5266                           ldb_dn_get_linearized(user_msg->dn)));
5267                 return NT_STATUS_OK;
5268         }
5269
5270         mod_msg = ldb_msg_new(mem_ctx);
5271         if (mod_msg == NULL) {
5272                 return NT_STATUS_NO_MEMORY;
5273         }
5274         mod_msg->dn = ldb_dn_copy(mod_msg, user_msg->dn);
5275         if (mod_msg->dn == NULL) {
5276                 TALLOC_FREE(mod_msg);
5277                 return NT_STATUS_NO_MEMORY;
5278         }
5279
5280         lockOutObservationWindow = ldb_msg_find_attr_as_int64(domain_msg,
5281                                                               "lockOutObservationWindow", 0);
5282
5283         badPwdCount = dsdb_effective_badPwdCount(user_msg, lockOutObservationWindow, now);
5284
5285         badPwdCount++;
5286
5287         ret = samdb_msg_add_int(sam_ctx, mod_msg, mod_msg, "badPwdCount", badPwdCount);
5288         if (ret != LDB_SUCCESS) {
5289                 TALLOC_FREE(mod_msg);
5290                 return NT_STATUS_NO_MEMORY;
5291         }
5292         ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "badPasswordTime", now);
5293         if (ret != LDB_SUCCESS) {
5294                 TALLOC_FREE(mod_msg);
5295                 return NT_STATUS_NO_MEMORY;
5296         }
5297
5298         if (badPwdCount >= lockoutThreshold) {
5299                 ret = samdb_msg_add_int64(sam_ctx, mod_msg, mod_msg, "lockoutTime", now);
5300                 if (ret != LDB_SUCCESS) {
5301                         TALLOC_FREE(mod_msg);
5302                         return NT_STATUS_NO_MEMORY;
5303                 }
5304                 DEBUG(5, ("Locked out user %s after %d wrong passwords\n",
5305                           ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5306         } else {
5307                 DEBUG(5, ("Updated badPwdCount on %s after %d wrong passwords\n",
5308                           ldb_dn_get_linearized(user_msg->dn), badPwdCount));
5309         }
5310
5311         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
5312         for (i=0; i< mod_msg->num_elements; i++) {
5313                 mod_msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
5314         }
5315
5316         *_mod_msg = mod_msg;
5317         return NT_STATUS_OK;
5318 }
5319
5320 /**
5321  * Sets defaults for a User object
5322  * List of default attributes set:
5323  *      accountExpires, badPasswordTime, badPwdCount,
5324  *      codePage, countryCode, lastLogoff, lastLogon
5325  *      logonCount, pwdLastSet
5326  */
5327 int dsdb_user_obj_set_defaults(struct ldb_context *ldb,
5328                                struct ldb_message *usr_obj,
5329                                struct ldb_request *req)
5330 {
5331         int i, ret;
5332         const struct attribute_values {
5333                 const char *name;
5334                 const char *value;
5335                 const char *add_value;
5336                 const char *mod_value;
5337                 const char *control;
5338                 unsigned add_flags;
5339                 unsigned mod_flags;
5340         } map[] = {
5341                 {
5342                         .name = "accountExpires",
5343                         .add_value = "9223372036854775807",
5344                         .mod_value = "0",
5345                 },
5346                 {
5347                         .name = "badPasswordTime",
5348                         .value = "0"
5349                 },
5350                 {
5351                         .name = "badPwdCount",
5352                         .value = "0"
5353                 },
5354                 {
5355                         .name = "codePage",
5356                         .value = "0"
5357                 },
5358                 {
5359                         .name = "countryCode",
5360                         .value = "0"
5361                 },
5362                 {
5363                         .name = "lastLogoff",
5364                         .value = "0"
5365                 },
5366                 {
5367                         .name = "lastLogon",
5368                         .value = "0"
5369                 },
5370                 {
5371                         .name = "logonCount",
5372                         .value = "0"
5373                 },
5374                 {
5375                         .name = "logonHours",
5376                         .add_flags = DSDB_FLAG_INTERNAL_FORCE_META_DATA,
5377                 },
5378                 {
5379                         .name = "pwdLastSet",
5380                         .value = "0",
5381                         .control = DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID,
5382                 },
5383                 {
5384                         .name = "adminCount",
5385                         .mod_value = "0",
5386                 },
5387                 {
5388                         .name = "operatorCount",
5389                         .mod_value = "0",
5390                 },
5391         };
5392
5393         for (i = 0; i < ARRAY_SIZE(map); i++) {
5394                 bool added = false;
5395                 const char *value = NULL;
5396                 unsigned flags = 0;
5397
5398                 if (req != NULL && req->operation == LDB_ADD) {
5399                         value = map[i].add_value;
5400                         flags = map[i].add_flags;
5401                 } else {
5402                         value = map[i].mod_value;
5403                         flags = map[i].mod_flags;
5404                 }
5405
5406                 if (value == NULL) {
5407                         value = map[i].value;
5408                 }
5409
5410                 if (value != NULL) {
5411                         flags |= LDB_FLAG_MOD_ADD;
5412                 }
5413
5414                 if (flags == 0) {
5415                         continue;
5416                 }
5417
5418                 ret = samdb_find_or_add_attribute_ex(ldb, usr_obj,
5419                                                      map[i].name,
5420                                                      value, flags,
5421                                                      &added);
5422                 if (ret != LDB_SUCCESS) {
5423                         return ret;
5424                 }
5425
5426                 if (req != NULL && added && map[i].control != NULL) {
5427                         ret = ldb_request_add_control(req,
5428                                                       map[i].control,
5429                                                       false, NULL);
5430                         if (ret != LDB_SUCCESS) {
5431                                 return ret;
5432                         }
5433                 }
5434         }
5435
5436         return LDB_SUCCESS;
5437 }
5438
5439 /**
5440  * Sets 'sAMAccountType on user object based on userAccountControl
5441  * @param ldb Current ldb_context
5442  * @param usr_obj ldb_message representing User object
5443  * @param user_account_control Value for userAccountControl flags
5444  * @param account_type_p Optional pointer to account_type to return
5445  * @return LDB_SUCCESS or LDB_ERR* code on failure
5446  */
5447 int dsdb_user_obj_set_account_type(struct ldb_context *ldb, struct ldb_message *usr_obj,
5448                                    uint32_t user_account_control, uint32_t *account_type_p)
5449 {
5450         int ret;
5451         uint32_t account_type;
5452         struct ldb_message_element *el;
5453
5454         account_type = ds_uf2atype(user_account_control);
5455         if (account_type == 0) {
5456                 ldb_set_errstring(ldb, "dsdb: Unrecognized account type!");
5457                 return LDB_ERR_UNWILLING_TO_PERFORM;
5458         }
5459         ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5460                                  "sAMAccountType",
5461                                  account_type);
5462         if (ret != LDB_SUCCESS) {
5463                 return ret;
5464         }
5465         el = ldb_msg_find_element(usr_obj, "sAMAccountType");
5466         el->flags = LDB_FLAG_MOD_REPLACE;
5467
5468         if (account_type_p) {
5469                 *account_type_p = account_type;
5470         }
5471
5472         return LDB_SUCCESS;
5473 }
5474
5475 /**
5476  * Determine and set primaryGroupID based on userAccountControl value
5477  * @param ldb Current ldb_context
5478  * @param usr_obj ldb_message representing User object
5479  * @param user_account_control Value for userAccountControl flags
5480  * @param group_rid_p Optional pointer to group RID to return
5481  * @return LDB_SUCCESS or LDB_ERR* code on failure
5482  */
5483 int dsdb_user_obj_set_primary_group_id(struct ldb_context *ldb, struct ldb_message *usr_obj,
5484                                        uint32_t user_account_control, uint32_t *group_rid_p)
5485 {
5486         int ret;
5487         uint32_t rid;
5488         struct ldb_message_element *el;
5489
5490         rid = ds_uf2prim_group_rid(user_account_control);
5491
5492         ret = samdb_msg_add_uint(ldb, usr_obj, usr_obj,
5493                                  "primaryGroupID", rid);
5494         if (ret != LDB_SUCCESS) {
5495                 return ret;
5496         }
5497         el = ldb_msg_find_element(usr_obj, "primaryGroupID");
5498         el->flags = LDB_FLAG_MOD_REPLACE;
5499
5500         if (group_rid_p) {
5501                 *group_rid_p = rid;
5502         }
5503
5504         return LDB_SUCCESS;
5505 }