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