CVE-2015-8467: samdb: Match MS15-096 behaviour for userAccountControl
[samba.git] / source4 / dsdb / samdb / ldb_modules / samldb.c
1 /*
2    SAM ldb module
3
4    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2014
5    Copyright (C) Simo Sorce  2004-2008
6    Copyright (C) Matthias Dieter Wallnöfer 2009-2011
7    Copyright (C) Matthieu Patou 2012
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 /*
24  *  Name: ldb
25  *
26  *  Component: ldb samldb module
27  *
28  *  Description: various internal DSDB triggers - most for SAM specific objects
29  *
30  *  Author: Simo Sorce
31  */
32
33 #include "includes.h"
34 #include "libcli/ldap/ldap_ndr.h"
35 #include "ldb_module.h"
36 #include "auth/auth.h"
37 #include "dsdb/samdb/samdb.h"
38 #include "dsdb/samdb/ldb_modules/util.h"
39 #include "dsdb/samdb/ldb_modules/ridalloc.h"
40 #include "libcli/security/security.h"
41 #include "librpc/gen_ndr/ndr_security.h"
42 #include "ldb_wrap.h"
43 #include "param/param.h"
44 #include "libds/common/flag_mapping.h"
45
46 struct samldb_ctx;
47 enum samldb_add_type {
48         SAMLDB_TYPE_USER,
49         SAMLDB_TYPE_GROUP,
50         SAMLDB_TYPE_CLASS,
51         SAMLDB_TYPE_ATTRIBUTE
52 };
53
54 typedef int (*samldb_step_fn_t)(struct samldb_ctx *);
55
56 struct samldb_step {
57         struct samldb_step *next;
58         samldb_step_fn_t fn;
59 };
60
61 struct samldb_ctx {
62         struct ldb_module *module;
63         struct ldb_request *req;
64
65         /* used for add operations */
66         enum samldb_add_type type;
67
68         /* the resulting message */
69         struct ldb_message *msg;
70
71         /* used in "samldb_find_for_defaultObjectCategory" */
72         struct ldb_dn *dn, *res_dn;
73
74         /* all the async steps necessary to complete the operation */
75         struct samldb_step *steps;
76         struct samldb_step *curstep;
77
78         /* If someone set an ares to forward controls and response back to the caller */
79         struct ldb_reply *ares;
80 };
81
82 static struct samldb_ctx *samldb_ctx_init(struct ldb_module *module,
83                                           struct ldb_request *req)
84 {
85         struct ldb_context *ldb;
86         struct samldb_ctx *ac;
87
88         ldb = ldb_module_get_ctx(module);
89
90         ac = talloc_zero(req, struct samldb_ctx);
91         if (ac == NULL) {
92                 ldb_oom(ldb);
93                 return NULL;
94         }
95
96         ac->module = module;
97         ac->req = req;
98
99         return ac;
100 }
101
102 static int samldb_add_step(struct samldb_ctx *ac, samldb_step_fn_t fn)
103 {
104         struct samldb_step *step, *stepper;
105
106         step = talloc_zero(ac, struct samldb_step);
107         if (step == NULL) {
108                 return ldb_oom(ldb_module_get_ctx(ac->module));
109         }
110
111         step->fn = fn;
112
113         if (ac->steps == NULL) {
114                 ac->steps = step;
115                 ac->curstep = step;
116         } else {
117                 if (ac->curstep == NULL)
118                         return ldb_operr(ldb_module_get_ctx(ac->module));
119                 for (stepper = ac->curstep; stepper->next != NULL;
120                         stepper = stepper->next);
121                 stepper->next = step;
122         }
123
124         return LDB_SUCCESS;
125 }
126
127 static int samldb_first_step(struct samldb_ctx *ac)
128 {
129         if (ac->steps == NULL) {
130                 return ldb_operr(ldb_module_get_ctx(ac->module));
131         }
132
133         ac->curstep = ac->steps;
134         return ac->curstep->fn(ac);
135 }
136
137 static int samldb_next_step(struct samldb_ctx *ac)
138 {
139         if (ac->curstep->next) {
140                 ac->curstep = ac->curstep->next;
141                 return ac->curstep->fn(ac);
142         }
143
144         /* We exit the samldb module here. If someone set an "ares" to forward
145          * controls and response back to the caller, use them. */
146         if (ac->ares) {
147                 return ldb_module_done(ac->req, ac->ares->controls,
148                                        ac->ares->response, LDB_SUCCESS);
149         } else {
150                 return ldb_module_done(ac->req, NULL, NULL, LDB_SUCCESS);
151         }
152 }
153
154
155 /* sAMAccountName handling */
156
157 static int samldb_generate_sAMAccountName(struct ldb_context *ldb,
158                                           struct ldb_message *msg)
159 {
160         char *name;
161
162         /* Format: $000000-000000000000 */
163
164         name = talloc_asprintf(msg, "$%.6X-%.6X%.6X",
165                                 (unsigned int)generate_random(),
166                                 (unsigned int)generate_random(),
167                                 (unsigned int)generate_random());
168         if (name == NULL) {
169                 return ldb_oom(ldb);
170         }
171         return ldb_msg_add_steal_string(msg, "sAMAccountName", name);
172 }
173
174 static int samldb_check_sAMAccountName(struct samldb_ctx *ac)
175 {
176         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
177         const char *name;
178         int ret;
179         struct ldb_result *res;
180         const char * const noattrs[] = { NULL };
181
182         if (ldb_msg_find_element(ac->msg, "sAMAccountName") == NULL) {
183                 ret = samldb_generate_sAMAccountName(ldb, ac->msg);
184                 if (ret != LDB_SUCCESS) {
185                         return ret;
186                 }
187         }
188
189         name = ldb_msg_find_attr_as_string(ac->msg, "sAMAccountName", NULL);
190         if (name == NULL) {
191                 /* The "sAMAccountName" cannot be nothing */
192                 ldb_set_errstring(ldb,
193                                   "samldb: Empty account names aren't allowed!");
194                 return LDB_ERR_CONSTRAINT_VIOLATION;
195         }
196
197         ret = dsdb_module_search(ac->module, ac, &res,
198                                  ldb_get_default_basedn(ldb), LDB_SCOPE_SUBTREE, noattrs,
199                                  DSDB_FLAG_NEXT_MODULE,
200                                  ac->req,
201                                  "(sAMAccountName=%s)",
202                                  ldb_binary_encode_string(ac, name));
203         if (ret != LDB_SUCCESS) {
204                 return ret;
205         }
206         if (res->count != 0) {
207                 ldb_asprintf_errstring(ldb,
208                                        "samldb: Account name (sAMAccountName) '%s' already in use!",
209                                        name);
210                 talloc_free(res);
211                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
212         }
213         talloc_free(res);
214
215         return samldb_next_step(ac);
216 }
217
218
219 static bool samldb_msg_add_sid(struct ldb_message *msg,
220                                 const char *name,
221                                 const struct dom_sid *sid)
222 {
223         struct ldb_val v;
224         enum ndr_err_code ndr_err;
225
226         ndr_err = ndr_push_struct_blob(&v, msg, sid,
227                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
228         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
229                 return false;
230         }
231         return (ldb_msg_add_value(msg, name, &v, NULL) == 0);
232 }
233
234
235 /* allocate a SID using our RID Set */
236 static int samldb_allocate_sid(struct samldb_ctx *ac)
237 {
238         uint32_t rid;
239         struct dom_sid *sid;
240         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
241         int ret;
242
243         ret = ridalloc_allocate_rid(ac->module, &rid, ac->req);
244         if (ret != LDB_SUCCESS) {
245                 return ret;
246         }
247
248         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
249         if (sid == NULL) {
250                 return ldb_module_oom(ac->module);
251         }
252
253         if ( ! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
254                 return ldb_operr(ldb);
255         }
256
257         return samldb_next_step(ac);
258 }
259
260 /*
261   see if a krbtgt_number is available
262  */
263 static bool samldb_krbtgtnumber_available(struct samldb_ctx *ac,
264                                           uint32_t krbtgt_number)
265 {
266         TALLOC_CTX *tmp_ctx = talloc_new(ac);
267         struct ldb_result *res;
268         const char * const no_attrs[] = { NULL };
269         int ret;
270
271         ret = dsdb_module_search(ac->module, tmp_ctx, &res,
272                                  ldb_get_default_basedn(ldb_module_get_ctx(ac->module)),
273                                  LDB_SCOPE_SUBTREE, no_attrs,
274                                  DSDB_FLAG_NEXT_MODULE,
275                                  ac->req,
276                                  "(msDC-SecondaryKrbTgtNumber=%u)",
277                                  krbtgt_number);
278         if (ret == LDB_SUCCESS && res->count == 0) {
279                 talloc_free(tmp_ctx);
280                 return true;
281         }
282         talloc_free(tmp_ctx);
283         return false;
284 }
285
286 /* special handling for add in RODC join */
287 static int samldb_rodc_add(struct samldb_ctx *ac)
288 {
289         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
290         uint32_t krbtgt_number, i_start, i;
291         int ret;
292         char *newpass;
293         struct ldb_val newpass_utf16;
294
295         /* find a unused msDC-SecondaryKrbTgtNumber */
296         i_start = generate_random() & 0xFFFF;
297         if (i_start == 0) {
298                 i_start = 1;
299         }
300
301         for (i=i_start; i<=0xFFFF; i++) {
302                 if (samldb_krbtgtnumber_available(ac, i)) {
303                         krbtgt_number = i;
304                         goto found;
305                 }
306         }
307         for (i=1; i<i_start; i++) {
308                 if (samldb_krbtgtnumber_available(ac, i)) {
309                         krbtgt_number = i;
310                         goto found;
311                 }
312         }
313
314         ldb_asprintf_errstring(ldb,
315                                "%08X: Unable to find available msDS-SecondaryKrbTgtNumber",
316                                W_ERROR_V(WERR_NO_SYSTEM_RESOURCES));
317         return LDB_ERR_OTHER;
318
319 found:
320         ret = ldb_msg_add_empty(ac->msg, "msDS-SecondaryKrbTgtNumber",
321                                 LDB_FLAG_INTERNAL_DISABLE_VALIDATION, NULL);
322         if (ret != LDB_SUCCESS) {
323                 return ldb_operr(ldb);
324         }
325
326         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
327                                  "msDS-SecondaryKrbTgtNumber", krbtgt_number);
328         if (ret != LDB_SUCCESS) {
329                 return ldb_operr(ldb);
330         }
331
332         ret = ldb_msg_add_fmt(ac->msg, "sAMAccountName", "krbtgt_%u",
333                               krbtgt_number);
334         if (ret != LDB_SUCCESS) {
335                 return ldb_operr(ldb);
336         }
337
338         newpass = generate_random_password(ac->msg, 128, 255);
339         if (newpass == NULL) {
340                 return ldb_operr(ldb);
341         }
342
343         if (!convert_string_talloc(ac,
344                                    CH_UNIX, CH_UTF16,
345                                    newpass, strlen(newpass),
346                                    (void *)&newpass_utf16.data,
347                                    &newpass_utf16.length)) {
348                 ldb_asprintf_errstring(ldb,
349                                        "samldb_rodc_add: "
350                                        "failed to generate UTF16 password from random password");
351                 return LDB_ERR_OPERATIONS_ERROR;
352         }
353         ret = ldb_msg_add_steal_value(ac->msg, "clearTextPassword", &newpass_utf16);
354         if (ret != LDB_SUCCESS) {
355                 return ldb_operr(ldb);
356         }
357
358         return samldb_next_step(ac);
359 }
360
361 static int samldb_find_for_defaultObjectCategory(struct samldb_ctx *ac)
362 {
363         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
364         struct ldb_result *res;
365         const char * const no_attrs[] = { NULL };
366         int ret;
367
368         ac->res_dn = NULL;
369
370         ret = dsdb_module_search(ac->module, ac, &res,
371                                  ac->dn, LDB_SCOPE_BASE, no_attrs,
372                                  DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT
373                                  | DSDB_FLAG_NEXT_MODULE,
374                                  ac->req,
375                                  "(objectClass=classSchema)");
376         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
377                 /* Don't be pricky when the DN doesn't exist if we have the */
378                 /* RELAX control specified */
379                 if (ldb_request_get_control(ac->req,
380                                             LDB_CONTROL_RELAX_OID) == NULL) {
381                         ldb_set_errstring(ldb,
382                                           "samldb_find_defaultObjectCategory: "
383                                           "Invalid DN for 'defaultObjectCategory'!");
384                         return LDB_ERR_CONSTRAINT_VIOLATION;
385                 }
386         }
387         if ((ret != LDB_ERR_NO_SUCH_OBJECT) && (ret != LDB_SUCCESS)) {
388                 return ret;
389         }
390
391         if (ret == LDB_SUCCESS) {
392                 /* ensure the defaultObjectCategory has a full GUID */
393                 struct ldb_message *m;
394                 m = ldb_msg_new(ac->msg);
395                 if (m == NULL) {
396                         return ldb_oom(ldb);
397                 }
398                 m->dn = ac->msg->dn;
399                 if (ldb_msg_add_string(m, "defaultObjectCategory",
400                                        ldb_dn_get_extended_linearized(m, res->msgs[0]->dn, 1)) !=
401                     LDB_SUCCESS) {
402                         return ldb_oom(ldb);
403                 }
404                 m->elements[0].flags = LDB_FLAG_MOD_REPLACE;
405
406                 ret = dsdb_module_modify(ac->module, m,
407                                          DSDB_FLAG_NEXT_MODULE,
408                                          ac->req);
409                 if (ret != LDB_SUCCESS) {
410                         return ret;
411                 }
412         }
413
414
415         ac->res_dn = ac->dn;
416
417         return samldb_next_step(ac);
418 }
419
420 /**
421  * msDS-IntId attributeSchema attribute handling
422  * during LDB_ADD request processing
423  */
424 static int samldb_add_handle_msDS_IntId(struct samldb_ctx *ac)
425 {
426         int ret;
427         bool id_exists;
428         uint32_t msds_intid;
429         int32_t system_flags;
430         struct ldb_context *ldb;
431         struct ldb_result *ldb_res;
432         struct ldb_dn *schema_dn;
433         struct samldb_msds_intid_persistant *msds_intid_struct;
434         struct dsdb_schema *schema;
435
436         ldb = ldb_module_get_ctx(ac->module);
437         schema_dn = ldb_get_schema_basedn(ldb);
438
439         /* replicated update should always go through */
440         if (ldb_request_get_control(ac->req,
441                                     DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
442                 return LDB_SUCCESS;
443         }
444
445         /* msDS-IntId is handled by system and should never be
446          * passed by clients */
447         if (ldb_msg_find_element(ac->msg, "msDS-IntId")) {
448                 return LDB_ERR_UNWILLING_TO_PERFORM;
449         }
450
451         /* do not generate msDS-IntId if Relax control is passed */
452         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
453                 return LDB_SUCCESS;
454         }
455
456         /* check Functional Level */
457         if (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003) {
458                 return LDB_SUCCESS;
459         }
460
461         /* check systemFlags for SCHEMA_BASE_OBJECT flag */
462         system_flags = ldb_msg_find_attr_as_int(ac->msg, "systemFlags", 0);
463         if (system_flags & SYSTEM_FLAG_SCHEMA_BASE_OBJECT) {
464                 return LDB_SUCCESS;
465         }
466         schema = dsdb_get_schema(ldb, NULL);
467         if (!schema) {
468                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
469                               "samldb_schema_info_update: no dsdb_schema loaded");
470                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
471                 return ldb_operr(ldb);
472         }
473
474         msds_intid_struct = (struct samldb_msds_intid_persistant*) ldb_get_opaque(ldb, SAMLDB_MSDS_INTID_OPAQUE);
475         if (!msds_intid_struct) {
476                 msds_intid_struct = talloc(ldb, struct samldb_msds_intid_persistant);
477                 /* Generate new value for msDs-IntId
478                 * Value should be in 0x80000000..0xBFFFFFFF range */
479                 msds_intid = generate_random() % 0X3FFFFFFF;
480                 msds_intid += 0x80000000;
481                 msds_intid_struct->msds_intid = msds_intid;
482                 msds_intid_struct->usn = schema->loaded_usn;
483                 DEBUG(2, ("No samldb_msds_intid_persistant struct, allocating a new one\n"));
484         } else {
485                 msds_intid = msds_intid_struct->msds_intid;
486         }
487
488         /* probe id values until unique one is found */
489         do {
490                 uint64_t current_usn;
491                 msds_intid++;
492                 if (msds_intid > 0xBFFFFFFF) {
493                         msds_intid = 0x80000001;
494                 }
495                 /*
496                  * Alternative strategy to a costly (even indexed search) to the
497                  * database.
498                  * We search in the schema if we have already this intid (using dsdb_attribute_by_attributeID_id because
499                  * in the range 0x80000000 0xBFFFFFFFF, attributeID is a DSDB_ATTID_TYPE_INTID).
500                  * If so generate another random value.
501                  * If not check if the highest USN in the database for the schema partition is the
502                  * one that we know.
503                  * If so it means that's only this ldb context that is touching the schema in the database.
504                  * If not it means that's someone else has modified the database while we are doing our changes too
505                  * (this case should be very bery rare) in order to be sure do the search in the database.
506                  */
507                 if (dsdb_attribute_by_attributeID_id(schema, msds_intid)) {
508                         msds_intid = generate_random() % 0X3FFFFFFF;
509                         msds_intid += 0x80000000;
510                         continue;
511                 }
512
513                 ret = dsdb_module_load_partition_usn(ac->module, schema_dn,
514                                                      &current_usn, NULL, NULL);
515                 if (ret != LDB_SUCCESS) {
516                         ldb_debug_set(ldb, LDB_DEBUG_ERROR,
517                                       __location__": Searching for schema USN failed: %s\n",
518                                       ldb_errstring(ldb));
519                         return ldb_operr(ldb);
520                 }
521
522                 /* current_usn can be lesser than msds_intid_struct-> if there is
523                  * uncommited changes.
524                  */
525                 if (current_usn > msds_intid_struct->usn) {
526                         /* oups something has changed, someone/something
527                          * else is modifying or has modified the schema
528                          * we'd better check this intid is the database directly
529                          */
530
531                         DEBUG(2, ("Schema has changed, searching the database for the unicity of %d\n",
532                                         msds_intid));
533
534                         ret = dsdb_module_search(ac->module, ac,
535                                                 &ldb_res,
536                                                 schema_dn, LDB_SCOPE_ONELEVEL, NULL,
537                                                 DSDB_FLAG_NEXT_MODULE,
538                                                 ac->req,
539                                                 "(msDS-IntId=%d)", msds_intid);
540                         if (ret != LDB_SUCCESS) {
541                                 ldb_debug_set(ldb, LDB_DEBUG_ERROR,
542                                         __location__": Searching for msDS-IntId=%d failed - %s\n",
543                                         msds_intid,
544                                         ldb_errstring(ldb));
545                                 return ldb_operr(ldb);
546                         }
547                         id_exists = (ldb_res->count > 0);
548                         talloc_free(ldb_res);
549                 } else {
550                         id_exists = 0;
551                 }
552
553         } while(id_exists);
554         msds_intid_struct->msds_intid = msds_intid;
555         ldb_set_opaque(ldb, SAMLDB_MSDS_INTID_OPAQUE, msds_intid_struct);
556
557         return samdb_msg_add_int(ldb, ac->msg, ac->msg, "msDS-IntId",
558                                  msds_intid);
559 }
560
561
562 /*
563  * samldb_add_entry (async)
564  */
565
566 static int samldb_add_entry_callback(struct ldb_request *req,
567                                         struct ldb_reply *ares)
568 {
569         struct ldb_context *ldb;
570         struct samldb_ctx *ac;
571         int ret;
572
573         ac = talloc_get_type(req->context, struct samldb_ctx);
574         ldb = ldb_module_get_ctx(ac->module);
575
576         if (!ares) {
577                 return ldb_module_done(ac->req, NULL, NULL,
578                                         LDB_ERR_OPERATIONS_ERROR);
579         }
580
581         if (ares->type == LDB_REPLY_REFERRAL) {
582                 return ldb_module_send_referral(ac->req, ares->referral);
583         }
584
585         if (ares->error != LDB_SUCCESS) {
586                 return ldb_module_done(ac->req, ares->controls,
587                                         ares->response, ares->error);
588         }
589         if (ares->type != LDB_REPLY_DONE) {
590                 ldb_asprintf_errstring(ldb, "Invalid LDB reply type %d", ares->type);
591                 return ldb_module_done(ac->req, NULL, NULL,
592                                         LDB_ERR_OPERATIONS_ERROR);
593         }
594
595         /* The caller may wish to get controls back from the add */
596         ac->ares = talloc_steal(ac, ares);
597
598         ret = samldb_next_step(ac);
599         if (ret != LDB_SUCCESS) {
600                 return ldb_module_done(ac->req, NULL, NULL, ret);
601         }
602         return ret;
603 }
604
605 static int samldb_add_entry(struct samldb_ctx *ac)
606 {
607         struct ldb_context *ldb;
608         struct ldb_request *req;
609         int ret;
610
611         ldb = ldb_module_get_ctx(ac->module);
612
613         ret = ldb_build_add_req(&req, ldb, ac,
614                                 ac->msg,
615                                 ac->req->controls,
616                                 ac, samldb_add_entry_callback,
617                                 ac->req);
618         LDB_REQ_SET_LOCATION(req);
619         if (ret != LDB_SUCCESS) {
620                 return ret;
621         }
622
623         return ldb_next_request(ac->module, req);
624 }
625
626 /*
627  * return true if msg carries an attributeSchema that is intended to be RODC
628  * filtered but is also a system-critical attribute.
629  */
630 static bool check_rodc_critical_attribute(struct ldb_message *msg)
631 {
632         uint32_t schemaFlagsEx, searchFlags, rodc_filtered_flags;
633
634         schemaFlagsEx = ldb_msg_find_attr_as_uint(msg, "schemaFlagsEx", 0);
635         searchFlags = ldb_msg_find_attr_as_uint(msg, "searchFlags", 0);
636         rodc_filtered_flags = (SEARCH_FLAG_RODC_ATTRIBUTE
637                               | SEARCH_FLAG_CONFIDENTIAL);
638
639         if ((schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) &&
640                 ((searchFlags & rodc_filtered_flags) == rodc_filtered_flags)) {
641                 return true;
642         } else {
643                 return false;
644         }
645 }
646
647
648 static int samldb_fill_object(struct samldb_ctx *ac)
649 {
650         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
651         int ret;
652
653         /* Add information for the different account types */
654         switch(ac->type) {
655         case SAMLDB_TYPE_USER: {
656                 struct ldb_control *rodc_control = ldb_request_get_control(ac->req,
657                                                                            LDB_CONTROL_RODC_DCPROMO_OID);
658                 if (rodc_control != NULL) {
659                         /* see [MS-ADTS] 3.1.1.3.4.1.23 LDAP_SERVER_RODC_DCPROMO_OID */
660                         rodc_control->critical = false;
661                         ret = samldb_add_step(ac, samldb_rodc_add);
662                         if (ret != LDB_SUCCESS) return ret;
663                 }
664
665                 /* check if we have a valid sAMAccountName */
666                 ret = samldb_add_step(ac, samldb_check_sAMAccountName);
667                 if (ret != LDB_SUCCESS) return ret;
668
669                 ret = samldb_add_step(ac, samldb_add_entry);
670                 if (ret != LDB_SUCCESS) return ret;
671                 break;
672         }
673
674         case SAMLDB_TYPE_GROUP: {
675                 /* check if we have a valid sAMAccountName */
676                 ret = samldb_add_step(ac, samldb_check_sAMAccountName);
677                 if (ret != LDB_SUCCESS) return ret;
678
679                 ret = samldb_add_step(ac, samldb_add_entry);
680                 if (ret != LDB_SUCCESS) return ret;
681                 break;
682         }
683
684         case SAMLDB_TYPE_CLASS: {
685                 const struct ldb_val *rdn_value, *def_obj_cat_val;
686                 unsigned int v = ldb_msg_find_attr_as_uint(ac->msg, "objectClassCategory", -2);
687
688                 /* As discussed with Microsoft through dochelp in April 2012 this is the behavior of windows*/
689                 if (!ldb_msg_find_element(ac->msg, "subClassOf")) {
690                         ret = ldb_msg_add_string(ac->msg, "subClassOf", "top");
691                         if (ret != LDB_SUCCESS) return ret;
692                 }
693
694                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
695                                                   "rdnAttId", "cn");
696                 if (ret != LDB_SUCCESS) return ret;
697
698                 /* do not allow to mark an attributeSchema as RODC filtered if it
699                  * is system-critical */
700                 if (check_rodc_critical_attribute(ac->msg)) {
701                         ldb_asprintf_errstring(ldb, "Refusing schema add of %s - cannot combine critical class with RODC filtering",
702                                                ldb_dn_get_linearized(ac->msg->dn));
703                         return LDB_ERR_UNWILLING_TO_PERFORM;
704                 }
705
706                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
707                 if (rdn_value == NULL) {
708                         return ldb_operr(ldb);
709                 }
710                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
711                         /* the RDN has prefix "CN" */
712                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
713                                 samdb_cn_to_lDAPDisplayName(ac->msg,
714                                                             (const char *) rdn_value->data));
715                         if (ret != LDB_SUCCESS) {
716                                 ldb_oom(ldb);
717                                 return ret;
718                         }
719                 }
720
721                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
722                         struct GUID guid;
723                         /* a new GUID */
724                         guid = GUID_random();
725                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
726                         if (ret != LDB_SUCCESS) {
727                                 ldb_oom(ldb);
728                                 return ret;
729                         }
730                 }
731
732                 def_obj_cat_val = ldb_msg_find_ldb_val(ac->msg,
733                                                        "defaultObjectCategory");
734                 if (def_obj_cat_val != NULL) {
735                         /* "defaultObjectCategory" has been set by the caller.
736                          * Do some checks for consistency.
737                          * NOTE: The real constraint check (that
738                          * 'defaultObjectCategory' is the DN of the new
739                          * objectclass or any parent of it) is still incomplete.
740                          * For now we say that 'defaultObjectCategory' is valid
741                          * if it exists and it is of objectclass "classSchema".
742                          */
743                         ac->dn = ldb_dn_from_ldb_val(ac, ldb, def_obj_cat_val);
744                         if (ac->dn == NULL) {
745                                 ldb_set_errstring(ldb,
746                                                   "Invalid DN for 'defaultObjectCategory'!");
747                                 return LDB_ERR_CONSTRAINT_VIOLATION;
748                         }
749                 } else {
750                         /* "defaultObjectCategory" has not been set by the
751                          * caller. Use the entry DN for it. */
752                         ac->dn = ac->msg->dn;
753
754                         ret = ldb_msg_add_string(ac->msg, "defaultObjectCategory",
755                                                  ldb_dn_alloc_linearized(ac->msg, ac->dn));
756                         if (ret != LDB_SUCCESS) {
757                                 ldb_oom(ldb);
758                                 return ret;
759                         }
760                 }
761
762                 ret = samldb_add_step(ac, samldb_add_entry);
763                 if (ret != LDB_SUCCESS) return ret;
764
765                 /* Now perform the checks for the 'defaultObjectCategory'. The
766                  * lookup DN was already saved in "ac->dn" */
767                 ret = samldb_add_step(ac, samldb_find_for_defaultObjectCategory);
768                 if (ret != LDB_SUCCESS) return ret;
769
770                 /* -2 is not a valid objectClassCategory so it means the attribute wasn't present */
771                 if (v == -2) {
772                         /* Windows 2003 does this*/
773                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "objectClassCategory", 0);
774                         if (ret != LDB_SUCCESS) {
775                                 return ret;
776                         }
777                 }
778                 break;
779         }
780
781         case SAMLDB_TYPE_ATTRIBUTE: {
782                 const struct ldb_val *rdn_value;
783                 struct ldb_message_element *el;
784                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
785                 if (rdn_value == NULL) {
786                         return ldb_operr(ldb);
787                 }
788                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
789                         /* the RDN has prefix "CN" */
790                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
791                                 samdb_cn_to_lDAPDisplayName(ac->msg,
792                                                             (const char *) rdn_value->data));
793                         if (ret != LDB_SUCCESS) {
794                                 ldb_oom(ldb);
795                                 return ret;
796                         }
797                 }
798
799                 /* do not allow to mark an attributeSchema as RODC filtered if it
800                  * is system-critical */
801                 if (check_rodc_critical_attribute(ac->msg)) {
802                         ldb_asprintf_errstring(ldb,
803                                                "samldb: refusing schema add of %s - cannot combine critical attribute with RODC filtering",
804                                                ldb_dn_get_linearized(ac->msg->dn));
805                         return LDB_ERR_UNWILLING_TO_PERFORM;
806                 }
807
808                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
809                                                   "isSingleValued", "FALSE");
810                 if (ret != LDB_SUCCESS) return ret;
811
812                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
813                         struct GUID guid;
814                         /* a new GUID */
815                         guid = GUID_random();
816                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
817                         if (ret != LDB_SUCCESS) {
818                                 ldb_oom(ldb);
819                                 return ret;
820                         }
821                 }
822
823                 el = ldb_msg_find_element(ac->msg, "attributeSyntax");
824                 if (el) {
825                         /*
826                          * No need to scream if there isn't as we have code later on
827                          * that will take care of it.
828                          */
829                         const struct dsdb_syntax *syntax = find_syntax_map_by_ad_oid((const char *)el->values[0].data);
830                         if (!syntax) {
831                                 DEBUG(9, ("Can't find dsdb_syntax object for attributeSyntax %s\n",
832                                                 (const char *)el->values[0].data));
833                         } else {
834                                 unsigned int v = ldb_msg_find_attr_as_uint(ac->msg, "oMSyntax", 0);
835                                 const struct ldb_val *val = ldb_msg_find_ldb_val(ac->msg, "oMObjectClass");
836
837                                 if (v == 0) {
838                                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "oMSyntax", syntax->oMSyntax);
839                                         if (ret != LDB_SUCCESS) {
840                                                 return ret;
841                                         }
842                                 }
843                                 if (!val) {
844                                         struct ldb_val val2 = ldb_val_dup(ldb, &syntax->oMObjectClass);
845                                         if (val2.length > 0) {
846                                                 ret = ldb_msg_add_value(ac->msg, "oMObjectClass", &val2, NULL);
847                                                 if (ret != LDB_SUCCESS) {
848                                                         return ret;
849                                                 }
850                                         }
851                                 }
852                         }
853                 }
854
855                 /* handle msDS-IntID attribute */
856                 ret = samldb_add_handle_msDS_IntId(ac);
857                 if (ret != LDB_SUCCESS) return ret;
858
859                 ret = samldb_add_step(ac, samldb_add_entry);
860                 if (ret != LDB_SUCCESS) return ret;
861                 break;
862         }
863
864         default:
865                 ldb_asprintf_errstring(ldb, "Invalid entry type!");
866                 return LDB_ERR_OPERATIONS_ERROR;
867                 break;
868         }
869
870         return samldb_first_step(ac);
871 }
872
873 static int samldb_fill_foreignSecurityPrincipal_object(struct samldb_ctx *ac)
874 {
875         struct ldb_context *ldb;
876         const struct ldb_val *rdn_value;
877         struct dom_sid *sid;
878         int ret;
879
880         ldb = ldb_module_get_ctx(ac->module);
881
882         sid = samdb_result_dom_sid(ac->msg, ac->msg, "objectSid");
883         if (sid == NULL) {
884                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
885                 if (rdn_value == NULL) {
886                         return ldb_operr(ldb);
887                 }
888                 sid = dom_sid_parse_talloc(ac->msg,
889                                            (const char *)rdn_value->data);
890                 if (sid == NULL) {
891                         ldb_set_errstring(ldb,
892                                           "samldb: No valid SID found in ForeignSecurityPrincipal CN!");
893                         return LDB_ERR_CONSTRAINT_VIOLATION;
894                 }
895                 if (! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
896                         return ldb_operr(ldb);
897                 }
898         }
899
900         /* finally proceed with adding the entry */
901         ret = samldb_add_step(ac, samldb_add_entry);
902         if (ret != LDB_SUCCESS) return ret;
903
904         return samldb_first_step(ac);
905 }
906
907 static int samldb_schema_info_update(struct samldb_ctx *ac)
908 {
909         int ret;
910         struct ldb_context *ldb;
911         struct dsdb_schema *schema;
912
913         /* replicated update should always go through */
914         if (ldb_request_get_control(ac->req,
915                                     DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
916                 return LDB_SUCCESS;
917         }
918
919         /* do not update schemaInfo during provisioning */
920         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
921                 return LDB_SUCCESS;
922         }
923
924         ldb = ldb_module_get_ctx(ac->module);
925         schema = dsdb_get_schema(ldb, NULL);
926         if (!schema) {
927                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
928                               "samldb_schema_info_update: no dsdb_schema loaded");
929                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
930                 return ldb_operr(ldb);
931         }
932
933         ret = dsdb_module_schema_info_update(ac->module, schema,
934                                              DSDB_FLAG_NEXT_MODULE|
935                                              DSDB_FLAG_AS_SYSTEM,
936                                              ac->req);
937         if (ret != LDB_SUCCESS) {
938                 ldb_asprintf_errstring(ldb,
939                                        "samldb_schema_info_update: dsdb_module_schema_info_update failed with %s",
940                                        ldb_errstring(ldb));
941                 return ret;
942         }
943
944         return LDB_SUCCESS;
945 }
946
947 static int samldb_prim_group_tester(struct samldb_ctx *ac, uint32_t rid);
948 static int samldb_check_user_account_control_acl(struct samldb_ctx *ac,
949                                                  struct dom_sid *sid,
950                                                  uint32_t user_account_control,
951                                                  uint32_t user_account_control_old);
952
953 /*
954  * "Objectclass" trigger (MS-SAMR 3.1.1.8.1)
955  *
956  * Has to be invoked on "add" and "modify" operations on "user", "computer" and
957  * "group" objects.
958  * ac->msg contains the "add"/"modify" message
959  * ac->type contains the object type (main objectclass)
960  */
961 static int samldb_objectclass_trigger(struct samldb_ctx *ac)
962 {
963         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
964         void *skip_allocate_sids = ldb_get_opaque(ldb,
965                                                   "skip_allocate_sids");
966         struct ldb_message_element *el, *el2;
967         struct dom_sid *sid;
968         int ret;
969
970         /* make sure that "sAMAccountType" is not specified */
971         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
972         if (el != NULL) {
973                 ldb_set_errstring(ldb,
974                                   "samldb: sAMAccountType must not be specified!");
975                 return LDB_ERR_UNWILLING_TO_PERFORM;
976         }
977
978         /* Step 1: objectSid assignment */
979
980         /* Don't allow the objectSid to be changed. But beside the RELAX
981          * control we have also to guarantee that it can always be set with
982          * SYSTEM permissions. This is needed for the "samba3sam" backend. */
983         sid = samdb_result_dom_sid(ac, ac->msg, "objectSid");
984         if ((sid != NULL) && (!dsdb_module_am_system(ac->module)) &&
985             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
986                 ldb_set_errstring(ldb,
987                                   "samldb: objectSid must not be specified!");
988                 return LDB_ERR_UNWILLING_TO_PERFORM;
989         }
990
991         /* but generate a new SID when we do have an add operations */
992         if ((sid == NULL) && (ac->req->operation == LDB_ADD) && !skip_allocate_sids) {
993                 ret = samldb_add_step(ac, samldb_allocate_sid);
994                 if (ret != LDB_SUCCESS) return ret;
995         }
996
997         switch(ac->type) {
998         case SAMLDB_TYPE_USER: {
999                 bool uac_generated = false, uac_add_flags = false;
1000
1001                 /* Step 1.2: Default values */
1002                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1003                         "accountExpires", "9223372036854775807");
1004                 if (ret != LDB_SUCCESS) return ret;
1005                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1006                         "badPasswordTime", "0");
1007                 if (ret != LDB_SUCCESS) return ret;
1008                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1009                         "badPwdCount", "0");
1010                 if (ret != LDB_SUCCESS) return ret;
1011                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1012                         "codePage", "0");
1013                 if (ret != LDB_SUCCESS) return ret;
1014                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1015                         "countryCode", "0");
1016                 if (ret != LDB_SUCCESS) return ret;
1017                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1018                         "lastLogoff", "0");
1019                 if (ret != LDB_SUCCESS) return ret;
1020                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1021                         "lastLogon", "0");
1022                 if (ret != LDB_SUCCESS) return ret;
1023                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1024                         "logonCount", "0");
1025                 if (ret != LDB_SUCCESS) return ret;
1026                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1027                         "pwdLastSet", "0");
1028                 if (ret != LDB_SUCCESS) return ret;
1029
1030                 /* On add operations we might need to generate a
1031                  * "userAccountControl" (if it isn't specified). */
1032                 el = ldb_msg_find_element(ac->msg, "userAccountControl");
1033                 if ((el == NULL) && (ac->req->operation == LDB_ADD)) {
1034                         ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
1035                                                  "userAccountControl",
1036                                                  UF_NORMAL_ACCOUNT);
1037                         if (ret != LDB_SUCCESS) {
1038                                 return ret;
1039                         }
1040                         uac_generated = true;
1041                         uac_add_flags = true;
1042                 }
1043
1044                 el = ldb_msg_find_element(ac->msg, "userAccountControl");
1045                 if (el != NULL) {
1046                         uint32_t user_account_control, account_type;
1047                         /* Step 1.3: "userAccountControl" -> "sAMAccountType" mapping */
1048                         user_account_control = ldb_msg_find_attr_as_uint(ac->msg,
1049                                                                          "userAccountControl",
1050                                                                          0);
1051                         /* "userAccountControl" = 0 means "UF_NORMAL_ACCOUNT" */
1052                         if (user_account_control == 0) {
1053                                 user_account_control = UF_NORMAL_ACCOUNT;
1054                                 uac_generated = true;
1055                         }
1056
1057                         /*
1058                          * As per MS-SAMR 3.1.1.8.10 these flags have not to be set
1059                          */
1060                         if ((user_account_control & UF_LOCKOUT) != 0) {
1061                                 user_account_control &= ~UF_LOCKOUT;
1062                                 uac_generated = true;
1063                         }
1064                         if ((user_account_control & UF_PASSWORD_EXPIRED) != 0) {
1065                                 user_account_control &= ~UF_PASSWORD_EXPIRED;
1066                                 uac_generated = true;
1067                         }
1068
1069                         /* Temporary duplicate accounts aren't allowed */
1070                         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
1071                                 return LDB_ERR_OTHER;
1072                         }
1073
1074                         /* Workstation and (read-only) DC objects do need objectclass "computer" */
1075                         if ((samdb_find_attribute(ldb, ac->msg,
1076                                                   "objectclass", "computer") == NULL) &&
1077                             (user_account_control &
1078                              (UF_SERVER_TRUST_ACCOUNT | UF_WORKSTATION_TRUST_ACCOUNT))) {
1079                                 ldb_set_errstring(ldb,
1080                                                   "samldb: Requested account type does need objectclass 'computer'!");
1081                                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1082                         }
1083
1084                         account_type = ds_uf2atype(user_account_control);
1085                         if (account_type == 0) {
1086                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1087                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1088                         }
1089                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1090                                                  "sAMAccountType",
1091                                                  account_type);
1092                         if (ret != LDB_SUCCESS) {
1093                                 return ret;
1094                         }
1095                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
1096                         el2->flags = LDB_FLAG_MOD_REPLACE;
1097
1098                         /* "isCriticalSystemObject" might be set */
1099                         if (user_account_control &
1100                             (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1101                                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1102                                                          "TRUE");
1103                                 if (ret != LDB_SUCCESS) {
1104                                         return ret;
1105                                 }
1106                                 el2 = ldb_msg_find_element(ac->msg,
1107                                                            "isCriticalSystemObject");
1108                                 el2->flags = LDB_FLAG_MOD_REPLACE;
1109                         } else if (user_account_control & UF_WORKSTATION_TRUST_ACCOUNT) {
1110                                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1111                                                          "FALSE");
1112                                 if (ret != LDB_SUCCESS) {
1113                                         return ret;
1114                                 }
1115                                 el2 = ldb_msg_find_element(ac->msg,
1116                                                            "isCriticalSystemObject");
1117                                 el2->flags = LDB_FLAG_MOD_REPLACE;
1118                         }
1119
1120                         /* Step 1.4: "userAccountControl" -> "primaryGroupID" mapping */
1121                         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
1122                                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
1123
1124                                 /*
1125                                  * Older AD deployments don't know about the
1126                                  * RODC group
1127                                  */
1128                                 if (rid == DOMAIN_RID_READONLY_DCS) {
1129                                         ret = samldb_prim_group_tester(ac, rid);
1130                                         if (ret != LDB_SUCCESS) {
1131                                                 return ret;
1132                                         }
1133                                 }
1134
1135                                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1136                                                          "primaryGroupID", rid);
1137                                 if (ret != LDB_SUCCESS) {
1138                                         return ret;
1139                                 }
1140                                 el2 = ldb_msg_find_element(ac->msg,
1141                                                            "primaryGroupID");
1142                                 el2->flags = LDB_FLAG_MOD_REPLACE;
1143                         }
1144
1145                         /* Step 1.5: Add additional flags when needed */
1146                         /* Obviously this is done when the "userAccountControl"
1147                          * has been generated here (tested against Windows
1148                          * Server) */
1149                         if (uac_generated) {
1150                                 if (uac_add_flags) {
1151                                         user_account_control |= UF_ACCOUNTDISABLE;
1152                                         user_account_control |= UF_PASSWD_NOTREQD;
1153                                 }
1154
1155                                 ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
1156                                                          "userAccountControl",
1157                                                          user_account_control);
1158                                 if (ret != LDB_SUCCESS) {
1159                                         return ret;
1160                                 }
1161                         }
1162
1163                         ret = samldb_check_user_account_control_acl(ac, NULL,
1164                                                                     user_account_control, 0);
1165                         if (ret != LDB_SUCCESS) {
1166                                 return ret;
1167                         }
1168                 }
1169                 break;
1170         }
1171
1172         case SAMLDB_TYPE_GROUP: {
1173                 const char *tempstr;
1174
1175                 /* Step 2.2: Default values */
1176                 tempstr = talloc_asprintf(ac->msg, "%d",
1177                                           GTYPE_SECURITY_GLOBAL_GROUP);
1178                 if (tempstr == NULL) return ldb_operr(ldb);
1179                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1180                         "groupType", tempstr);
1181                 if (ret != LDB_SUCCESS) return ret;
1182
1183                 /* Step 2.3: "groupType" -> "sAMAccountType" */
1184                 el = ldb_msg_find_element(ac->msg, "groupType");
1185                 if (el != NULL) {
1186                         uint32_t group_type, account_type;
1187
1188                         group_type = ldb_msg_find_attr_as_uint(ac->msg,
1189                                                                "groupType", 0);
1190
1191                         /* The creation of builtin groups requires the
1192                          * RELAX control */
1193                         if (group_type == GTYPE_SECURITY_BUILTIN_LOCAL_GROUP) {
1194                                 if (ldb_request_get_control(ac->req,
1195                                                             LDB_CONTROL_RELAX_OID) == NULL) {
1196                                         return LDB_ERR_UNWILLING_TO_PERFORM;
1197                                 }
1198                         }
1199
1200                         account_type = ds_gtype2atype(group_type);
1201                         if (account_type == 0) {
1202                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1203                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1204                         }
1205                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1206                                                  "sAMAccountType",
1207                                                  account_type);
1208                         if (ret != LDB_SUCCESS) {
1209                                 return ret;
1210                         }
1211                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
1212                         el2->flags = LDB_FLAG_MOD_REPLACE;
1213                 }
1214                 break;
1215         }
1216
1217         default:
1218                 ldb_asprintf_errstring(ldb,
1219                                 "Invalid entry type!");
1220                 return LDB_ERR_OPERATIONS_ERROR;
1221                 break;
1222         }
1223
1224         return LDB_SUCCESS;
1225 }
1226
1227 /*
1228  * "Primary group ID" trigger (MS-SAMR 3.1.1.8.2)
1229  *
1230  * Has to be invoked on "add" and "modify" operations on "user" and "computer"
1231  * objects.
1232  * ac->msg contains the "add"/"modify" message
1233  */
1234
1235 static int samldb_prim_group_tester(struct samldb_ctx *ac, uint32_t rid)
1236 {
1237         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1238         struct dom_sid *sid;
1239         struct ldb_result *res;
1240         int ret;
1241         const char * const noattrs[] = { NULL };
1242
1243         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1244         if (sid == NULL) {
1245                 return ldb_operr(ldb);
1246         }
1247
1248         ret = dsdb_module_search(ac->module, ac, &res,
1249                                  ldb_get_default_basedn(ldb),
1250                                  LDB_SCOPE_SUBTREE,
1251                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1252                                  ac->req,
1253                                  "(objectSid=%s)",
1254                                  ldap_encode_ndr_dom_sid(ac, sid));
1255         if (ret != LDB_SUCCESS) {
1256                 return ret;
1257         }
1258         if (res->count != 1) {
1259                 talloc_free(res);
1260                 ldb_asprintf_errstring(ldb,
1261                                        "Failed to find primary group with RID %u!",
1262                                        rid);
1263                 return LDB_ERR_UNWILLING_TO_PERFORM;
1264         }
1265         talloc_free(res);
1266
1267         return LDB_SUCCESS;
1268 }
1269
1270 static int samldb_prim_group_set(struct samldb_ctx *ac)
1271 {
1272         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1273         uint32_t rid;
1274
1275         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1276         if (rid == (uint32_t) -1) {
1277                 /* we aren't affected of any primary group set */
1278                 return LDB_SUCCESS;
1279
1280         } else if (!ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
1281                 ldb_set_errstring(ldb,
1282                                   "The primary group isn't settable on add operations!");
1283                 return LDB_ERR_UNWILLING_TO_PERFORM;
1284         }
1285
1286         return samldb_prim_group_tester(ac, rid);
1287 }
1288
1289 static int samldb_prim_group_change(struct samldb_ctx *ac)
1290 {
1291         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1292         const char * const attrs[] = { "primaryGroupID", "memberOf", NULL };
1293         struct ldb_result *res, *group_res;
1294         struct ldb_message_element *el;
1295         struct ldb_message *msg;
1296         uint32_t prev_rid, new_rid;
1297         struct dom_sid *prev_sid, *new_sid;
1298         struct ldb_dn *prev_prim_group_dn, *new_prim_group_dn;
1299         int ret;
1300         const char * const noattrs[] = { NULL };
1301
1302         el = dsdb_get_single_valued_attr(ac->msg, "primaryGroupID",
1303                                          ac->req->operation);
1304         if (el == NULL) {
1305                 /* we are not affected */
1306                 return LDB_SUCCESS;
1307         }
1308
1309         /* Fetch information from the existing object */
1310
1311         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
1312                                     DSDB_FLAG_NEXT_MODULE, ac->req);
1313         if (ret != LDB_SUCCESS) {
1314                 return ret;
1315         }
1316
1317         /* Finds out the DN of the old primary group */
1318
1319         prev_rid = ldb_msg_find_attr_as_uint(res->msgs[0], "primaryGroupID",
1320                                              (uint32_t) -1);
1321         if (prev_rid == (uint32_t) -1) {
1322                 /* User objects do always have a mandatory "primaryGroupID"
1323                  * attribute. If this doesn't exist then the object is of the
1324                  * wrong type. This is the exact Windows error code */
1325                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1326         }
1327
1328         prev_sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), prev_rid);
1329         if (prev_sid == NULL) {
1330                 return ldb_operr(ldb);
1331         }
1332
1333         /* Finds out the DN of the new primary group
1334          * Notice: in order to parse the primary group ID correctly we create
1335          * a temporary message here. */
1336
1337         msg = ldb_msg_new(ac->msg);
1338         if (msg == NULL) {
1339                 return ldb_module_oom(ac->module);
1340         }
1341         ret = ldb_msg_add(msg, el, 0);
1342         if (ret != LDB_SUCCESS) {
1343                 return ret;
1344         }
1345         new_rid = ldb_msg_find_attr_as_uint(msg, "primaryGroupID", (uint32_t) -1);
1346         talloc_free(msg);
1347         if (new_rid == (uint32_t) -1) {
1348                 /* we aren't affected of any primary group change */
1349                 return LDB_SUCCESS;
1350         }
1351
1352         if (prev_rid == new_rid) {
1353                 return LDB_SUCCESS;
1354         }
1355
1356         ret = dsdb_module_search(ac->module, ac, &group_res,
1357                                  ldb_get_default_basedn(ldb),
1358                                  LDB_SCOPE_SUBTREE,
1359                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1360                                  ac->req,
1361                                  "(objectSid=%s)",
1362                                  ldap_encode_ndr_dom_sid(ac, prev_sid));
1363         if (ret != LDB_SUCCESS) {
1364                 return ret;
1365         }
1366         if (group_res->count != 1) {
1367                 return ldb_operr(ldb);
1368         }
1369         prev_prim_group_dn = group_res->msgs[0]->dn;
1370
1371         new_sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), new_rid);
1372         if (new_sid == NULL) {
1373                 return ldb_operr(ldb);
1374         }
1375
1376         ret = dsdb_module_search(ac->module, ac, &group_res,
1377                                  ldb_get_default_basedn(ldb),
1378                                  LDB_SCOPE_SUBTREE,
1379                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1380                                  ac->req,
1381                                  "(objectSid=%s)",
1382                                  ldap_encode_ndr_dom_sid(ac, new_sid));
1383         if (ret != LDB_SUCCESS) {
1384                 return ret;
1385         }
1386         if (group_res->count != 1) {
1387                 /* Here we know if the specified new primary group candidate is
1388                  * valid or not. */
1389                 return LDB_ERR_UNWILLING_TO_PERFORM;
1390         }
1391         new_prim_group_dn = group_res->msgs[0]->dn;
1392
1393         /* We need to be already a normal member of the new primary
1394          * group in order to be successful. */
1395         el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1396                                   ldb_dn_get_linearized(new_prim_group_dn));
1397         if (el == NULL) {
1398                 return LDB_ERR_UNWILLING_TO_PERFORM;
1399         }
1400
1401         /* Remove the "member" attribute on the new primary group */
1402         msg = ldb_msg_new(ac->msg);
1403         if (msg == NULL) {
1404                 return ldb_module_oom(ac->module);
1405         }
1406         msg->dn = new_prim_group_dn;
1407
1408         ret = samdb_msg_add_delval(ldb, msg, msg, "member",
1409                                    ldb_dn_get_linearized(ac->msg->dn));
1410         if (ret != LDB_SUCCESS) {
1411                 return ret;
1412         }
1413
1414         ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE, ac->req);
1415         if (ret != LDB_SUCCESS) {
1416                 return ret;
1417         }
1418         talloc_free(msg);
1419
1420         /* Add a "member" attribute for the previous primary group */
1421         msg = ldb_msg_new(ac->msg);
1422         if (msg == NULL) {
1423                 return ldb_module_oom(ac->module);
1424         }
1425         msg->dn = prev_prim_group_dn;
1426
1427         ret = samdb_msg_add_addval(ldb, msg, msg, "member",
1428                                    ldb_dn_get_linearized(ac->msg->dn));
1429         if (ret != LDB_SUCCESS) {
1430                 return ret;
1431         }
1432
1433         ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE, ac->req);
1434         if (ret != LDB_SUCCESS) {
1435                 return ret;
1436         }
1437         talloc_free(msg);
1438
1439         return LDB_SUCCESS;
1440 }
1441
1442 static int samldb_prim_group_trigger(struct samldb_ctx *ac)
1443 {
1444         int ret;
1445
1446         if (ac->req->operation == LDB_ADD) {
1447                 ret = samldb_prim_group_set(ac);
1448         } else {
1449                 ret = samldb_prim_group_change(ac);
1450         }
1451
1452         return ret;
1453 }
1454
1455 /**
1456  * Validate that the restriction in point 5 of MS-SAMR 3.1.1.8.10 userAccountControl is honoured
1457  *
1458  */
1459 static int samldb_check_user_account_control_acl(struct samldb_ctx *ac,
1460                                                  struct dom_sid *sid,
1461                                                  uint32_t user_account_control,
1462                                                  uint32_t user_account_control_old)
1463 {
1464         int i, ret = 0;
1465         bool need_acl_check = false;
1466         struct ldb_result *res;
1467         const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL};
1468         struct security_token *user_token;
1469         struct security_descriptor *domain_sd;
1470         struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module));
1471         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1472         const struct uac_to_guid {
1473                 uint32_t uac;
1474                 uint32_t priv_to_change_from;
1475                 const char *oid;
1476                 const char *guid;
1477                 enum sec_privilege privilege;
1478                 bool delete_is_privileged;
1479                 bool admin_required;
1480                 const char *error_string;
1481         } map[] = {
1482                 {
1483                         .uac = UF_PASSWD_NOTREQD,
1484                         .guid = GUID_DRS_UPDATE_PASSWORD_NOT_REQUIRED_BIT,
1485                         .error_string = "Adding the UF_PASSWD_NOTREQD bit in userAccountControl requires the Update-Password-Not-Required-Bit right that was not given on the Domain object"
1486                 },
1487                 {
1488                         .uac = UF_DONT_EXPIRE_PASSWD,
1489                         .guid = GUID_DRS_UNEXPIRE_PASSWORD,
1490                         .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object"
1491                 },
1492                 {
1493                         .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED,
1494                         .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD,
1495                         .error_string = "Adding the UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED bit in userAccountControl requires the Enable-Per-User-Reversibly-Encrypted-Password right that was not given on the Domain object"
1496                 },
1497                 {
1498                         .uac = UF_SERVER_TRUST_ACCOUNT,
1499                         .guid = GUID_DRS_DS_INSTALL_REPLICA,
1500                         .error_string = "Adding the UF_SERVER_TRUST_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object"
1501                 },
1502                 {
1503                         .uac = UF_PARTIAL_SECRETS_ACCOUNT,
1504                         .guid = GUID_DRS_DS_INSTALL_REPLICA,
1505                         .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object"
1506                 },
1507                 {
1508                         .uac = UF_WORKSTATION_TRUST_ACCOUNT,
1509                         .priv_to_change_from = UF_NORMAL_ACCOUNT,
1510                         .error_string = "Swapping UF_NORMAL_ACCOUNT to UF_WORKSTATION_TRUST_ACCOUNT requires the user to be a member of the domain admins group"
1511                 },
1512                 {
1513                         .uac = UF_NORMAL_ACCOUNT,
1514                         .priv_to_change_from = UF_WORKSTATION_TRUST_ACCOUNT,
1515                         .error_string = "Swapping UF_WORKSTATION_TRUST_ACCOUNT to UF_NORMAL_ACCOUNT requires the user to be a member of the domain admins group"
1516                 },
1517                 {
1518                         .uac = UF_INTERDOMAIN_TRUST_ACCOUNT,
1519                         .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
1520                         .error_string = "Updating the UF_INTERDOMAIN_TRUST_ACCOUNT bit in userAccountControl is not permitted over LDAP.  This bit is restricted to the LSA CreateTrustedDomain interface",
1521                         .delete_is_privileged = true
1522                 },
1523                 {
1524                         .uac = UF_TRUSTED_FOR_DELEGATION,
1525                         .privilege = SEC_PRIV_ENABLE_DELEGATION,
1526                         .delete_is_privileged = true,
1527                         .error_string = "Updating the UF_TRUSTED_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege"
1528                 },
1529                 {
1530                         .uac = UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION,
1531                         .privilege = SEC_PRIV_ENABLE_DELEGATION,
1532                         .delete_is_privileged = true,
1533                         .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege"
1534                 }
1535
1536         };
1537
1538         if (dsdb_module_am_system(ac->module)) {
1539                 return LDB_SUCCESS;
1540         }
1541
1542         for (i = 0; i < ARRAY_SIZE(map); i++) {
1543                 if (user_account_control & map[i].uac) {
1544                         need_acl_check = true;
1545                         break;
1546                 }
1547         }
1548         if (need_acl_check == false) {
1549                 return LDB_SUCCESS;
1550         }
1551
1552         user_token = acl_user_token(ac->module);
1553         if (user_token == NULL) {
1554                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1555         }
1556
1557         ret = dsdb_module_search_dn(ac->module, ac, &res,
1558                                     domain_dn,
1559                                     sd_attrs,
1560                                     DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED,
1561                                     ac->req);
1562         if (ret != LDB_SUCCESS) {
1563                 return ret;
1564         }
1565         if (res->count != 1) {
1566                 return ldb_module_operr(ac->module);
1567         }
1568
1569         ret = dsdb_get_sd_from_ldb_message(ldb,
1570                                            ac, res->msgs[0], &domain_sd);
1571
1572         if (ret != LDB_SUCCESS) {
1573                 return ret;
1574         }
1575
1576         for (i = 0; i < ARRAY_SIZE(map); i++) {
1577                 uint32_t this_uac_new = user_account_control & map[i].uac;
1578                 uint32_t this_uac_old = user_account_control_old & map[i].uac;
1579                 if (this_uac_new != this_uac_old) {
1580                         if (this_uac_old != 0) {
1581                                 if (map[i].delete_is_privileged == false) {
1582                                         continue;
1583                                 }
1584                         }
1585                         if (map[i].oid) {
1586                                 struct ldb_control *control = ldb_request_get_control(ac->req, map[i].oid);
1587                                 if (control == NULL) {
1588                                         ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1589                                 }
1590                         } else if (map[i].privilege != SEC_PRIV_INVALID) {
1591                                 bool have_priv = security_token_has_privilege(user_token,
1592                                                                               map[i].privilege);
1593                                 if (have_priv == false) {
1594                                         ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1595                                 }
1596                         } else if (map[i].priv_to_change_from & user_account_control_old) {
1597                                 bool is_admin = security_token_has_builtin_administrators(user_token);
1598                                 if (is_admin == false) {
1599                                         ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1600                                 }
1601                         } else if (map[i].guid) {
1602                                 ret = acl_check_extended_right(ac, domain_sd,
1603                                                                user_token,
1604                                                                map[i].guid,
1605                                                                SEC_ADS_CONTROL_ACCESS,
1606                                                                sid);
1607                         } else {
1608                                 ret = LDB_SUCCESS;
1609                         }
1610                         if (ret != LDB_SUCCESS) {
1611                                 break;
1612                         }
1613                 }
1614         }
1615         if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
1616                 switch (ac->req->operation) {
1617                 case LDB_ADD:
1618                         ldb_asprintf_errstring(ldb_module_get_ctx(ac->module),
1619                                                "Failed to add %s: %s",
1620                                                ldb_dn_get_linearized(ac->msg->dn),
1621                                                map[i].error_string);
1622                         break;
1623                 case LDB_MODIFY:
1624                         ldb_asprintf_errstring(ldb_module_get_ctx(ac->module),
1625                                                "Failed to modify %s: %s",
1626                                                ldb_dn_get_linearized(ac->msg->dn),
1627                                                map[i].error_string);
1628                         break;
1629                 default:
1630                         return ldb_module_operr(ac->module);
1631                 }
1632                 if (map[i].guid) {
1633                         dsdb_acl_debug(domain_sd, acl_user_token(ac->module),
1634                                        domain_dn,
1635                                        true,
1636                                        10);
1637                 }
1638         }
1639         return ret;
1640 }
1641
1642 /**
1643  * This function is called on LDB modify operations. It performs some additions/
1644  * replaces on the current LDB message when "userAccountControl" changes.
1645  */
1646 static int samldb_user_account_control_change(struct samldb_ctx *ac)
1647 {
1648         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1649         uint32_t user_account_control, old_user_account_control, account_type;
1650         struct ldb_message_element *el;
1651         struct ldb_message *tmp_msg;
1652         struct dom_sid *sid;
1653         int ret;
1654         struct ldb_result *res;
1655         const char * const attrs[] = { "userAccountControl", "objectClass",
1656                                        "lockoutTime", "objectSid", NULL };
1657         unsigned int i;
1658         bool is_computer = false, uac_generated = false;
1659
1660         el = dsdb_get_single_valued_attr(ac->msg, "userAccountControl",
1661                                          ac->req->operation);
1662         if (el == NULL) {
1663                 /* we are not affected */
1664                 return LDB_SUCCESS;
1665         }
1666
1667         /* Create a temporary message for fetching the "userAccountControl" */
1668         tmp_msg = ldb_msg_new(ac->msg);
1669         if (tmp_msg == NULL) {
1670                 return ldb_module_oom(ac->module);
1671         }
1672         ret = ldb_msg_add(tmp_msg, el, 0);
1673         if (ret != LDB_SUCCESS) {
1674                 return ret;
1675         }
1676         user_account_control = ldb_msg_find_attr_as_uint(tmp_msg,
1677                                                          "userAccountControl",
1678                                                          0);
1679         talloc_free(tmp_msg);
1680
1681         /* Temporary duplicate accounts aren't allowed */
1682         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
1683                 return LDB_ERR_OTHER;
1684         }
1685
1686         /* Fetch the old "userAccountControl" and "objectClass" */
1687         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
1688                                     DSDB_FLAG_NEXT_MODULE, ac->req);
1689         if (ret != LDB_SUCCESS) {
1690                 return ret;
1691         }
1692         old_user_account_control = ldb_msg_find_attr_as_uint(res->msgs[0], "userAccountControl", 0);
1693         if (old_user_account_control == 0) {
1694                 return ldb_operr(ldb);
1695         }
1696         el = ldb_msg_find_element(res->msgs[0], "objectClass");
1697         if (el == NULL) {
1698                 return ldb_operr(ldb);
1699         }
1700
1701         /* When we do not have objectclass "computer" we cannot switch to a (read-only) DC */
1702         for (i = 0; i < el->num_values; i++) {
1703                 if (ldb_attr_cmp((char *)el->values[i].data, "computer") == 0) {
1704                         is_computer = true;
1705                         break;
1706                 }
1707         }
1708         if (!is_computer &&
1709             (user_account_control & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT))) {
1710                 ldb_set_errstring(ldb,
1711                                   "samldb: Requested account type does need objectclass 'computer'!");
1712                 return LDB_ERR_UNWILLING_TO_PERFORM;
1713         }
1714
1715         /*
1716          * The functions "ds_uf2atype" and "ds_uf2prim_group_rid" are used as
1717          * detectors for account type changes.
1718          * So if the account type does change then we need to adjust the
1719          * "sAMAccountType", the "isCriticalSystemObject" and the
1720          * "primaryGroupID" attribute.
1721          */
1722         if ((ds_uf2atype(user_account_control)
1723              == ds_uf2atype(old_user_account_control)) &&
1724             (ds_uf2prim_group_rid(user_account_control)
1725              == ds_uf2prim_group_rid(old_user_account_control))) {
1726                 return LDB_SUCCESS;
1727         }
1728
1729         account_type = ds_uf2atype(user_account_control);
1730         if (account_type == 0) {
1731                 /*
1732                  * When there is no account type embedded in "userAccountControl"
1733                  * fall back to default "UF_NORMAL_ACCOUNT".
1734                  */
1735                 if (user_account_control == 0) {
1736                         ldb_set_errstring(ldb,
1737                                           "samldb: Invalid user account control value!");
1738                         return LDB_ERR_UNWILLING_TO_PERFORM;
1739                 }
1740
1741                 user_account_control |= UF_NORMAL_ACCOUNT;
1742                 uac_generated = true;
1743                 account_type = ATYPE_NORMAL_ACCOUNT;
1744         }
1745         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1746                                  account_type);
1747         if (ret != LDB_SUCCESS) {
1748                 return ret;
1749         }
1750         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1751         el->flags = LDB_FLAG_MOD_REPLACE;
1752
1753         /* As per MS-SAMR 3.1.1.8.10 these flags have not to be set */
1754         if ((user_account_control & UF_LOCKOUT) != 0) {
1755                 /* "lockoutTime" reset as per MS-SAMR 3.1.1.8.10 */
1756                 uint64_t lockout_time = ldb_msg_find_attr_as_uint64(res->msgs[0],
1757                                                                     "lockoutTime",
1758                                                                     0);
1759                 if (lockout_time != 0) {
1760                         ldb_msg_remove_attr(ac->msg, "lockoutTime");
1761                         ret = samdb_msg_add_uint64(ldb, ac->msg, ac->msg,
1762                                                    "lockoutTime", (NTTIME)0);
1763                         if (ret != LDB_SUCCESS) {
1764                                 return ret;
1765                         }
1766                         el = ldb_msg_find_element(ac->msg, "lockoutTime");
1767                         el->flags = LDB_FLAG_MOD_REPLACE;
1768                 }
1769
1770                 user_account_control &= ~UF_LOCKOUT;
1771                 uac_generated = true;
1772         }
1773         if ((user_account_control & UF_PASSWORD_EXPIRED) != 0) {
1774                 /* "pwdLastSet" reset as password expiration has been forced  */
1775                 ldb_msg_remove_attr(ac->msg, "pwdLastSet");
1776                 ret = samdb_msg_add_uint64(ldb, ac->msg, ac->msg, "pwdLastSet",
1777                                            (NTTIME)0);
1778                 if (ret != LDB_SUCCESS) {
1779                         return ret;
1780                 }
1781                 el = ldb_msg_find_element(ac->msg, "pwdLastSet");
1782                 el->flags = LDB_FLAG_MOD_REPLACE;
1783
1784                 user_account_control &= ~UF_PASSWORD_EXPIRED;
1785                 uac_generated = true;
1786         }
1787
1788         /* "isCriticalSystemObject" might be set/changed */
1789         if (user_account_control
1790             & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1791                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1792                                          "TRUE");
1793                 if (ret != LDB_SUCCESS) {
1794                         return ret;
1795                 }
1796                 el = ldb_msg_find_element(ac->msg,
1797                                            "isCriticalSystemObject");
1798                 el->flags = LDB_FLAG_MOD_REPLACE;
1799         } else if (user_account_control & UF_WORKSTATION_TRUST_ACCOUNT) {
1800                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1801                                          "FALSE");
1802                 if (ret != LDB_SUCCESS) {
1803                         return ret;
1804                 }
1805                 el = ldb_msg_find_element(ac->msg,
1806                                            "isCriticalSystemObject");
1807                 el->flags = LDB_FLAG_MOD_REPLACE;
1808         }
1809
1810         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
1811                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
1812
1813                 /* Older AD deployments don't know about the RODC group */
1814                 if (rid == DOMAIN_RID_READONLY_DCS) {
1815                         ret = samldb_prim_group_tester(ac, rid);
1816                         if (ret != LDB_SUCCESS) {
1817                                 return ret;
1818                         }
1819                 }
1820
1821                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1822                                          "primaryGroupID", rid);
1823                 if (ret != LDB_SUCCESS) {
1824                         return ret;
1825                 }
1826                 el = ldb_msg_find_element(ac->msg,
1827                                            "primaryGroupID");
1828                 el->flags = LDB_FLAG_MOD_REPLACE;
1829         }
1830
1831         /* Propagate eventual "userAccountControl" attribute changes */
1832         if (uac_generated) {
1833                 char *tempstr = talloc_asprintf(ac->msg, "%d",
1834                                                 user_account_control);
1835                 if (tempstr == NULL) {
1836                         return ldb_module_oom(ac->module);
1837                 }
1838
1839                 /* Overwrite "userAccountControl" correctly */
1840                 el = dsdb_get_single_valued_attr(ac->msg, "userAccountControl",
1841                                                  ac->req->operation);
1842                 el->values[0].data = (uint8_t *) tempstr;
1843                 el->values[0].length = strlen(tempstr);
1844         }
1845
1846         sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
1847         if (sid == NULL) {
1848                 return ldb_module_operr(ac->module);
1849         }
1850
1851         ret = samldb_check_user_account_control_acl(ac, sid, user_account_control,
1852                                                     old_user_account_control);
1853         if (ret != LDB_SUCCESS) {
1854                 return ret;
1855         }
1856
1857         return LDB_SUCCESS;
1858 }
1859
1860 static int samldb_group_type_change(struct samldb_ctx *ac)
1861 {
1862         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1863         uint32_t group_type, old_group_type, account_type;
1864         struct ldb_message_element *el;
1865         struct ldb_message *tmp_msg;
1866         int ret;
1867         struct ldb_result *res;
1868         const char * const attrs[] = { "groupType", NULL };
1869
1870         el = dsdb_get_single_valued_attr(ac->msg, "groupType",
1871                                          ac->req->operation);
1872         if (el == NULL) {
1873                 /* we are not affected */
1874                 return LDB_SUCCESS;
1875         }
1876
1877         /* Create a temporary message for fetching the "groupType" */
1878         tmp_msg = ldb_msg_new(ac->msg);
1879         if (tmp_msg == NULL) {
1880                 return ldb_module_oom(ac->module);
1881         }
1882         ret = ldb_msg_add(tmp_msg, el, 0);
1883         if (ret != LDB_SUCCESS) {
1884                 return ret;
1885         }
1886         group_type = ldb_msg_find_attr_as_uint(tmp_msg, "groupType", 0);
1887         talloc_free(tmp_msg);
1888
1889         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
1890                                     DSDB_FLAG_NEXT_MODULE |
1891                                     DSDB_SEARCH_SHOW_DELETED, ac->req);
1892         if (ret != LDB_SUCCESS) {
1893                 return ret;
1894         }
1895         old_group_type = ldb_msg_find_attr_as_uint(res->msgs[0], "groupType", 0);
1896         if (old_group_type == 0) {
1897                 return ldb_operr(ldb);
1898         }
1899
1900         /* Group type switching isn't so easy as it seems: We can only
1901          * change in this directions: global <-> universal <-> local
1902          * On each step also the group type itself
1903          * (security/distribution) is variable. */
1904
1905         if (ldb_request_get_control(ac->req, LDB_CONTROL_PROVISION_OID) == NULL) {
1906                 switch (group_type) {
1907                 case GTYPE_SECURITY_GLOBAL_GROUP:
1908                 case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
1909                         /* change to "universal" allowed */
1910                         if ((old_group_type == GTYPE_SECURITY_DOMAIN_LOCAL_GROUP) ||
1911                         (old_group_type == GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP)) {
1912                                 ldb_set_errstring(ldb,
1913                                         "samldb: Change from security/distribution local group forbidden!");
1914                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1915                         }
1916                 break;
1917
1918                 case GTYPE_SECURITY_UNIVERSAL_GROUP:
1919                 case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
1920                         /* each change allowed */
1921                 break;
1922                 case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
1923                 case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
1924                         /* change to "universal" allowed */
1925                         if ((old_group_type == GTYPE_SECURITY_GLOBAL_GROUP) ||
1926                         (old_group_type == GTYPE_DISTRIBUTION_GLOBAL_GROUP)) {
1927                                 ldb_set_errstring(ldb,
1928                                         "samldb: Change from security/distribution global group forbidden!");
1929                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1930                         }
1931                 break;
1932
1933                 case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
1934                 default:
1935                         /* we don't allow this "groupType" values */
1936                         return LDB_ERR_UNWILLING_TO_PERFORM;
1937                 break;
1938                 }
1939         }
1940
1941         account_type =  ds_gtype2atype(group_type);
1942         if (account_type == 0) {
1943                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1944                 return LDB_ERR_UNWILLING_TO_PERFORM;
1945         }
1946         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1947                                  account_type);
1948         if (ret != LDB_SUCCESS) {
1949                 return ret;
1950         }
1951         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1952         el->flags = LDB_FLAG_MOD_REPLACE;
1953
1954         return LDB_SUCCESS;
1955 }
1956
1957 static int samldb_sam_accountname_check(struct samldb_ctx *ac)
1958 {
1959         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1960         const char * const no_attrs[] = { NULL };
1961         struct ldb_result *res;
1962         const char *sam_accountname, *enc_str;
1963         struct ldb_message_element *el;
1964         struct ldb_message *tmp_msg;
1965         int ret;
1966
1967         el = dsdb_get_single_valued_attr(ac->msg, "sAMAccountName",
1968                                          ac->req->operation);
1969         if (el == NULL) {
1970                 /* we are not affected */
1971                 return LDB_SUCCESS;
1972         }
1973
1974         /* Create a temporary message for fetching the "sAMAccountName" */
1975         tmp_msg = ldb_msg_new(ac->msg);
1976         if (tmp_msg == NULL) {
1977                 return ldb_module_oom(ac->module);
1978         }
1979         ret = ldb_msg_add(tmp_msg, el, 0);
1980         if (ret != LDB_SUCCESS) {
1981                 return ret;
1982         }
1983
1984         /* We must not steal the original string, it belongs to the caller! */
1985         sam_accountname = talloc_strdup(ac, 
1986                                         ldb_msg_find_attr_as_string(tmp_msg, "sAMAccountName", NULL));
1987         talloc_free(tmp_msg);
1988
1989         if (sam_accountname == NULL) {
1990                 /* The "sAMAccountName" cannot be nothing */
1991                 ldb_set_errstring(ldb,
1992                                   "samldb: Empty account names aren't allowed!");
1993                 return LDB_ERR_UNWILLING_TO_PERFORM;
1994         }
1995
1996         enc_str = ldb_binary_encode_string(ac, sam_accountname);
1997         if (enc_str == NULL) {
1998                 return ldb_module_oom(ac->module);
1999         }
2000
2001         /* Make sure that a "sAMAccountName" is only used once */
2002
2003         ret = dsdb_module_search(ac->module, ac, &res,
2004                                  ldb_get_default_basedn(ldb),
2005                                  LDB_SCOPE_SUBTREE, no_attrs,
2006                                  DSDB_FLAG_NEXT_MODULE, ac->req,
2007                                  "(sAMAccountName=%s)", enc_str);
2008         if (ret != LDB_SUCCESS) {
2009                 return ret;
2010         }
2011         if (res->count > 1) {
2012                 return ldb_operr(ldb);
2013         } else if (res->count == 1) {
2014                 if (ldb_dn_compare(res->msgs[0]->dn, ac->msg->dn) != 0) {
2015                         ldb_asprintf_errstring(ldb,
2016                                                "samldb: Account name (sAMAccountName) '%s' already in use!",
2017                                                sam_accountname);
2018                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
2019                 }
2020         }
2021         talloc_free(res);
2022
2023         return LDB_SUCCESS;
2024 }
2025
2026 static int samldb_member_check(struct samldb_ctx *ac)
2027 {
2028         const char * const attrs[] = { "objectSid", NULL };
2029         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2030         struct ldb_message_element *el;
2031         struct ldb_dn *member_dn;
2032         struct dom_sid *sid;
2033         struct ldb_result *res;
2034         struct dom_sid *group_sid;
2035         unsigned int i, j;
2036         int ret;
2037
2038         /* Fetch information from the existing object */
2039
2040         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
2041                                  DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED, ac->req, NULL);
2042         if (ret != LDB_SUCCESS) {
2043                 return ret;
2044         }
2045         if (res->count != 1) {
2046                 return ldb_operr(ldb);
2047         }
2048
2049         group_sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
2050         if (group_sid == NULL) {
2051                 return ldb_operr(ldb);
2052         }
2053
2054         /* We've to walk over all modification entries and consider the "member"
2055          * ones. */
2056         for (i = 0; i < ac->msg->num_elements; i++) {
2057                 if (ldb_attr_cmp(ac->msg->elements[i].name, "member") != 0) {
2058                         continue;
2059                 }
2060
2061                 el = &ac->msg->elements[i];
2062                 for (j = 0; j < el->num_values; j++) {
2063                         struct ldb_result *group_res;
2064                         const char *group_attrs[] = { "primaryGroupID" , NULL };
2065                         uint32_t prim_group_rid;
2066
2067                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE) {
2068                                 /* Deletes will be handled in
2069                                  * repl_meta_data, and deletes not
2070                                  * matching a member will return
2071                                  * LDB_ERR_UNWILLING_TO_PERFORM
2072                                  * there */
2073                                 continue;
2074                         }
2075
2076                         member_dn = ldb_dn_from_ldb_val(ac, ldb,
2077                                                         &el->values[j]);
2078                         if (!ldb_dn_validate(member_dn)) {
2079                                 return ldb_operr(ldb);
2080                         }
2081
2082                         /* Denies to add "member"s to groups which are primary
2083                          * ones for them - in this case return
2084                          * ERR_ENTRY_ALREADY_EXISTS. */
2085
2086                         ret = dsdb_module_search_dn(ac->module, ac, &group_res,
2087                                                     member_dn, group_attrs,
2088                                                     DSDB_FLAG_NEXT_MODULE, ac->req);
2089                         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2090                                 /* member DN doesn't exist yet */
2091                                 continue;
2092                         }
2093                         if (ret != LDB_SUCCESS) {
2094                                 return ret;
2095                         }
2096                         prim_group_rid = ldb_msg_find_attr_as_uint(group_res->msgs[0], "primaryGroupID", (uint32_t)-1);
2097                         if (prim_group_rid == (uint32_t) -1) {
2098                                 /* the member hasn't to be a user account ->
2099                                  * therefore no check needed in this case. */
2100                                 continue;
2101                         }
2102
2103                         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
2104                                               prim_group_rid);
2105                         if (sid == NULL) {
2106                                 return ldb_operr(ldb);
2107                         }
2108
2109                         if (dom_sid_equal(group_sid, sid)) {
2110                                 ldb_asprintf_errstring(ldb,
2111                                                        "samldb: member %s already set via primaryGroupID %u",
2112                                                        ldb_dn_get_linearized(member_dn), prim_group_rid);
2113                                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
2114                         }
2115                 }
2116         }
2117
2118         talloc_free(res);
2119
2120         return LDB_SUCCESS;
2121 }
2122
2123 /* SAM objects have special rules regarding the "description" attribute on
2124  * modify operations. */
2125 static int samldb_description_check(struct samldb_ctx *ac, bool *modified)
2126 {
2127         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2128         const char * const attrs[] = { "objectClass", "description", NULL };
2129         struct ldb_result *res;
2130         unsigned int i;
2131         int ret;
2132
2133         /* Fetch information from the existing object */
2134         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
2135                                  DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED, ac->req,
2136                                  "(|(objectclass=user)(objectclass=group)(objectclass=samDomain)(objectclass=samServer))");
2137         if (ret != LDB_SUCCESS) {
2138                 /* don't treat it specially ... let normal error codes
2139                    happen from other places */
2140                 ldb_reset_err_string(ldb);
2141                 return LDB_SUCCESS;
2142         }
2143         if (res->count == 0) {
2144                 /* we didn't match the filter */
2145                 talloc_free(res);
2146                 return LDB_SUCCESS;
2147         }
2148
2149         /* We've to walk over all modification entries and consider the
2150          * "description" ones. */
2151         for (i = 0; i < ac->msg->num_elements; i++) {
2152                 if (ldb_attr_cmp(ac->msg->elements[i].name, "description") == 0) {
2153                         ac->msg->elements[i].flags |= LDB_FLAG_INTERNAL_FORCE_SINGLE_VALUE_CHECK;
2154                         *modified = true;
2155                 }
2156         }
2157
2158         talloc_free(res);
2159
2160         return LDB_SUCCESS;
2161 }
2162
2163 /* This trigger adapts the "servicePrincipalName" attributes if the
2164  * "dNSHostName" and/or "sAMAccountName" attribute change(s) */
2165 static int samldb_service_principal_names_change(struct samldb_ctx *ac)
2166 {
2167         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2168         struct ldb_message_element *el = NULL, *el2 = NULL;
2169         struct ldb_message *msg;
2170         const char * const attrs[] = { "servicePrincipalName", NULL };
2171         struct ldb_result *res;
2172         const char *dns_hostname = NULL, *old_dns_hostname = NULL,
2173                    *sam_accountname = NULL, *old_sam_accountname = NULL;
2174         unsigned int i, j;
2175         int ret;
2176
2177         el = dsdb_get_single_valued_attr(ac->msg, "dNSHostName",
2178                                          ac->req->operation);
2179         el2 = dsdb_get_single_valued_attr(ac->msg, "sAMAccountName",
2180                                           ac->req->operation);
2181         if ((el == NULL) && (el2 == NULL)) {
2182                 /* we are not affected */
2183                 return LDB_SUCCESS;
2184         }
2185
2186         /* Create a temporary message for fetching the "dNSHostName" */
2187         if (el != NULL) {
2188                 const char *dns_attrs[] = { "dNSHostName", NULL };
2189                 msg = ldb_msg_new(ac->msg);
2190                 if (msg == NULL) {
2191                         return ldb_module_oom(ac->module);
2192                 }
2193                 ret = ldb_msg_add(msg, el, 0);
2194                 if (ret != LDB_SUCCESS) {
2195                         return ret;
2196                 }
2197                 dns_hostname = talloc_strdup(ac, 
2198                                              ldb_msg_find_attr_as_string(msg, "dNSHostName", NULL));
2199                 if (dns_hostname == NULL) {
2200                         return ldb_module_oom(ac->module);
2201                 }
2202                         
2203                 talloc_free(msg);
2204
2205                 ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn,
2206                                             dns_attrs, DSDB_FLAG_NEXT_MODULE, ac->req);
2207                 if (ret == LDB_SUCCESS) {
2208                         old_dns_hostname = ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
2209                 }
2210         }
2211
2212         /* Create a temporary message for fetching the "sAMAccountName" */
2213         if (el2 != NULL) {
2214                 char *tempstr, *tempstr2 = NULL;
2215                 const char *acct_attrs[] = { "sAMAccountName", NULL };
2216
2217                 msg = ldb_msg_new(ac->msg);
2218                 if (msg == NULL) {
2219                         return ldb_module_oom(ac->module);
2220                 }
2221                 ret = ldb_msg_add(msg, el2, 0);
2222                 if (ret != LDB_SUCCESS) {
2223                         return ret;
2224                 }
2225                 tempstr = talloc_strdup(ac,
2226                                         ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL));
2227                 talloc_free(msg);
2228
2229                 ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, acct_attrs,
2230                                             DSDB_FLAG_NEXT_MODULE, ac->req);
2231                 if (ret == LDB_SUCCESS) {
2232                         tempstr2 = talloc_strdup(ac,
2233                                                  ldb_msg_find_attr_as_string(res->msgs[0],
2234                                                                              "sAMAccountName", NULL));
2235                 }
2236
2237
2238                 /* The "sAMAccountName" needs some additional trimming: we need
2239                  * to remove the trailing "$"s if they exist. */
2240                 if ((tempstr != NULL) && (tempstr[0] != '\0') &&
2241                     (tempstr[strlen(tempstr) - 1] == '$')) {
2242                         tempstr[strlen(tempstr) - 1] = '\0';
2243                 }
2244                 if ((tempstr2 != NULL) && (tempstr2[0] != '\0') &&
2245                     (tempstr2[strlen(tempstr2) - 1] == '$')) {
2246                         tempstr2[strlen(tempstr2) - 1] = '\0';
2247                 }
2248                 sam_accountname = tempstr;
2249                 old_sam_accountname = tempstr2;
2250         }
2251
2252         if (old_dns_hostname == NULL) {
2253                 /* we cannot change when the old name is unknown */
2254                 dns_hostname = NULL;
2255         }
2256         if ((old_dns_hostname != NULL) && (dns_hostname != NULL) &&
2257             (strcasecmp_m(old_dns_hostname, dns_hostname) == 0)) {
2258                 /* The "dNSHostName" didn't change */
2259                 dns_hostname = NULL;
2260         }
2261
2262         if (old_sam_accountname == NULL) {
2263                 /* we cannot change when the old name is unknown */
2264                 sam_accountname = NULL;
2265         }
2266         if ((old_sam_accountname != NULL) && (sam_accountname != NULL) &&
2267             (strcasecmp_m(old_sam_accountname, sam_accountname) == 0)) {
2268                 /* The "sAMAccountName" didn't change */
2269                 sam_accountname = NULL;
2270         }
2271
2272         if ((dns_hostname == NULL) && (sam_accountname == NULL)) {
2273                 /* Well, there are information missing (old name(s)) or the
2274                  * names didn't change. We've nothing to do and can exit here */
2275                 return LDB_SUCCESS;
2276         }
2277
2278         /* Potential "servicePrincipalName" changes in the same request have to
2279          * be handled before the update (Windows behaviour). */
2280         el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
2281         if (el != NULL) {
2282                 msg = ldb_msg_new(ac->msg);
2283                 if (msg == NULL) {
2284                         return ldb_module_oom(ac->module);
2285                 }
2286                 msg->dn = ac->msg->dn;
2287
2288                 do {
2289                         ret = ldb_msg_add(msg, el, el->flags);
2290                         if (ret != LDB_SUCCESS) {
2291                                 return ret;
2292                         }
2293
2294                         ldb_msg_remove_element(ac->msg, el);
2295
2296                         el = ldb_msg_find_element(ac->msg,
2297                                                   "servicePrincipalName");
2298                 } while (el != NULL);
2299
2300                 ret = dsdb_module_modify(ac->module, msg,
2301                                          DSDB_FLAG_NEXT_MODULE, ac->req);
2302                 if (ret != LDB_SUCCESS) {
2303                         return ret;
2304                 }
2305                 talloc_free(msg);
2306         }
2307
2308         /* Fetch the "servicePrincipalName"s if any */
2309         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
2310                                  DSDB_FLAG_NEXT_MODULE, ac->req, NULL);
2311         if (ret != LDB_SUCCESS) {
2312                 return ret;
2313         }
2314         if ((res->count != 1) || (res->msgs[0]->num_elements > 1)) {
2315                 return ldb_operr(ldb);
2316         }
2317
2318         if (res->msgs[0]->num_elements == 1) {
2319                 /*
2320                  * Yes, we do have "servicePrincipalName"s. First we update them
2321                  * locally, that means we do always substitute the current
2322                  * "dNSHostName" with the new one and/or "sAMAccountName"
2323                  * without "$" with the new one and then we append the
2324                  * modified "servicePrincipalName"s as a message element
2325                  * replace to the modification request (Windows behaviour). We
2326                  * need also to make sure that the values remain case-
2327                  * insensitively unique.
2328                  */
2329
2330                 ret = ldb_msg_add_empty(ac->msg, "servicePrincipalName",
2331                                         LDB_FLAG_MOD_REPLACE, &el);
2332                 if (ret != LDB_SUCCESS) {
2333                         return ret;
2334                 }
2335
2336                 for (i = 0; i < res->msgs[0]->elements[0].num_values; i++) {
2337                         char *old_str, *new_str, *pos;
2338                         const char *tok;
2339                         struct ldb_val *vals;
2340                         bool found = false;
2341
2342                         old_str = (char *)
2343                                 res->msgs[0]->elements[0].values[i].data;
2344
2345                         new_str = talloc_strdup(ac->msg,
2346                                                 strtok_r(old_str, "/", &pos));
2347                         if (new_str == NULL) {
2348                                 return ldb_module_oom(ac->module);
2349                         }
2350
2351                         while ((tok = strtok_r(NULL, "/", &pos)) != NULL) {
2352                                 if ((dns_hostname != NULL) &&
2353                                     (strcasecmp_m(tok, old_dns_hostname) == 0)) {
2354                                         tok = dns_hostname;
2355                                 }
2356                                 if ((sam_accountname != NULL) &&
2357                                     (strcasecmp_m(tok, old_sam_accountname) == 0)) {
2358                                         tok = sam_accountname;
2359                                 }
2360
2361                                 new_str = talloc_asprintf(ac->msg, "%s/%s",
2362                                                           new_str, tok);
2363                                 if (new_str == NULL) {
2364                                         return ldb_module_oom(ac->module);
2365                                 }
2366                         }
2367
2368                         /* Uniqueness check */
2369                         for (j = 0; (!found) && (j < el->num_values); j++) {
2370                                 if (strcasecmp_m((char *)el->values[j].data,
2371                                                new_str) == 0) {
2372                                         found = true;
2373                                 }
2374                         }
2375                         if (found) {
2376                                 continue;
2377                         }
2378
2379                         /*
2380                          * append the new "servicePrincipalName" -
2381                          * code derived from ldb_msg_add_value().
2382                          *
2383                          * Open coded to make it clear that we must
2384                          * append to the MOD_REPLACE el created above.
2385                          */
2386                         vals = talloc_realloc(ac->msg, el->values,
2387                                               struct ldb_val,
2388                                               el->num_values + 1);
2389                         if (vals == NULL) {
2390                                 return ldb_module_oom(ac->module);
2391                         }
2392                         el->values = vals;
2393                         el->values[el->num_values] = data_blob_string_const(new_str);
2394                         ++(el->num_values);
2395                 }
2396         }
2397
2398         talloc_free(res);
2399
2400         return LDB_SUCCESS;
2401 }
2402
2403 /* This checks the "fSMORoleOwner" attributes */
2404 static int samldb_fsmo_role_owner_check(struct samldb_ctx *ac)
2405 {
2406         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2407         const char * const no_attrs[] = { NULL };
2408         struct ldb_message_element *el;
2409         struct ldb_message *tmp_msg;
2410         struct ldb_dn *res_dn;
2411         struct ldb_result *res;
2412         int ret;
2413
2414         el = dsdb_get_single_valued_attr(ac->msg, "fSMORoleOwner",
2415                                          ac->req->operation);
2416         if (el == NULL) {
2417                 /* we are not affected */
2418                 return LDB_SUCCESS;
2419         }
2420
2421         /* Create a temporary message for fetching the "fSMORoleOwner" */
2422         tmp_msg = ldb_msg_new(ac->msg);
2423         if (tmp_msg == NULL) {
2424                 return ldb_module_oom(ac->module);
2425         }
2426         ret = ldb_msg_add(tmp_msg, el, 0);
2427         if (ret != LDB_SUCCESS) {
2428                 return ret;
2429         }
2430         res_dn = ldb_msg_find_attr_as_dn(ldb, ac, tmp_msg, "fSMORoleOwner");
2431         talloc_free(tmp_msg);
2432
2433         if (res_dn == NULL) {
2434                 ldb_set_errstring(ldb,
2435                                   "samldb: 'fSMORoleOwner' attributes have to reference 'nTDSDSA' entries!");
2436                 if (ac->req->operation == LDB_ADD) {
2437                         return LDB_ERR_CONSTRAINT_VIOLATION;
2438                 } else {
2439                         return LDB_ERR_UNWILLING_TO_PERFORM;
2440                 }
2441         }
2442
2443         /* Fetched DN has to reference a "nTDSDSA" entry */
2444         ret = dsdb_module_search(ac->module, ac, &res, res_dn, LDB_SCOPE_BASE,
2445                                  no_attrs,
2446                                  DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED,
2447                                  ac->req, "(objectClass=nTDSDSA)");
2448         if (ret != LDB_SUCCESS) {
2449                 return ret;
2450         }
2451         if (res->count != 1) {
2452                 ldb_set_errstring(ldb,
2453                                   "samldb: 'fSMORoleOwner' attributes have to reference 'nTDSDSA' entries!");
2454                 return LDB_ERR_UNWILLING_TO_PERFORM;
2455         }
2456
2457         talloc_free(res);
2458
2459         return LDB_SUCCESS;
2460 }
2461
2462
2463 /* add */
2464 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
2465 {
2466         struct ldb_context *ldb;
2467         struct samldb_ctx *ac;
2468         struct ldb_message_element *el;
2469         int ret;
2470
2471         ldb = ldb_module_get_ctx(module);
2472         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
2473
2474         /* do not manipulate our control entries */
2475         if (ldb_dn_is_special(req->op.add.message->dn)) {
2476                 return ldb_next_request(module, req);
2477         }
2478
2479         el = ldb_msg_find_element(req->op.add.message, "userParameters");
2480         if (el != NULL && ldb_req_is_untrusted(req)) {
2481                 const char *reason = "samldb_add: "
2482                         "setting userParameters is not supported over LDAP, "
2483                         "see https://bugzilla.samba.org/show_bug.cgi?id=8077";
2484                 ldb_debug(ldb, LDB_DEBUG_WARNING, "%s", reason);
2485                 return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, reason);
2486         }
2487
2488         ac = samldb_ctx_init(module, req);
2489         if (ac == NULL) {
2490                 return ldb_operr(ldb);
2491         }
2492
2493         /* build the new msg */
2494         ac->msg = ldb_msg_copy_shallow(ac, req->op.add.message);
2495         if (ac->msg == NULL) {
2496                 talloc_free(ac);
2497                 ldb_debug(ldb, LDB_DEBUG_FATAL,
2498                           "samldb_add: ldb_msg_copy_shallow failed!\n");
2499                 return ldb_operr(ldb);
2500         }
2501
2502         el = ldb_msg_find_element(ac->msg, "fSMORoleOwner");
2503         if (el != NULL) {
2504                 ret = samldb_fsmo_role_owner_check(ac);
2505                 if (ret != LDB_SUCCESS) {
2506                         return ret;
2507                 }
2508         }
2509
2510         if (samdb_find_attribute(ldb, ac->msg,
2511                                  "objectclass", "user") != NULL) {
2512                 ac->type = SAMLDB_TYPE_USER;
2513
2514                 ret = samldb_prim_group_trigger(ac);
2515                 if (ret != LDB_SUCCESS) {
2516                         return ret;
2517                 }
2518
2519                 ret = samldb_objectclass_trigger(ac);
2520                 if (ret != LDB_SUCCESS) {
2521                         return ret;
2522                 }
2523
2524                 return samldb_fill_object(ac);
2525         }
2526
2527         if (samdb_find_attribute(ldb, ac->msg,
2528                                  "objectclass", "group") != NULL) {
2529                 ac->type = SAMLDB_TYPE_GROUP;
2530
2531                 ret = samldb_objectclass_trigger(ac);
2532                 if (ret != LDB_SUCCESS) {
2533                         return ret;
2534                 }
2535
2536                 return samldb_fill_object(ac);
2537         }
2538
2539         /* perhaps a foreignSecurityPrincipal? */
2540         if (samdb_find_attribute(ldb, ac->msg,
2541                                  "objectclass",
2542                                  "foreignSecurityPrincipal") != NULL) {
2543                 return samldb_fill_foreignSecurityPrincipal_object(ac);
2544         }
2545
2546         if (samdb_find_attribute(ldb, ac->msg,
2547                                  "objectclass", "classSchema") != NULL) {
2548                 ret = samldb_schema_info_update(ac);
2549                 if (ret != LDB_SUCCESS) {
2550                         talloc_free(ac);
2551                         return ret;
2552                 }
2553
2554                 ac->type = SAMLDB_TYPE_CLASS;
2555                 return samldb_fill_object(ac);
2556         }
2557
2558         if (samdb_find_attribute(ldb, ac->msg,
2559                                  "objectclass", "attributeSchema") != NULL) {
2560                 ret = samldb_schema_info_update(ac);
2561                 if (ret != LDB_SUCCESS) {
2562                         talloc_free(ac);
2563                         return ret;
2564                 }
2565
2566                 ac->type = SAMLDB_TYPE_ATTRIBUTE;
2567                 return samldb_fill_object(ac);
2568         }
2569
2570         talloc_free(ac);
2571
2572         /* nothing matched, go on */
2573         return ldb_next_request(module, req);
2574 }
2575
2576 /* modify */
2577 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
2578 {
2579         struct ldb_context *ldb;
2580         struct samldb_ctx *ac;
2581         struct ldb_message_element *el, *el2;
2582         bool modified = false;
2583         int ret;
2584
2585         if (ldb_dn_is_special(req->op.mod.message->dn)) {
2586                 /* do not manipulate our control entries */
2587                 return ldb_next_request(module, req);
2588         }
2589
2590         ldb = ldb_module_get_ctx(module);
2591
2592         /* make sure that "objectSid" is not specified */
2593         el = ldb_msg_find_element(req->op.mod.message, "objectSid");
2594         if (el != NULL) {
2595                 if (ldb_request_get_control(req, LDB_CONTROL_PROVISION_OID) == NULL) {
2596                         ldb_set_errstring(ldb,
2597                                           "samldb: objectSid must not be specified!");
2598                         return LDB_ERR_UNWILLING_TO_PERFORM;
2599                 }
2600         }
2601         /* make sure that "sAMAccountType" is not specified */
2602         el = ldb_msg_find_element(req->op.mod.message, "sAMAccountType");
2603         if (el != NULL) {
2604                 ldb_set_errstring(ldb,
2605                                   "samldb: sAMAccountType must not be specified!");
2606                 return LDB_ERR_UNWILLING_TO_PERFORM;
2607         }
2608         /* make sure that "isCriticalSystemObject" is not specified */
2609         el = ldb_msg_find_element(req->op.mod.message, "isCriticalSystemObject");
2610         if (el != NULL) {
2611                 if (ldb_request_get_control(req, LDB_CONTROL_RELAX_OID) == NULL) {
2612                         ldb_set_errstring(ldb,
2613                                           "samldb: isCriticalSystemObject must not be specified!");
2614                         return LDB_ERR_UNWILLING_TO_PERFORM;
2615                 }
2616         }
2617
2618         /* msDS-IntId is not allowed to be modified
2619          * except when modification comes from replication */
2620         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
2621                 if (!ldb_request_get_control(req,
2622                                              DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
2623                         return LDB_ERR_CONSTRAINT_VIOLATION;
2624                 }
2625         }
2626
2627         el = ldb_msg_find_element(req->op.mod.message, "userParameters");
2628         if (el != NULL && ldb_req_is_untrusted(req)) {
2629                 const char *reason = "samldb: "
2630                         "setting userParameters is not supported over LDAP, "
2631                         "see https://bugzilla.samba.org/show_bug.cgi?id=8077";
2632                 ldb_debug(ldb, LDB_DEBUG_WARNING, "%s", reason);
2633                 return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, reason);
2634         }
2635
2636         ac = samldb_ctx_init(module, req);
2637         if (ac == NULL) {
2638                 return ldb_operr(ldb);
2639         }
2640
2641         /* build the new msg */
2642         ac->msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
2643         if (ac->msg == NULL) {
2644                 talloc_free(ac);
2645                 ldb_debug(ldb, LDB_DEBUG_FATAL,
2646                           "samldb_modify: ldb_msg_copy_shallow failed!\n");
2647                 return ldb_operr(ldb);
2648         }
2649
2650         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
2651         if (el != NULL) {
2652                 ret = samldb_prim_group_trigger(ac);
2653                 if (ret != LDB_SUCCESS) {
2654                         return ret;
2655                 }
2656         }
2657
2658         el = ldb_msg_find_element(ac->msg, "userAccountControl");
2659         if (el != NULL) {
2660                 modified = true;
2661                 ret = samldb_user_account_control_change(ac);
2662                 if (ret != LDB_SUCCESS) {
2663                         return ret;
2664                 }
2665         }
2666
2667         el = ldb_msg_find_element(ac->msg, "groupType");
2668         if (el != NULL) {
2669                 modified = true;
2670                 ret = samldb_group_type_change(ac);
2671                 if (ret != LDB_SUCCESS) {
2672                         return ret;
2673                 }
2674         }
2675
2676         el = ldb_msg_find_element(ac->msg, "sAMAccountName");
2677         if (el != NULL) {
2678                 ret = samldb_sam_accountname_check(ac);
2679                 if (ret != LDB_SUCCESS) {
2680                         return ret;
2681                 }
2682         }
2683
2684         el = ldb_msg_find_element(ac->msg, "member");
2685         if (el != NULL) {
2686                 ret = samldb_member_check(ac);
2687                 if (ret != LDB_SUCCESS) {
2688                         return ret;
2689                 }
2690         }
2691
2692         el = ldb_msg_find_element(ac->msg, "description");
2693         if (el != NULL) {
2694                 ret = samldb_description_check(ac, &modified);
2695                 if (ret != LDB_SUCCESS) {
2696                         return ret;
2697                 }
2698         }
2699
2700         el = ldb_msg_find_element(ac->msg, "dNSHostName");
2701         el2 = ldb_msg_find_element(ac->msg, "sAMAccountName");
2702         if ((el != NULL) || (el2 != NULL)) {
2703                 modified = true;
2704                 ret = samldb_service_principal_names_change(ac);
2705                 if (ret != LDB_SUCCESS) {
2706                         return ret;
2707                 }
2708         }
2709
2710         el = ldb_msg_find_element(ac->msg, "fSMORoleOwner");
2711         if (el != NULL) {
2712                 ret = samldb_fsmo_role_owner_check(ac);
2713                 if (ret != LDB_SUCCESS) {
2714                         return ret;
2715                 }
2716         }
2717
2718         if (modified) {
2719                 struct ldb_request *child_req;
2720
2721                 /* Now perform the real modifications as a child request */
2722                 ret = ldb_build_mod_req(&child_req, ldb, ac,
2723                                         ac->msg,
2724                                         req->controls,
2725                                         req, dsdb_next_callback,
2726                                         req);
2727                 LDB_REQ_SET_LOCATION(child_req);
2728                 if (ret != LDB_SUCCESS) {
2729                         return ret;
2730                 }
2731
2732                 return ldb_next_request(module, child_req);
2733         }
2734
2735         talloc_free(ac);
2736
2737         /* no change which interests us, go on */
2738         return ldb_next_request(module, req);
2739 }
2740
2741 /* delete */
2742
2743 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
2744 {
2745         struct ldb_context *ldb;
2746         struct dom_sid *sid;
2747         uint32_t rid;
2748         NTSTATUS status;
2749         int ret;
2750         struct ldb_result *res;
2751         const char * const attrs[] = { "objectSid", "isDeleted", NULL };
2752         const char * const noattrs[] = { NULL };
2753
2754         ldb = ldb_module_get_ctx(ac->module);
2755
2756         /* Finds out the SID/RID of the SAM object */
2757         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->req->op.del.dn,
2758                                         attrs,
2759                                         DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED,
2760                                         ac->req);
2761         if (ret != LDB_SUCCESS) {
2762                 return ret;
2763         }
2764
2765         if (ldb_msg_check_string_attribute(res->msgs[0], "isDeleted", "TRUE")) {
2766                 return LDB_SUCCESS;
2767         }
2768
2769         sid = samdb_result_dom_sid(ac, res->msgs[0], "objectSid");
2770         if (sid == NULL) {
2771                 /* No SID - it might not be a SAM object - therefore ok */
2772                 return LDB_SUCCESS;
2773         }
2774         status = dom_sid_split_rid(ac, sid, NULL, &rid);
2775         if (!NT_STATUS_IS_OK(status)) {
2776                 return ldb_operr(ldb);
2777         }
2778         if (rid == 0) {
2779                 /* Special object (security principal?) */
2780                 return LDB_SUCCESS;
2781         }
2782         /* do not allow deletion of well-known sids */
2783         if (rid < DSDB_SAMDB_MINIMUM_ALLOWED_RID &&
2784             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
2785                 return LDB_ERR_OTHER;
2786         }
2787
2788         /* Deny delete requests from groups which are primary ones */
2789         ret = dsdb_module_search(ac->module, ac, &res,
2790                                  ldb_get_default_basedn(ldb),
2791                                  LDB_SCOPE_SUBTREE, noattrs,
2792                                  DSDB_FLAG_NEXT_MODULE,
2793                                  ac->req,
2794                                  "(&(primaryGroupID=%u)(objectClass=user))", rid);
2795         if (ret != LDB_SUCCESS) {
2796                 return ret;
2797         }
2798         if (res->count > 0) {
2799                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
2800         }
2801
2802         return LDB_SUCCESS;
2803 }
2804
2805 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
2806 {
2807         struct samldb_ctx *ac;
2808         int ret;
2809
2810         if (ldb_dn_is_special(req->op.del.dn)) {
2811                 /* do not manipulate our control entries */
2812                 return ldb_next_request(module, req);
2813         }
2814
2815         ac = samldb_ctx_init(module, req);
2816         if (ac == NULL) {
2817                 return ldb_operr(ldb_module_get_ctx(module));
2818         }
2819
2820         ret = samldb_prim_group_users_check(ac);
2821         if (ret != LDB_SUCCESS) {
2822                 return ret;
2823         }
2824
2825         talloc_free(ac);
2826
2827         return ldb_next_request(module, req);
2828 }
2829
2830 /* rename */
2831
2832 static int check_rename_constraints(struct ldb_message *msg,
2833                                     struct samldb_ctx *ac,
2834                                     struct ldb_dn *olddn, struct ldb_dn *newdn)
2835 {
2836         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2837         struct ldb_dn *dn1, *dn2, *nc_root;
2838         int32_t systemFlags;
2839         bool move_op = false;
2840         bool rename_op = false;
2841         int ret;
2842
2843         /* Skip the checks if old and new DN are the same, or if we have the
2844          * relax control specified or if the returned objects is already
2845          * deleted and needs only to be moved for consistency. */
2846
2847         if (ldb_dn_compare(olddn, newdn) == 0) {
2848                 return LDB_SUCCESS;
2849         }
2850         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) != NULL) {
2851                 return LDB_SUCCESS;
2852         }
2853         if (ldb_msg_find_attr_as_bool(msg, "isDeleted", false)) {
2854                 return LDB_SUCCESS;
2855         }
2856
2857         /* Objects under CN=System */
2858
2859         dn1 = ldb_dn_copy(ac, ldb_get_default_basedn(ldb));
2860         if (dn1 == NULL) return ldb_oom(ldb);
2861
2862         if ( ! ldb_dn_add_child_fmt(dn1, "CN=System")) {
2863                 talloc_free(dn1);
2864                 return LDB_ERR_OPERATIONS_ERROR;
2865         }
2866
2867         if ((ldb_dn_compare_base(dn1, olddn) == 0) &&
2868             (ldb_dn_compare_base(dn1, newdn) != 0)) {
2869                 talloc_free(dn1);
2870                 ldb_asprintf_errstring(ldb,
2871                                        "subtree_rename: Cannot move/rename %s. Objects under CN=System have to stay under it!",
2872                                        ldb_dn_get_linearized(olddn));
2873                 return LDB_ERR_OTHER;
2874         }
2875
2876         talloc_free(dn1);
2877
2878         /* LSA objects */
2879
2880         if ((samdb_find_attribute(ldb, msg, "objectClass", "secret") != NULL) ||
2881             (samdb_find_attribute(ldb, msg, "objectClass", "trustedDomain") != NULL)) {
2882                 ldb_asprintf_errstring(ldb,
2883                                        "subtree_rename: Cannot move/rename %s. It's an LSA-specific object!",
2884                                        ldb_dn_get_linearized(olddn));
2885                 return LDB_ERR_UNWILLING_TO_PERFORM;
2886         }
2887
2888         /* systemFlags */
2889
2890         dn1 = ldb_dn_get_parent(ac, olddn);
2891         if (dn1 == NULL) return ldb_oom(ldb);
2892         dn2 = ldb_dn_get_parent(ac, newdn);
2893         if (dn2 == NULL) return ldb_oom(ldb);
2894
2895         if (ldb_dn_compare(dn1, dn2) == 0) {
2896                 rename_op = true;
2897         } else {
2898                 move_op = true;
2899         }
2900
2901         talloc_free(dn1);
2902         talloc_free(dn2);
2903
2904         systemFlags = ldb_msg_find_attr_as_int(msg, "systemFlags", 0);
2905
2906         /* Fetch name context */
2907
2908         ret = dsdb_find_nc_root(ldb, ac, olddn, &nc_root);
2909         if (ret != LDB_SUCCESS) {
2910                 return ret;
2911         }
2912
2913         if (ldb_dn_compare(nc_root, ldb_get_schema_basedn(ldb)) == 0) {
2914                 if (move_op) {
2915                         ldb_asprintf_errstring(ldb,
2916                                                "subtree_rename: Cannot move %s within schema partition",
2917                                                ldb_dn_get_linearized(olddn));
2918                         return LDB_ERR_UNWILLING_TO_PERFORM;
2919                 }
2920                 if (rename_op &&
2921                     (systemFlags & SYSTEM_FLAG_SCHEMA_BASE_OBJECT) != 0) {
2922                         ldb_asprintf_errstring(ldb,
2923                                                "subtree_rename: Cannot rename %s within schema partition",
2924                                                ldb_dn_get_linearized(olddn));
2925                         return LDB_ERR_UNWILLING_TO_PERFORM;
2926                 }
2927         } else if (ldb_dn_compare(nc_root, ldb_get_config_basedn(ldb)) == 0) {
2928                 if (move_op &&
2929                     (systemFlags & SYSTEM_FLAG_CONFIG_ALLOW_MOVE) == 0) {
2930                         /* Here we have to do more: control the
2931                          * "ALLOW_LIMITED_MOVE" flag. This means that the
2932                          * grand-grand-parents of two objects have to be equal
2933                          * in order to perform the move (this is used for
2934                          * moving "server" objects in the "sites" container). */
2935                         bool limited_move =
2936                                 systemFlags & SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE;
2937
2938                         if (limited_move) {
2939                                 dn1 = ldb_dn_copy(ac, olddn);
2940                                 if (dn1 == NULL) return ldb_oom(ldb);
2941                                 dn2 = ldb_dn_copy(ac, newdn);
2942                                 if (dn2 == NULL) return ldb_oom(ldb);
2943
2944                                 limited_move &= ldb_dn_remove_child_components(dn1, 3);
2945                                 limited_move &= ldb_dn_remove_child_components(dn2, 3);
2946                                 limited_move &= ldb_dn_compare(dn1, dn2) == 0;
2947
2948                                 talloc_free(dn1);
2949                                 talloc_free(dn2);
2950                         }
2951
2952                         if (!limited_move) {
2953                                 ldb_asprintf_errstring(ldb,
2954                                                        "subtree_rename: Cannot move %s to %s in config partition",
2955                                                        ldb_dn_get_linearized(olddn), ldb_dn_get_linearized(newdn));
2956                                 return LDB_ERR_UNWILLING_TO_PERFORM;
2957                         }
2958                 }
2959                 if (rename_op &&
2960                     (systemFlags & SYSTEM_FLAG_CONFIG_ALLOW_RENAME) == 0) {
2961                         ldb_asprintf_errstring(ldb,
2962                                                "subtree_rename: Cannot rename %s to %s within config partition",
2963                                                ldb_dn_get_linearized(olddn), ldb_dn_get_linearized(newdn));
2964                         return LDB_ERR_UNWILLING_TO_PERFORM;
2965                 }
2966         } else if (ldb_dn_compare(nc_root, ldb_get_default_basedn(ldb)) == 0) {
2967                 if (move_op &&
2968                     (systemFlags & SYSTEM_FLAG_DOMAIN_DISALLOW_MOVE) != 0) {
2969                         ldb_asprintf_errstring(ldb,
2970                                                "subtree_rename: Cannot move %s to %s - DISALLOW_MOVE set",
2971                                                ldb_dn_get_linearized(olddn), ldb_dn_get_linearized(newdn));
2972                         return LDB_ERR_UNWILLING_TO_PERFORM;
2973                 }
2974                 if (rename_op &&
2975                     (systemFlags & SYSTEM_FLAG_DOMAIN_DISALLOW_RENAME) != 0) {
2976                         ldb_asprintf_errstring(ldb,
2977                                                        "subtree_rename: Cannot rename %s to %s - DISALLOW_RENAME set",
2978                                                ldb_dn_get_linearized(olddn), ldb_dn_get_linearized(newdn));
2979                         return LDB_ERR_UNWILLING_TO_PERFORM;
2980                 }
2981         }
2982
2983         talloc_free(nc_root);
2984
2985         return LDB_SUCCESS;
2986 }
2987
2988
2989 static int samldb_rename_search_base_callback(struct ldb_request *req,
2990                                                struct ldb_reply *ares)
2991 {
2992         struct samldb_ctx *ac;
2993         int ret;
2994
2995         ac = talloc_get_type(req->context, struct samldb_ctx);
2996
2997         if (!ares) {
2998                 return ldb_module_done(ac->req, NULL, NULL,
2999                                         LDB_ERR_OPERATIONS_ERROR);
3000         }
3001         if (ares->error != LDB_SUCCESS) {
3002                 return ldb_module_done(ac->req, ares->controls,
3003                                         ares->response, ares->error);
3004         }
3005
3006         switch (ares->type) {
3007         case LDB_REPLY_ENTRY:
3008                 /*
3009                  * This is the root entry of the originating move
3010                  * respectively rename request. It has been already
3011                  * stored in the list using "subtree_rename_search()".
3012                  * Only this one is subject to constraint checking.
3013                  */
3014                 ret = check_rename_constraints(ares->message, ac,
3015                                                ac->req->op.rename.olddn,
3016                                                ac->req->op.rename.newdn);
3017                 if (ret != LDB_SUCCESS) {
3018                         return ldb_module_done(ac->req, NULL, NULL,
3019                                                ret);
3020                 }
3021                 break;
3022
3023         case LDB_REPLY_REFERRAL:
3024                 /* ignore */
3025                 break;
3026
3027         case LDB_REPLY_DONE:
3028
3029                 /*
3030                  * Great, no problem with the rename, so go ahead as
3031                  * if we never were here
3032                  */
3033                 ret = ldb_next_request(ac->module, ac->req);
3034                 talloc_free(ares);
3035                 return ret;
3036         }
3037
3038         talloc_free(ares);
3039         return LDB_SUCCESS;
3040 }
3041
3042
3043 /* rename */
3044 static int samldb_rename(struct ldb_module *module, struct ldb_request *req)
3045 {
3046         struct ldb_context *ldb;
3047         static const char * const attrs[] = { "objectClass", "systemFlags",
3048                                               "isDeleted", NULL };
3049         struct ldb_request *search_req;
3050         struct samldb_ctx *ac;
3051         int ret;
3052
3053         if (ldb_dn_is_special(req->op.rename.olddn)) { /* do not manipulate our control entries */
3054                 return ldb_next_request(module, req);
3055         }
3056
3057         ldb = ldb_module_get_ctx(module);
3058
3059         ac = samldb_ctx_init(module, req);
3060         if (!ac) {
3061                 return ldb_oom(ldb);
3062         }
3063
3064         ret = ldb_build_search_req(&search_req, ldb, ac,
3065                                    req->op.rename.olddn,
3066                                    LDB_SCOPE_BASE,
3067                                    "(objectClass=*)",
3068                                    attrs,
3069                                    NULL,
3070                                    ac,
3071                                    samldb_rename_search_base_callback,
3072                                    req);
3073         LDB_REQ_SET_LOCATION(search_req);
3074         if (ret != LDB_SUCCESS) {
3075                 return ret;
3076         }
3077
3078         ret = ldb_request_add_control(search_req, LDB_CONTROL_SHOW_RECYCLED_OID,
3079                                       true, NULL);
3080         if (ret != LDB_SUCCESS) {
3081                 return ret;
3082         }
3083
3084         return ldb_next_request(ac->module, search_req);
3085 }
3086
3087 /* extended */
3088
3089 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
3090 {
3091         struct ldb_context *ldb = ldb_module_get_ctx(module);
3092         struct dsdb_fsmo_extended_op *exop;
3093         int ret;
3094
3095         exop = talloc_get_type(req->op.extended.data,
3096                                struct dsdb_fsmo_extended_op);
3097         if (!exop) {
3098                 ldb_set_errstring(ldb,
3099                                   "samldb_extended_allocate_rid_pool: invalid extended data");
3100                 return LDB_ERR_PROTOCOL_ERROR;
3101         }
3102
3103         ret = ridalloc_allocate_rid_pool_fsmo(module, exop, req);
3104         if (ret != LDB_SUCCESS) {
3105                 return ret;
3106         }
3107
3108         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
3109 }
3110
3111 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
3112 {
3113         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
3114                 return samldb_extended_allocate_rid_pool(module, req);
3115         }
3116
3117         return ldb_next_request(module, req);
3118 }
3119
3120
3121 static const struct ldb_module_ops ldb_samldb_module_ops = {
3122         .name          = "samldb",
3123         .add           = samldb_add,
3124         .modify        = samldb_modify,
3125         .del           = samldb_delete,
3126         .rename        = samldb_rename,
3127         .extended      = samldb_extended
3128 };
3129
3130
3131 int ldb_samldb_module_init(const char *version)
3132 {
3133         LDB_MODULE_CHECK_VERSION(version);
3134         return ldb_register_module(&ldb_samldb_module_ops);
3135 }