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