dsdb-samldb: Only allow known and settable userAccountControl bits to be set
[kai/samba-autobuild/.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_rules(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 or missing one of the types means "UF_NORMAL_ACCOUNT" */
1052                         if ((user_account_control & UF_ACCOUNT_TYPE_MASK) == 0) {
1053                                 user_account_control = UF_NORMAL_ACCOUNT | user_account_control;
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                         ret = samldb_check_user_account_control_rules(ac, NULL,
1070                                                                       user_account_control, 0);
1071                         if (ret != LDB_SUCCESS) {
1072                                 return ret;
1073                         }
1074
1075                         /* Workstation and (read-only) DC objects do need objectclass "computer" */
1076                         if ((samdb_find_attribute(ldb, ac->msg,
1077                                                   "objectclass", "computer") == NULL) &&
1078                             (user_account_control &
1079                              (UF_SERVER_TRUST_ACCOUNT | UF_WORKSTATION_TRUST_ACCOUNT))) {
1080                                 ldb_set_errstring(ldb,
1081                                                   "samldb: Requested account type does need objectclass 'computer'!");
1082                                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1083                         }
1084
1085                         account_type = ds_uf2atype(user_account_control);
1086                         if (account_type == 0) {
1087                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1088                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1089                         }
1090                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1091                                                  "sAMAccountType",
1092                                                  account_type);
1093                         if (ret != LDB_SUCCESS) {
1094                                 return ret;
1095                         }
1096                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
1097                         el2->flags = LDB_FLAG_MOD_REPLACE;
1098
1099                         /* "isCriticalSystemObject" might be set */
1100                         if (user_account_control &
1101                             (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1102                                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1103                                                          "TRUE");
1104                                 if (ret != LDB_SUCCESS) {
1105                                         return ret;
1106                                 }
1107                                 el2 = ldb_msg_find_element(ac->msg,
1108                                                            "isCriticalSystemObject");
1109                                 el2->flags = LDB_FLAG_MOD_REPLACE;
1110                         } else if (user_account_control & UF_WORKSTATION_TRUST_ACCOUNT) {
1111                                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1112                                                          "FALSE");
1113                                 if (ret != LDB_SUCCESS) {
1114                                         return ret;
1115                                 }
1116                                 el2 = ldb_msg_find_element(ac->msg,
1117                                                            "isCriticalSystemObject");
1118                                 el2->flags = LDB_FLAG_MOD_REPLACE;
1119                         }
1120
1121                         /* Step 1.4: "userAccountControl" -> "primaryGroupID" mapping */
1122                         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
1123                                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
1124
1125                                 /*
1126                                  * Older AD deployments don't know about the
1127                                  * RODC group
1128                                  */
1129                                 if (rid == DOMAIN_RID_READONLY_DCS) {
1130                                         ret = samldb_prim_group_tester(ac, rid);
1131                                         if (ret != LDB_SUCCESS) {
1132                                                 return ret;
1133                                         }
1134                                 }
1135
1136                                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1137                                                          "primaryGroupID", rid);
1138                                 if (ret != LDB_SUCCESS) {
1139                                         return ret;
1140                                 }
1141                                 el2 = ldb_msg_find_element(ac->msg,
1142                                                            "primaryGroupID");
1143                                 el2->flags = LDB_FLAG_MOD_REPLACE;
1144                         }
1145
1146                         /* Step 1.5: Add additional flags when needed */
1147                         /* Obviously this is done when the "userAccountControl"
1148                          * has been generated here (tested against Windows
1149                          * Server) */
1150                         if (uac_generated) {
1151                                 if (uac_add_flags) {
1152                                         user_account_control |= UF_ACCOUNTDISABLE;
1153                                         user_account_control |= UF_PASSWD_NOTREQD;
1154                                 }
1155
1156                                 ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
1157                                                          "userAccountControl",
1158                                                          user_account_control);
1159                                 if (ret != LDB_SUCCESS) {
1160                                         return ret;
1161                                 }
1162                         }
1163
1164                 }
1165                 break;
1166         }
1167
1168         case SAMLDB_TYPE_GROUP: {
1169                 const char *tempstr;
1170
1171                 /* Step 2.2: Default values */
1172                 tempstr = talloc_asprintf(ac->msg, "%d",
1173                                           GTYPE_SECURITY_GLOBAL_GROUP);
1174                 if (tempstr == NULL) return ldb_operr(ldb);
1175                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
1176                         "groupType", tempstr);
1177                 if (ret != LDB_SUCCESS) return ret;
1178
1179                 /* Step 2.3: "groupType" -> "sAMAccountType" */
1180                 el = ldb_msg_find_element(ac->msg, "groupType");
1181                 if (el != NULL) {
1182                         uint32_t group_type, account_type;
1183
1184                         group_type = ldb_msg_find_attr_as_uint(ac->msg,
1185                                                                "groupType", 0);
1186
1187                         /* The creation of builtin groups requires the
1188                          * RELAX control */
1189                         if (group_type == GTYPE_SECURITY_BUILTIN_LOCAL_GROUP) {
1190                                 if (ldb_request_get_control(ac->req,
1191                                                             LDB_CONTROL_RELAX_OID) == NULL) {
1192                                         return LDB_ERR_UNWILLING_TO_PERFORM;
1193                                 }
1194                         }
1195
1196                         account_type = ds_gtype2atype(group_type);
1197                         if (account_type == 0) {
1198                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1199                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1200                         }
1201                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1202                                                  "sAMAccountType",
1203                                                  account_type);
1204                         if (ret != LDB_SUCCESS) {
1205                                 return ret;
1206                         }
1207                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
1208                         el2->flags = LDB_FLAG_MOD_REPLACE;
1209                 }
1210                 break;
1211         }
1212
1213         default:
1214                 ldb_asprintf_errstring(ldb,
1215                                 "Invalid entry type!");
1216                 return LDB_ERR_OPERATIONS_ERROR;
1217                 break;
1218         }
1219
1220         return LDB_SUCCESS;
1221 }
1222
1223 /*
1224  * "Primary group ID" trigger (MS-SAMR 3.1.1.8.2)
1225  *
1226  * Has to be invoked on "add" and "modify" operations on "user" and "computer"
1227  * objects.
1228  * ac->msg contains the "add"/"modify" message
1229  */
1230
1231 static int samldb_prim_group_tester(struct samldb_ctx *ac, uint32_t rid)
1232 {
1233         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1234         struct dom_sid *sid;
1235         struct ldb_result *res;
1236         int ret;
1237         const char * const noattrs[] = { NULL };
1238
1239         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1240         if (sid == NULL) {
1241                 return ldb_operr(ldb);
1242         }
1243
1244         ret = dsdb_module_search(ac->module, ac, &res,
1245                                  ldb_get_default_basedn(ldb),
1246                                  LDB_SCOPE_SUBTREE,
1247                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1248                                  ac->req,
1249                                  "(objectSid=%s)",
1250                                  ldap_encode_ndr_dom_sid(ac, sid));
1251         if (ret != LDB_SUCCESS) {
1252                 return ret;
1253         }
1254         if (res->count != 1) {
1255                 talloc_free(res);
1256                 ldb_asprintf_errstring(ldb,
1257                                        "Failed to find primary group with RID %u!",
1258                                        rid);
1259                 return LDB_ERR_UNWILLING_TO_PERFORM;
1260         }
1261         talloc_free(res);
1262
1263         return LDB_SUCCESS;
1264 }
1265
1266 static int samldb_prim_group_set(struct samldb_ctx *ac)
1267 {
1268         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1269         uint32_t rid;
1270
1271         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1272         if (rid == (uint32_t) -1) {
1273                 /* we aren't affected of any primary group set */
1274                 return LDB_SUCCESS;
1275
1276         } else if (!ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
1277                 ldb_set_errstring(ldb,
1278                                   "The primary group isn't settable on add operations!");
1279                 return LDB_ERR_UNWILLING_TO_PERFORM;
1280         }
1281
1282         return samldb_prim_group_tester(ac, rid);
1283 }
1284
1285 static int samldb_prim_group_change(struct samldb_ctx *ac)
1286 {
1287         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1288         const char * const attrs[] = {
1289                 "primaryGroupID",
1290                 "memberOf",
1291                 "userAccountControl",
1292                 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, uac;
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         uac = ldb_msg_find_attr_as_uint(res->msgs[0], "userAccountControl", 0);
1318
1319         /* Finds out the DN of the old primary group */
1320
1321         prev_rid = ldb_msg_find_attr_as_uint(res->msgs[0], "primaryGroupID",
1322                                              (uint32_t) -1);
1323         if (prev_rid == (uint32_t) -1) {
1324                 /* User objects do always have a mandatory "primaryGroupID"
1325                  * attribute. If this doesn't exist then the object is of the
1326                  * wrong type. This is the exact Windows error code */
1327                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1328         }
1329
1330         prev_sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), prev_rid);
1331         if (prev_sid == NULL) {
1332                 return ldb_operr(ldb);
1333         }
1334
1335         /* Finds out the DN of the new primary group
1336          * Notice: in order to parse the primary group ID correctly we create
1337          * a temporary message here. */
1338
1339         msg = ldb_msg_new(ac->msg);
1340         if (msg == NULL) {
1341                 return ldb_module_oom(ac->module);
1342         }
1343         ret = ldb_msg_add(msg, el, 0);
1344         if (ret != LDB_SUCCESS) {
1345                 return ret;
1346         }
1347         new_rid = ldb_msg_find_attr_as_uint(msg, "primaryGroupID", (uint32_t) -1);
1348         talloc_free(msg);
1349         if (new_rid == (uint32_t) -1) {
1350                 /* we aren't affected of any primary group change */
1351                 return LDB_SUCCESS;
1352         }
1353
1354         if (prev_rid == new_rid) {
1355                 return LDB_SUCCESS;
1356         }
1357
1358         if ((uac & UF_SERVER_TRUST_ACCOUNT) && new_rid != DOMAIN_RID_DCS) {
1359                 ldb_asprintf_errstring(ldb,
1360                         "%08X: samldb: UF_SERVER_TRUST_ACCOUNT requires "
1361                         "primaryGroupID=%u!",
1362                         W_ERROR_V(WERR_DS_CANT_MOD_PRIMARYGROUPID),
1363                         DOMAIN_RID_DCS);
1364                 return LDB_ERR_UNWILLING_TO_PERFORM;
1365         }
1366
1367         if ((uac & UF_PARTIAL_SECRETS_ACCOUNT) && new_rid != DOMAIN_RID_READONLY_DCS) {
1368                 ldb_asprintf_errstring(ldb,
1369                         "%08X: samldb: UF_PARTIAL_SECRETS_ACCOUNT requires "
1370                         "primaryGroupID=%u!",
1371                         W_ERROR_V(WERR_DS_CANT_MOD_PRIMARYGROUPID),
1372                         DOMAIN_RID_READONLY_DCS);
1373                 return LDB_ERR_UNWILLING_TO_PERFORM;
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, prev_sid));
1383         if (ret != LDB_SUCCESS) {
1384                 return ret;
1385         }
1386         if (group_res->count != 1) {
1387                 return ldb_operr(ldb);
1388         }
1389         prev_prim_group_dn = group_res->msgs[0]->dn;
1390
1391         new_sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), new_rid);
1392         if (new_sid == NULL) {
1393                 return ldb_operr(ldb);
1394         }
1395
1396         ret = dsdb_module_search(ac->module, ac, &group_res,
1397                                  ldb_get_default_basedn(ldb),
1398                                  LDB_SCOPE_SUBTREE,
1399                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1400                                  ac->req,
1401                                  "(objectSid=%s)",
1402                                  ldap_encode_ndr_dom_sid(ac, new_sid));
1403         if (ret != LDB_SUCCESS) {
1404                 return ret;
1405         }
1406         if (group_res->count != 1) {
1407                 /* Here we know if the specified new primary group candidate is
1408                  * valid or not. */
1409                 return LDB_ERR_UNWILLING_TO_PERFORM;
1410         }
1411         new_prim_group_dn = group_res->msgs[0]->dn;
1412
1413         /* We need to be already a normal member of the new primary
1414          * group in order to be successful. */
1415         el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1416                                   ldb_dn_get_linearized(new_prim_group_dn));
1417         if (el == NULL) {
1418                 return LDB_ERR_UNWILLING_TO_PERFORM;
1419         }
1420
1421         /* Remove the "member" attribute on the new primary group */
1422         msg = ldb_msg_new(ac->msg);
1423         if (msg == NULL) {
1424                 return ldb_module_oom(ac->module);
1425         }
1426         msg->dn = new_prim_group_dn;
1427
1428         ret = samdb_msg_add_delval(ldb, msg, msg, "member",
1429                                    ldb_dn_get_linearized(ac->msg->dn));
1430         if (ret != LDB_SUCCESS) {
1431                 return ret;
1432         }
1433
1434         ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE, ac->req);
1435         if (ret != LDB_SUCCESS) {
1436                 return ret;
1437         }
1438         talloc_free(msg);
1439
1440         /* Add a "member" attribute for the previous primary group */
1441         msg = ldb_msg_new(ac->msg);
1442         if (msg == NULL) {
1443                 return ldb_module_oom(ac->module);
1444         }
1445         msg->dn = prev_prim_group_dn;
1446
1447         ret = samdb_msg_add_addval(ldb, msg, msg, "member",
1448                                    ldb_dn_get_linearized(ac->msg->dn));
1449         if (ret != LDB_SUCCESS) {
1450                 return ret;
1451         }
1452
1453         ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE, ac->req);
1454         if (ret != LDB_SUCCESS) {
1455                 return ret;
1456         }
1457         talloc_free(msg);
1458
1459         return LDB_SUCCESS;
1460 }
1461
1462 static int samldb_prim_group_trigger(struct samldb_ctx *ac)
1463 {
1464         int ret;
1465
1466         if (ac->req->operation == LDB_ADD) {
1467                 ret = samldb_prim_group_set(ac);
1468         } else {
1469                 ret = samldb_prim_group_change(ac);
1470         }
1471
1472         return ret;
1473 }
1474
1475 static int samldb_check_user_account_control_invariants(struct samldb_ctx *ac,
1476                                                     uint32_t user_account_control)
1477 {
1478         int i, ret = 0;
1479         bool need_check = false;
1480         const struct uac_to_guid {
1481                 uint32_t uac;
1482                 bool never;
1483                 uint32_t needs;
1484                 uint32_t not_with;
1485                 const char *error_string;
1486         } map[] = {
1487                 {
1488                         .uac = UF_TEMP_DUPLICATE_ACCOUNT,
1489                         .never = true,
1490                         .error_string = "Updating the UF_TEMP_DUPLICATE_ACCOUNT flag is never allowed"
1491                 },
1492                 {
1493                         .uac = UF_PARTIAL_SECRETS_ACCOUNT,
1494                         .needs = UF_WORKSTATION_TRUST_ACCOUNT,
1495                         .error_string = "Setting UF_PARTIAL_SECRETS_ACCOUNT only permitted with UF_WORKSTATION_TRUST_ACCOUNT"
1496                 },
1497                 {
1498                         .uac = UF_TRUSTED_FOR_DELEGATION,
1499                         .not_with = UF_PARTIAL_SECRETS_ACCOUNT,
1500                         .error_string = "Setting UF_TRUSTED_FOR_DELEGATION not allowed with UF_PARTIAL_SECRETS_ACCOUNT"
1501                 },
1502                 {
1503                         .uac = UF_NORMAL_ACCOUNT,
1504                         .not_with = UF_ACCOUNT_TYPE_MASK & ~UF_NORMAL_ACCOUNT,
1505                         .error_string = "Setting more than one account type not permitted"
1506                 },
1507                 {
1508                         .uac = UF_WORKSTATION_TRUST_ACCOUNT,
1509                         .not_with = UF_ACCOUNT_TYPE_MASK & ~UF_WORKSTATION_TRUST_ACCOUNT,
1510                         .error_string = "Setting more than one account type not permitted"
1511                 },
1512                 {
1513                         .uac = UF_INTERDOMAIN_TRUST_ACCOUNT,
1514                         .not_with = UF_ACCOUNT_TYPE_MASK & ~UF_INTERDOMAIN_TRUST_ACCOUNT,
1515                         .error_string = "Setting more than one account type not permitted"
1516                 },
1517                 {
1518                         .uac = UF_SERVER_TRUST_ACCOUNT,
1519                         .not_with = UF_ACCOUNT_TYPE_MASK & ~UF_SERVER_TRUST_ACCOUNT,
1520                         .error_string = "Setting more than one account type not permitted"
1521                 },
1522                 {
1523                         .uac = UF_TRUSTED_FOR_DELEGATION,
1524                         .not_with = UF_PARTIAL_SECRETS_ACCOUNT,
1525                         .error_string = "Setting UF_TRUSTED_FOR_DELEGATION not allowed with UF_PARTIAL_SECRETS_ACCOUNT"
1526                 }
1527         };
1528
1529         for (i = 0; i < ARRAY_SIZE(map); i++) {
1530                 if (user_account_control & map[i].uac) {
1531                         need_check = true;
1532                         break;
1533                 }
1534         }
1535         if (need_check == false) {
1536                 return LDB_SUCCESS;
1537         }
1538
1539         for (i = 0; i < ARRAY_SIZE(map); i++) {
1540                 uint32_t this_uac = user_account_control & map[i].uac;
1541                 if (this_uac != 0) {
1542                         if (map[i].never) {
1543                                 ret = LDB_ERR_OTHER;
1544                                 break;
1545                         } else if (map[i].needs != 0) {
1546                                 if ((map[i].needs & user_account_control) == 0) {
1547                                         ret = LDB_ERR_OTHER;
1548                                         break;
1549                                 }
1550                         } else if (map[i].not_with != 0) {
1551                                 if ((map[i].not_with & user_account_control) != 0) {
1552                                         ret = LDB_ERR_OTHER;
1553                                         break;
1554                                 }
1555                         }
1556                 }
1557         }
1558         if (ret != LDB_SUCCESS) {
1559                 switch (ac->req->operation) {
1560                 case LDB_ADD:
1561                         ldb_asprintf_errstring(ldb_module_get_ctx(ac->module),
1562                                                "Failed to add %s: %s",
1563                                                ldb_dn_get_linearized(ac->msg->dn),
1564                                                map[i].error_string);
1565                         break;
1566                 case LDB_MODIFY:
1567                         ldb_asprintf_errstring(ldb_module_get_ctx(ac->module),
1568                                                "Failed to modify %s: %s",
1569                                                ldb_dn_get_linearized(ac->msg->dn),
1570                                                map[i].error_string);
1571                         break;
1572                 default:
1573                         return ldb_module_operr(ac->module);
1574                 }
1575         }
1576         return ret;
1577 }
1578
1579 /**
1580  * Validate that the restriction in point 5 of MS-SAMR 3.1.1.8.10 userAccountControl is honoured
1581  *
1582  */
1583 static int samldb_check_user_account_control_acl(struct samldb_ctx *ac,
1584                                                  struct dom_sid *sid,
1585                                                  uint32_t user_account_control,
1586                                                  uint32_t user_account_control_old)
1587 {
1588         int i, ret = 0;
1589         bool need_acl_check = false;
1590         struct ldb_result *res;
1591         const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL};
1592         struct security_token *user_token;
1593         struct security_descriptor *domain_sd;
1594         struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module));
1595         const struct uac_to_guid {
1596                 uint32_t uac;
1597                 const char *oid;
1598                 const char *guid;
1599                 enum sec_privilege privilege;
1600                 bool delete_is_privileged;
1601                 const char *error_string;
1602         } map[] = {
1603                 {
1604                         .uac = UF_PASSWD_NOTREQD,
1605                         .guid = GUID_DRS_UPDATE_PASSWORD_NOT_REQUIRED_BIT,
1606                         .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"
1607                 },
1608                 {
1609                         .uac = UF_DONT_EXPIRE_PASSWD,
1610                         .guid = GUID_DRS_UNEXPIRE_PASSWORD,
1611                         .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object"
1612                 },
1613                 {
1614                         .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED,
1615                         .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD,
1616                         .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"
1617                 },
1618                 {
1619                         .uac = UF_SERVER_TRUST_ACCOUNT,
1620                         .guid = GUID_DRS_DS_INSTALL_REPLICA,
1621                         .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"
1622                 },
1623                 {
1624                         .uac = UF_PARTIAL_SECRETS_ACCOUNT,
1625                         .guid = GUID_DRS_DS_INSTALL_REPLICA,
1626                         .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"
1627                 },
1628                 {
1629                         .uac = UF_INTERDOMAIN_TRUST_ACCOUNT,
1630                         .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID,
1631                         .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",
1632                         .delete_is_privileged = true
1633                 },
1634                 {
1635                         .uac = UF_TRUSTED_FOR_DELEGATION,
1636                         .privilege = SEC_PRIV_ENABLE_DELEGATION,
1637                         .delete_is_privileged = true,
1638                         .error_string = "Updating the UF_TRUSTED_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege"
1639                 },
1640                 {
1641                         .uac = UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION,
1642                         .privilege = SEC_PRIV_ENABLE_DELEGATION,
1643                         .delete_is_privileged = true,
1644                         .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege"
1645                 }
1646
1647         };
1648
1649         if (dsdb_module_am_system(ac->module)) {
1650                 return LDB_SUCCESS;
1651         }
1652
1653         for (i = 0; i < ARRAY_SIZE(map); i++) {
1654                 if (user_account_control & map[i].uac) {
1655                         need_acl_check = true;
1656                         break;
1657                 }
1658         }
1659         if (need_acl_check == false) {
1660                 return LDB_SUCCESS;
1661         }
1662
1663         user_token = acl_user_token(ac->module);
1664         if (user_token == NULL) {
1665                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1666         }
1667
1668         ret = dsdb_module_search_dn(ac->module, ac, &res,
1669                                     domain_dn,
1670                                     sd_attrs,
1671                                     DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED,
1672                                     ac->req);
1673         if (ret != LDB_SUCCESS) {
1674                 return ret;
1675         }
1676         if (res->count != 1) {
1677                 return ldb_module_operr(ac->module);
1678         }
1679
1680         ret = dsdb_get_sd_from_ldb_message(ldb_module_get_ctx(ac->module),
1681                                            ac, res->msgs[0], &domain_sd);
1682
1683         if (ret != LDB_SUCCESS) {
1684                 return ret;
1685         }
1686
1687         for (i = 0; i < ARRAY_SIZE(map); i++) {
1688                 uint32_t this_uac_new = user_account_control & map[i].uac;
1689                 uint32_t this_uac_old = user_account_control_old & map[i].uac;
1690                 if (this_uac_new != this_uac_old) {
1691                         if (this_uac_old != 0) {
1692                                 if (map[i].delete_is_privileged == false) {
1693                                         continue;
1694                                 }
1695                         }
1696                         if (map[i].oid) {
1697                                 struct ldb_control *control = ldb_request_get_control(ac->req, map[i].oid);
1698                                 if (control == NULL) {
1699                                         ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1700                                 }
1701                         } else if (map[i].privilege != SEC_PRIV_INVALID) {
1702                                 bool have_priv = security_token_has_privilege(user_token,
1703                                                                               map[i].privilege);
1704                                 if (have_priv == false) {
1705                                         ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1706                                 }
1707                         } else {
1708                                 ret = acl_check_extended_right(ac, domain_sd,
1709                                                                user_token,
1710                                                                map[i].guid,
1711                                                                SEC_ADS_CONTROL_ACCESS,
1712                                                                sid);
1713                         }
1714                         if (ret != LDB_SUCCESS) {
1715                                 break;
1716                         }
1717                 }
1718         }
1719         if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
1720                 switch (ac->req->operation) {
1721                 case LDB_ADD:
1722                         ldb_asprintf_errstring(ldb_module_get_ctx(ac->module),
1723                                                "Failed to add %s: %s",
1724                                                ldb_dn_get_linearized(ac->msg->dn),
1725                                                map[i].error_string);
1726                         break;
1727                 case LDB_MODIFY:
1728                         ldb_asprintf_errstring(ldb_module_get_ctx(ac->module),
1729                                                "Failed to modify %s: %s",
1730                                                ldb_dn_get_linearized(ac->msg->dn),
1731                                                map[i].error_string);
1732                         break;
1733                 default:
1734                         return ldb_module_operr(ac->module);
1735                 }
1736                 if (map[i].guid) {
1737                         dsdb_acl_debug(domain_sd, acl_user_token(ac->module),
1738                                        domain_dn,
1739                                        true,
1740                                        10);
1741                 }
1742         }
1743         return ret;
1744 }
1745
1746 static int samldb_check_user_account_control_rules(struct samldb_ctx *ac,
1747                                                    struct dom_sid *sid,
1748                                                    uint32_t user_account_control,
1749                                                    uint32_t user_account_control_old)
1750 {
1751         int ret;
1752         ret = samldb_check_user_account_control_invariants(ac, user_account_control);
1753         if (ret != LDB_SUCCESS) {
1754                 return ret;
1755         }
1756         ret = samldb_check_user_account_control_acl(ac, sid, user_account_control, user_account_control_old);
1757         if (ret != LDB_SUCCESS) {
1758                 return ret;
1759         }
1760         return ret;
1761 }
1762
1763
1764 /**
1765  * This function is called on LDB modify operations. It performs some additions/
1766  * replaces on the current LDB message when "userAccountControl" changes.
1767  */
1768 static int samldb_user_account_control_change(struct samldb_ctx *ac)
1769 {
1770         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1771         uint32_t old_uac;
1772         uint32_t new_uac;
1773         uint32_t raw_uac;
1774         uint32_t old_ufa;
1775         uint32_t new_ufa;
1776         uint32_t old_acb;
1777         uint32_t new_acb;
1778         uint32_t clear_acb;
1779         uint32_t old_atype;
1780         uint32_t new_atype;
1781         uint32_t old_pgrid;
1782         uint32_t new_pgrid;
1783         NTTIME old_lockoutTime;
1784         struct ldb_message_element *el;
1785         struct ldb_val *val;
1786         struct ldb_val computer_val;
1787         struct ldb_message *tmp_msg;
1788         struct dom_sid *sid;
1789         int ret;
1790         struct ldb_result *res;
1791         const char * const attrs[] = {
1792                 "objectClass",
1793                 "isCriticalSystemObject",
1794                 "userAccountControl",
1795                 "msDS-User-Account-Control-Computed",
1796                 "lockoutTime",
1797                 "objectSid",
1798                 NULL
1799         };
1800         bool is_computer = false;
1801         bool old_is_critical = false;
1802         bool new_is_critical = false;
1803
1804         el = dsdb_get_single_valued_attr(ac->msg, "userAccountControl",
1805                                          ac->req->operation);
1806         if (el == NULL || el->num_values == 0) {
1807                 ldb_asprintf_errstring(ldb,
1808                         "%08X: samldb: 'userAccountControl' can't be deleted!",
1809                         W_ERROR_V(WERR_DS_ILLEGAL_MOD_OPERATION));
1810                 return LDB_ERR_UNWILLING_TO_PERFORM;
1811         }
1812
1813         /* Create a temporary message for fetching the "userAccountControl" */
1814         tmp_msg = ldb_msg_new(ac->msg);
1815         if (tmp_msg == NULL) {
1816                 return ldb_module_oom(ac->module);
1817         }
1818         ret = ldb_msg_add(tmp_msg, el, 0);
1819         if (ret != LDB_SUCCESS) {
1820                 return ret;
1821         }
1822         raw_uac = ldb_msg_find_attr_as_uint(tmp_msg,
1823                                             "userAccountControl",
1824                                             0);
1825         new_acb = samdb_result_acct_flags(tmp_msg, NULL);
1826         talloc_free(tmp_msg);
1827         /*
1828          * UF_LOCKOUT, UF_PASSWD_CANT_CHANGE and UF_PASSWORD_EXPIRED
1829          * are only generated and not stored. We ignore them almost
1830          * completely, along with unknown bits and UF_SCRIPT.
1831          *
1832          * The only exception is ACB_AUTOLOCK, which features in
1833          * clear_acb when the bit is cleared in this modify operation.
1834          *
1835          * MS-SAMR 2.2.1.13 UF_FLAG Codes states that some bits are
1836          * ignored by clients and servers
1837          */
1838         new_uac = raw_uac & UF_SETTABLE_BITS;
1839
1840         /* Fetch the old "userAccountControl" and "objectClass" */
1841         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
1842                                     DSDB_FLAG_NEXT_MODULE, ac->req);
1843         if (ret != LDB_SUCCESS) {
1844                 return ret;
1845         }
1846         old_uac = ldb_msg_find_attr_as_uint(res->msgs[0], "userAccountControl", 0);
1847         if (old_uac == 0) {
1848                 return ldb_operr(ldb);
1849         }
1850         old_acb = samdb_result_acct_flags(res->msgs[0],
1851                                           "msDS-User-Account-Control-Computed");
1852         old_lockoutTime = ldb_msg_find_attr_as_int64(res->msgs[0],
1853                                                      "lockoutTime", 0);
1854         old_is_critical = ldb_msg_find_attr_as_bool(res->msgs[0],
1855                                                     "isCriticalSystemObject", 0);
1856         /* When we do not have objectclass "omputer" we cannot switch to a (read-only) DC */
1857         el = ldb_msg_find_element(res->msgs[0], "objectClass");
1858         if (el == NULL) {
1859                 return ldb_operr(ldb);
1860         }
1861         computer_val = data_blob_string_const("computer");
1862         val = ldb_msg_find_val(el, &computer_val);
1863         if (val != NULL) {
1864                 is_computer = true;
1865         }
1866
1867         old_ufa = old_uac & UF_ACCOUNT_TYPE_MASK;
1868         old_atype = ds_uf2atype(old_ufa);
1869         old_pgrid = ds_uf2prim_group_rid(old_uac);
1870
1871         new_ufa = new_uac & UF_ACCOUNT_TYPE_MASK;
1872         if (new_ufa == 0) {
1873                 /*
1874                  * When there is no account type embedded in "userAccountControl"
1875                  * fall back to UF_NORMAL_ACCOUNT.
1876                  */
1877                 new_ufa = UF_NORMAL_ACCOUNT;
1878                 new_uac |= new_ufa;
1879         }
1880         sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
1881         if (sid == NULL) {
1882                 return ldb_module_operr(ac->module);
1883         }
1884
1885         ret = samldb_check_user_account_control_rules(ac, sid, new_uac, old_uac);
1886         if (ret != LDB_SUCCESS) {
1887                 return ret;
1888         }
1889
1890         new_atype = ds_uf2atype(new_ufa);
1891         new_pgrid = ds_uf2prim_group_rid(new_uac);
1892
1893         clear_acb = old_acb & ~new_acb;
1894
1895         switch (new_ufa) {
1896         case UF_NORMAL_ACCOUNT:
1897                 new_is_critical = old_is_critical;
1898                 break;
1899
1900         case UF_INTERDOMAIN_TRUST_ACCOUNT:
1901                 new_is_critical = true;
1902                 break;
1903
1904         case UF_WORKSTATION_TRUST_ACCOUNT:
1905                 new_is_critical = false;
1906                 if (new_uac & UF_PARTIAL_SECRETS_ACCOUNT) {
1907                         if (!is_computer) {
1908                                 ldb_asprintf_errstring(ldb,
1909                                                        "%08X: samldb: UF_PARTIAL_SECRETS_ACCOUNT "
1910                                                        "requires objectclass 'computer'!",
1911                                                        W_ERROR_V(WERR_DS_MACHINE_ACCOUNT_CREATED_PRENT4));
1912                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1913                         }
1914                         new_is_critical = true;
1915                 }
1916                 break;
1917
1918         case UF_SERVER_TRUST_ACCOUNT:
1919                 if (!is_computer) {
1920                         ldb_asprintf_errstring(ldb,
1921                                 "%08X: samldb: UF_SERVER_TRUST_ACCOUNT "
1922                                 "requires objectclass 'computer'!",
1923                                 W_ERROR_V(WERR_DS_MACHINE_ACCOUNT_CREATED_PRENT4));
1924                         return LDB_ERR_UNWILLING_TO_PERFORM;
1925                 }
1926                 new_is_critical = true;
1927                 break;
1928
1929         default:
1930                 ldb_asprintf_errstring(ldb,
1931                         "%08X: samldb: invalid userAccountControl[0x%08X]",
1932                         W_ERROR_V(WERR_INVALID_PARAMETER), raw_uac);
1933                 return LDB_ERR_OTHER;
1934         }
1935
1936         if (old_atype != new_atype) {
1937                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1938                                          "sAMAccountType", new_atype);
1939                 if (ret != LDB_SUCCESS) {
1940                         return ret;
1941                 }
1942                 el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1943                 el->flags = LDB_FLAG_MOD_REPLACE;
1944         }
1945
1946         /* As per MS-SAMR 3.1.1.8.10 these flags have not to be set */
1947         if ((clear_acb & ACB_AUTOLOCK) && (old_lockoutTime != 0)) {
1948                 /* "pwdLastSet" reset as password expiration has been forced  */
1949                 ldb_msg_remove_attr(ac->msg, "lockoutTime");
1950                 ret = samdb_msg_add_uint64(ldb, ac->msg, ac->msg, "lockoutTime",
1951                                            (NTTIME)0);
1952                 if (ret != LDB_SUCCESS) {
1953                         return ret;
1954                 }
1955                 el = ldb_msg_find_element(ac->msg, "lockoutTime");
1956                 el->flags = LDB_FLAG_MOD_REPLACE;
1957         }
1958
1959         /* "isCriticalSystemObject" might be set/changed */
1960         if (old_is_critical != new_is_critical) {
1961                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1962                                          new_is_critical ? "TRUE": "FALSE");
1963                 if (ret != LDB_SUCCESS) {
1964                         return ret;
1965                 }
1966                 el = ldb_msg_find_element(ac->msg,
1967                                            "isCriticalSystemObject");
1968                 el->flags = LDB_FLAG_MOD_REPLACE;
1969         }
1970
1971         if (!ldb_msg_find_element(ac->msg, "primaryGroupID") &&
1972             (old_pgrid != new_pgrid)) {
1973                 /* Older AD deployments don't know about the RODC group */
1974                 if (new_pgrid == DOMAIN_RID_READONLY_DCS) {
1975                         ret = samldb_prim_group_tester(ac, new_pgrid);
1976                         if (ret != LDB_SUCCESS) {
1977                                 return ret;
1978                         }
1979                 }
1980
1981                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1982                                          "primaryGroupID", new_pgrid);
1983                 if (ret != LDB_SUCCESS) {
1984                         return ret;
1985                 }
1986                 el = ldb_msg_find_element(ac->msg,
1987                                            "primaryGroupID");
1988                 el->flags = LDB_FLAG_MOD_REPLACE;
1989         }
1990
1991         /* Propagate eventual "userAccountControl" attribute changes */
1992         if (old_uac != new_uac) {
1993                 char *tempstr = talloc_asprintf(ac->msg, "%d",
1994                                                 new_uac);
1995                 if (tempstr == NULL) {
1996                         return ldb_module_oom(ac->module);
1997                 }
1998
1999                 /* Overwrite "userAccountControl" correctly */
2000                 el = dsdb_get_single_valued_attr(ac->msg, "userAccountControl",
2001                                                  ac->req->operation);
2002                 el->values[0].data = (uint8_t *) tempstr;
2003                 el->values[0].length = strlen(tempstr);
2004         } else {
2005                 ldb_msg_remove_attr(ac->msg, "userAccountControl");
2006         }
2007
2008         return LDB_SUCCESS;
2009 }
2010
2011 static int samldb_lockout_time(struct samldb_ctx *ac)
2012 {
2013         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2014         NTTIME lockoutTime;
2015         struct ldb_message_element *el;
2016         struct ldb_message *tmp_msg;
2017         int ret;
2018
2019         el = dsdb_get_single_valued_attr(ac->msg, "lockoutTime",
2020                                          ac->req->operation);
2021         if (el == NULL || el->num_values == 0) {
2022                 ldb_asprintf_errstring(ldb,
2023                         "%08X: samldb: 'lockoutTime' can't be deleted!",
2024                         W_ERROR_V(WERR_DS_ILLEGAL_MOD_OPERATION));
2025                 return LDB_ERR_UNWILLING_TO_PERFORM;
2026         }
2027
2028         /* Create a temporary message for fetching the "lockoutTime" */
2029         tmp_msg = ldb_msg_new(ac->msg);
2030         if (tmp_msg == NULL) {
2031                 return ldb_module_oom(ac->module);
2032         }
2033         ret = ldb_msg_add(tmp_msg, el, 0);
2034         if (ret != LDB_SUCCESS) {
2035                 return ret;
2036         }
2037         lockoutTime = ldb_msg_find_attr_as_int64(tmp_msg,
2038                                                  "lockoutTime",
2039                                                  0);
2040         talloc_free(tmp_msg);
2041
2042         if (lockoutTime != 0) {
2043                 return LDB_SUCCESS;
2044         }
2045
2046         /* lockoutTime == 0 resets badPwdCount */
2047         ldb_msg_remove_attr(ac->msg, "badPwdCount");
2048         ret = samdb_msg_add_int(ldb, ac->msg, ac->msg,
2049                                 "badPwdCount", 0);
2050         if (ret != LDB_SUCCESS) {
2051                 return ret;
2052         }
2053         el = ldb_msg_find_element(ac->msg, "badPwdCount");
2054         el->flags = LDB_FLAG_MOD_REPLACE;
2055
2056         return LDB_SUCCESS;
2057 }
2058
2059 static int samldb_group_type_change(struct samldb_ctx *ac)
2060 {
2061         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2062         uint32_t group_type, old_group_type, account_type;
2063         struct ldb_message_element *el;
2064         struct ldb_message *tmp_msg;
2065         int ret;
2066         struct ldb_result *res;
2067         const char * const attrs[] = { "groupType", NULL };
2068
2069         el = dsdb_get_single_valued_attr(ac->msg, "groupType",
2070                                          ac->req->operation);
2071         if (el == NULL) {
2072                 /* we are not affected */
2073                 return LDB_SUCCESS;
2074         }
2075
2076         /* Create a temporary message for fetching the "groupType" */
2077         tmp_msg = ldb_msg_new(ac->msg);
2078         if (tmp_msg == NULL) {
2079                 return ldb_module_oom(ac->module);
2080         }
2081         ret = ldb_msg_add(tmp_msg, el, 0);
2082         if (ret != LDB_SUCCESS) {
2083                 return ret;
2084         }
2085         group_type = ldb_msg_find_attr_as_uint(tmp_msg, "groupType", 0);
2086         talloc_free(tmp_msg);
2087
2088         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
2089                                     DSDB_FLAG_NEXT_MODULE |
2090                                     DSDB_SEARCH_SHOW_DELETED, ac->req);
2091         if (ret != LDB_SUCCESS) {
2092                 return ret;
2093         }
2094         old_group_type = ldb_msg_find_attr_as_uint(res->msgs[0], "groupType", 0);
2095         if (old_group_type == 0) {
2096                 return ldb_operr(ldb);
2097         }
2098
2099         /* Group type switching isn't so easy as it seems: We can only
2100          * change in this directions: global <-> universal <-> local
2101          * On each step also the group type itself
2102          * (security/distribution) is variable. */
2103
2104         if (ldb_request_get_control(ac->req, LDB_CONTROL_PROVISION_OID) == NULL) {
2105                 switch (group_type) {
2106                 case GTYPE_SECURITY_GLOBAL_GROUP:
2107                 case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
2108                         /* change to "universal" allowed */
2109                         if ((old_group_type == GTYPE_SECURITY_DOMAIN_LOCAL_GROUP) ||
2110                         (old_group_type == GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP)) {
2111                                 ldb_set_errstring(ldb,
2112                                         "samldb: Change from security/distribution local group forbidden!");
2113                                 return LDB_ERR_UNWILLING_TO_PERFORM;
2114                         }
2115                 break;
2116
2117                 case GTYPE_SECURITY_UNIVERSAL_GROUP:
2118                 case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
2119                         /* each change allowed */
2120                 break;
2121                 case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
2122                 case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
2123                         /* change to "universal" allowed */
2124                         if ((old_group_type == GTYPE_SECURITY_GLOBAL_GROUP) ||
2125                         (old_group_type == GTYPE_DISTRIBUTION_GLOBAL_GROUP)) {
2126                                 ldb_set_errstring(ldb,
2127                                         "samldb: Change from security/distribution global group forbidden!");
2128                                 return LDB_ERR_UNWILLING_TO_PERFORM;
2129                         }
2130                 break;
2131
2132                 case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
2133                 default:
2134                         /* we don't allow this "groupType" values */
2135                         return LDB_ERR_UNWILLING_TO_PERFORM;
2136                 break;
2137                 }
2138         }
2139
2140         account_type =  ds_gtype2atype(group_type);
2141         if (account_type == 0) {
2142                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
2143                 return LDB_ERR_UNWILLING_TO_PERFORM;
2144         }
2145         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
2146                                  account_type);
2147         if (ret != LDB_SUCCESS) {
2148                 return ret;
2149         }
2150         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
2151         el->flags = LDB_FLAG_MOD_REPLACE;
2152
2153         return LDB_SUCCESS;
2154 }
2155
2156 static int samldb_sam_accountname_check(struct samldb_ctx *ac)
2157 {
2158         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2159         const char * const no_attrs[] = { NULL };
2160         struct ldb_result *res;
2161         const char *sam_accountname, *enc_str;
2162         struct ldb_message_element *el;
2163         struct ldb_message *tmp_msg;
2164         int ret;
2165
2166         el = dsdb_get_single_valued_attr(ac->msg, "sAMAccountName",
2167                                          ac->req->operation);
2168         if (el == NULL) {
2169                 /* we are not affected */
2170                 return LDB_SUCCESS;
2171         }
2172
2173         /* Create a temporary message for fetching the "sAMAccountName" */
2174         tmp_msg = ldb_msg_new(ac->msg);
2175         if (tmp_msg == NULL) {
2176                 return ldb_module_oom(ac->module);
2177         }
2178         ret = ldb_msg_add(tmp_msg, el, 0);
2179         if (ret != LDB_SUCCESS) {
2180                 return ret;
2181         }
2182
2183         /* We must not steal the original string, it belongs to the caller! */
2184         sam_accountname = talloc_strdup(ac, 
2185                                         ldb_msg_find_attr_as_string(tmp_msg, "sAMAccountName", NULL));
2186         talloc_free(tmp_msg);
2187
2188         if (sam_accountname == NULL) {
2189                 /* The "sAMAccountName" cannot be nothing */
2190                 ldb_set_errstring(ldb,
2191                                   "samldb: Empty account names aren't allowed!");
2192                 return LDB_ERR_UNWILLING_TO_PERFORM;
2193         }
2194
2195         enc_str = ldb_binary_encode_string(ac, sam_accountname);
2196         if (enc_str == NULL) {
2197                 return ldb_module_oom(ac->module);
2198         }
2199
2200         /* Make sure that a "sAMAccountName" is only used once */
2201
2202         ret = dsdb_module_search(ac->module, ac, &res,
2203                                  ldb_get_default_basedn(ldb),
2204                                  LDB_SCOPE_SUBTREE, no_attrs,
2205                                  DSDB_FLAG_NEXT_MODULE, ac->req,
2206                                  "(sAMAccountName=%s)", enc_str);
2207         if (ret != LDB_SUCCESS) {
2208                 return ret;
2209         }
2210         if (res->count > 1) {
2211                 return ldb_operr(ldb);
2212         } else if (res->count == 1) {
2213                 if (ldb_dn_compare(res->msgs[0]->dn, ac->msg->dn) != 0) {
2214                         ldb_asprintf_errstring(ldb,
2215                                                "samldb: Account name (sAMAccountName) '%s' already in use!",
2216                                                sam_accountname);
2217                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
2218                 }
2219         }
2220         talloc_free(res);
2221
2222         return LDB_SUCCESS;
2223 }
2224
2225 static int samldb_member_check(struct samldb_ctx *ac)
2226 {
2227         const char * const attrs[] = { "objectSid", NULL };
2228         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2229         struct ldb_message_element *el;
2230         struct ldb_dn *member_dn;
2231         struct dom_sid *sid;
2232         struct ldb_result *res;
2233         struct dom_sid *group_sid;
2234         unsigned int i, j;
2235         int ret;
2236
2237         /* Fetch information from the existing object */
2238
2239         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
2240                                  DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED, ac->req, NULL);
2241         if (ret != LDB_SUCCESS) {
2242                 return ret;
2243         }
2244         if (res->count != 1) {
2245                 return ldb_operr(ldb);
2246         }
2247
2248         group_sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
2249         if (group_sid == NULL) {
2250                 return ldb_operr(ldb);
2251         }
2252
2253         /* We've to walk over all modification entries and consider the "member"
2254          * ones. */
2255         for (i = 0; i < ac->msg->num_elements; i++) {
2256                 if (ldb_attr_cmp(ac->msg->elements[i].name, "member") != 0) {
2257                         continue;
2258                 }
2259
2260                 el = &ac->msg->elements[i];
2261                 for (j = 0; j < el->num_values; j++) {
2262                         struct ldb_result *group_res;
2263                         const char *group_attrs[] = { "primaryGroupID" , NULL };
2264                         uint32_t prim_group_rid;
2265
2266                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE) {
2267                                 /* Deletes will be handled in
2268                                  * repl_meta_data, and deletes not
2269                                  * matching a member will return
2270                                  * LDB_ERR_UNWILLING_TO_PERFORM
2271                                  * there */
2272                                 continue;
2273                         }
2274
2275                         member_dn = ldb_dn_from_ldb_val(ac, ldb,
2276                                                         &el->values[j]);
2277                         if (!ldb_dn_validate(member_dn)) {
2278                                 return ldb_operr(ldb);
2279                         }
2280
2281                         /* Denies to add "member"s to groups which are primary
2282                          * ones for them - in this case return
2283                          * ERR_ENTRY_ALREADY_EXISTS. */
2284
2285                         ret = dsdb_module_search_dn(ac->module, ac, &group_res,
2286                                                     member_dn, group_attrs,
2287                                                     DSDB_FLAG_NEXT_MODULE, ac->req);
2288                         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2289                                 /* member DN doesn't exist yet */
2290                                 continue;
2291                         }
2292                         if (ret != LDB_SUCCESS) {
2293                                 return ret;
2294                         }
2295                         prim_group_rid = ldb_msg_find_attr_as_uint(group_res->msgs[0], "primaryGroupID", (uint32_t)-1);
2296                         if (prim_group_rid == (uint32_t) -1) {
2297                                 /* the member hasn't to be a user account ->
2298                                  * therefore no check needed in this case. */
2299                                 continue;
2300                         }
2301
2302                         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
2303                                               prim_group_rid);
2304                         if (sid == NULL) {
2305                                 return ldb_operr(ldb);
2306                         }
2307
2308                         if (dom_sid_equal(group_sid, sid)) {
2309                                 ldb_asprintf_errstring(ldb,
2310                                                        "samldb: member %s already set via primaryGroupID %u",
2311                                                        ldb_dn_get_linearized(member_dn), prim_group_rid);
2312                                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
2313                         }
2314                 }
2315         }
2316
2317         talloc_free(res);
2318
2319         return LDB_SUCCESS;
2320 }
2321
2322 /* SAM objects have special rules regarding the "description" attribute on
2323  * modify operations. */
2324 static int samldb_description_check(struct samldb_ctx *ac, bool *modified)
2325 {
2326         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2327         const char * const attrs[] = { "objectClass", "description", NULL };
2328         struct ldb_result *res;
2329         unsigned int i;
2330         int ret;
2331
2332         /* Fetch information from the existing object */
2333         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
2334                                  DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED, ac->req,
2335                                  "(|(objectclass=user)(objectclass=group)(objectclass=samDomain)(objectclass=samServer))");
2336         if (ret != LDB_SUCCESS) {
2337                 /* don't treat it specially ... let normal error codes
2338                    happen from other places */
2339                 ldb_reset_err_string(ldb);
2340                 return LDB_SUCCESS;
2341         }
2342         if (res->count == 0) {
2343                 /* we didn't match the filter */
2344                 talloc_free(res);
2345                 return LDB_SUCCESS;
2346         }
2347
2348         /* We've to walk over all modification entries and consider the
2349          * "description" ones. */
2350         for (i = 0; i < ac->msg->num_elements; i++) {
2351                 if (ldb_attr_cmp(ac->msg->elements[i].name, "description") == 0) {
2352                         ac->msg->elements[i].flags |= LDB_FLAG_INTERNAL_FORCE_SINGLE_VALUE_CHECK;
2353                         *modified = true;
2354                 }
2355         }
2356
2357         talloc_free(res);
2358
2359         return LDB_SUCCESS;
2360 }
2361
2362 /* This trigger adapts the "servicePrincipalName" attributes if the
2363  * "dNSHostName" and/or "sAMAccountName" attribute change(s) */
2364 static int samldb_service_principal_names_change(struct samldb_ctx *ac)
2365 {
2366         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2367         struct ldb_message_element *el = NULL, *el2 = NULL;
2368         struct ldb_message *msg;
2369         const char * const attrs[] = { "servicePrincipalName", NULL };
2370         struct ldb_result *res;
2371         const char *dns_hostname = NULL, *old_dns_hostname = NULL,
2372                    *sam_accountname = NULL, *old_sam_accountname = NULL;
2373         unsigned int i, j;
2374         int ret;
2375
2376         el = dsdb_get_single_valued_attr(ac->msg, "dNSHostName",
2377                                          ac->req->operation);
2378         el2 = dsdb_get_single_valued_attr(ac->msg, "sAMAccountName",
2379                                           ac->req->operation);
2380         if ((el == NULL) && (el2 == NULL)) {
2381                 /* we are not affected */
2382                 return LDB_SUCCESS;
2383         }
2384
2385         /* Create a temporary message for fetching the "dNSHostName" */
2386         if (el != NULL) {
2387                 const char *dns_attrs[] = { "dNSHostName", NULL };
2388                 msg = ldb_msg_new(ac->msg);
2389                 if (msg == NULL) {
2390                         return ldb_module_oom(ac->module);
2391                 }
2392                 ret = ldb_msg_add(msg, el, 0);
2393                 if (ret != LDB_SUCCESS) {
2394                         return ret;
2395                 }
2396                 dns_hostname = talloc_strdup(ac, 
2397                                              ldb_msg_find_attr_as_string(msg, "dNSHostName", NULL));
2398                 if (dns_hostname == NULL) {
2399                         return ldb_module_oom(ac->module);
2400                 }
2401                         
2402                 talloc_free(msg);
2403
2404                 ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn,
2405                                             dns_attrs, DSDB_FLAG_NEXT_MODULE, ac->req);
2406                 if (ret == LDB_SUCCESS) {
2407                         old_dns_hostname = ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
2408                 }
2409         }
2410
2411         /* Create a temporary message for fetching the "sAMAccountName" */
2412         if (el2 != NULL) {
2413                 char *tempstr, *tempstr2 = NULL;
2414                 const char *acct_attrs[] = { "sAMAccountName", NULL };
2415
2416                 msg = ldb_msg_new(ac->msg);
2417                 if (msg == NULL) {
2418                         return ldb_module_oom(ac->module);
2419                 }
2420                 ret = ldb_msg_add(msg, el2, 0);
2421                 if (ret != LDB_SUCCESS) {
2422                         return ret;
2423                 }
2424                 tempstr = talloc_strdup(ac,
2425                                         ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL));
2426                 talloc_free(msg);
2427
2428                 ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, acct_attrs,
2429                                             DSDB_FLAG_NEXT_MODULE, ac->req);
2430                 if (ret == LDB_SUCCESS) {
2431                         tempstr2 = talloc_strdup(ac,
2432                                                  ldb_msg_find_attr_as_string(res->msgs[0],
2433                                                                              "sAMAccountName", NULL));
2434                 }
2435
2436
2437                 /* The "sAMAccountName" needs some additional trimming: we need
2438                  * to remove the trailing "$"s if they exist. */
2439                 if ((tempstr != NULL) && (tempstr[0] != '\0') &&
2440                     (tempstr[strlen(tempstr) - 1] == '$')) {
2441                         tempstr[strlen(tempstr) - 1] = '\0';
2442                 }
2443                 if ((tempstr2 != NULL) && (tempstr2[0] != '\0') &&
2444                     (tempstr2[strlen(tempstr2) - 1] == '$')) {
2445                         tempstr2[strlen(tempstr2) - 1] = '\0';
2446                 }
2447                 sam_accountname = tempstr;
2448                 old_sam_accountname = tempstr2;
2449         }
2450
2451         if (old_dns_hostname == NULL) {
2452                 /* we cannot change when the old name is unknown */
2453                 dns_hostname = NULL;
2454         }
2455         if ((old_dns_hostname != NULL) && (dns_hostname != NULL) &&
2456             (strcasecmp_m(old_dns_hostname, dns_hostname) == 0)) {
2457                 /* The "dNSHostName" didn't change */
2458                 dns_hostname = NULL;
2459         }
2460
2461         if (old_sam_accountname == NULL) {
2462                 /* we cannot change when the old name is unknown */
2463                 sam_accountname = NULL;
2464         }
2465         if ((old_sam_accountname != NULL) && (sam_accountname != NULL) &&
2466             (strcasecmp_m(old_sam_accountname, sam_accountname) == 0)) {
2467                 /* The "sAMAccountName" didn't change */
2468                 sam_accountname = NULL;
2469         }
2470
2471         if ((dns_hostname == NULL) && (sam_accountname == NULL)) {
2472                 /* Well, there are information missing (old name(s)) or the
2473                  * names didn't change. We've nothing to do and can exit here */
2474                 return LDB_SUCCESS;
2475         }
2476
2477         /* Potential "servicePrincipalName" changes in the same request have to
2478          * be handled before the update (Windows behaviour). */
2479         el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
2480         if (el != NULL) {
2481                 msg = ldb_msg_new(ac->msg);
2482                 if (msg == NULL) {
2483                         return ldb_module_oom(ac->module);
2484                 }
2485                 msg->dn = ac->msg->dn;
2486
2487                 do {
2488                         ret = ldb_msg_add(msg, el, el->flags);
2489                         if (ret != LDB_SUCCESS) {
2490                                 return ret;
2491                         }
2492
2493                         ldb_msg_remove_element(ac->msg, el);
2494
2495                         el = ldb_msg_find_element(ac->msg,
2496                                                   "servicePrincipalName");
2497                 } while (el != NULL);
2498
2499                 ret = dsdb_module_modify(ac->module, msg,
2500                                          DSDB_FLAG_NEXT_MODULE, ac->req);
2501                 if (ret != LDB_SUCCESS) {
2502                         return ret;
2503                 }
2504                 talloc_free(msg);
2505         }
2506
2507         /* Fetch the "servicePrincipalName"s if any */
2508         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
2509                                  DSDB_FLAG_NEXT_MODULE, ac->req, NULL);
2510         if (ret != LDB_SUCCESS) {
2511                 return ret;
2512         }
2513         if ((res->count != 1) || (res->msgs[0]->num_elements > 1)) {
2514                 return ldb_operr(ldb);
2515         }
2516
2517         if (res->msgs[0]->num_elements == 1) {
2518                 /*
2519                  * Yes, we do have "servicePrincipalName"s. First we update them
2520                  * locally, that means we do always substitute the current
2521                  * "dNSHostName" with the new one and/or "sAMAccountName"
2522                  * without "$" with the new one and then we append the
2523                  * modified "servicePrincipalName"s as a message element
2524                  * replace to the modification request (Windows behaviour). We
2525                  * need also to make sure that the values remain case-
2526                  * insensitively unique.
2527                  */
2528
2529                 ret = ldb_msg_add_empty(ac->msg, "servicePrincipalName",
2530                                         LDB_FLAG_MOD_REPLACE, &el);
2531                 if (ret != LDB_SUCCESS) {
2532                         return ret;
2533                 }
2534
2535                 for (i = 0; i < res->msgs[0]->elements[0].num_values; i++) {
2536                         char *old_str, *new_str, *pos;
2537                         const char *tok;
2538                         struct ldb_val *vals;
2539                         bool found = false;
2540
2541                         old_str = (char *)
2542                                 res->msgs[0]->elements[0].values[i].data;
2543
2544                         new_str = talloc_strdup(ac->msg,
2545                                                 strtok_r(old_str, "/", &pos));
2546                         if (new_str == NULL) {
2547                                 return ldb_module_oom(ac->module);
2548                         }
2549
2550                         while ((tok = strtok_r(NULL, "/", &pos)) != NULL) {
2551                                 if ((dns_hostname != NULL) &&
2552                                     (strcasecmp_m(tok, old_dns_hostname) == 0)) {
2553                                         tok = dns_hostname;
2554                                 }
2555                                 if ((sam_accountname != NULL) &&
2556                                     (strcasecmp_m(tok, old_sam_accountname) == 0)) {
2557                                         tok = sam_accountname;
2558                                 }
2559
2560                                 new_str = talloc_asprintf(ac->msg, "%s/%s",
2561                                                           new_str, tok);
2562                                 if (new_str == NULL) {
2563                                         return ldb_module_oom(ac->module);
2564                                 }
2565                         }
2566
2567                         /* Uniqueness check */
2568                         for (j = 0; (!found) && (j < el->num_values); j++) {
2569                                 if (strcasecmp_m((char *)el->values[j].data,
2570                                                new_str) == 0) {
2571                                         found = true;
2572                                 }
2573                         }
2574                         if (found) {
2575                                 continue;
2576                         }
2577
2578                         /*
2579                          * append the new "servicePrincipalName" -
2580                          * code derived from ldb_msg_add_value().
2581                          *
2582                          * Open coded to make it clear that we must
2583                          * append to the MOD_REPLACE el created above.
2584                          */
2585                         vals = talloc_realloc(ac->msg, el->values,
2586                                               struct ldb_val,
2587                                               el->num_values + 1);
2588                         if (vals == NULL) {
2589                                 return ldb_module_oom(ac->module);
2590                         }
2591                         el->values = vals;
2592                         el->values[el->num_values] = data_blob_string_const(new_str);
2593                         ++(el->num_values);
2594                 }
2595         }
2596
2597         talloc_free(res);
2598
2599         return LDB_SUCCESS;
2600 }
2601
2602 /* This checks the "fSMORoleOwner" attributes */
2603 static int samldb_fsmo_role_owner_check(struct samldb_ctx *ac)
2604 {
2605         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
2606         const char * const no_attrs[] = { NULL };
2607         struct ldb_message_element *el;
2608         struct ldb_message *tmp_msg;
2609         struct ldb_dn *res_dn;
2610         struct ldb_result *res;
2611         int ret;
2612
2613         el = dsdb_get_single_valued_attr(ac->msg, "fSMORoleOwner",
2614                                          ac->req->operation);
2615         if (el == NULL) {
2616                 /* we are not affected */
2617                 return LDB_SUCCESS;
2618         }
2619
2620         /* Create a temporary message for fetching the "fSMORoleOwner" */
2621         tmp_msg = ldb_msg_new(ac->msg);
2622         if (tmp_msg == NULL) {
2623                 return ldb_module_oom(ac->module);
2624         }
2625         ret = ldb_msg_add(tmp_msg, el, 0);
2626         if (ret != LDB_SUCCESS) {
2627                 return ret;
2628         }
2629         res_dn = ldb_msg_find_attr_as_dn(ldb, ac, tmp_msg, "fSMORoleOwner");
2630         talloc_free(tmp_msg);
2631
2632         if (res_dn == NULL) {
2633                 ldb_set_errstring(ldb,
2634                                   "samldb: 'fSMORoleOwner' attributes have to reference 'nTDSDSA' entries!");
2635                 if (ac->req->operation == LDB_ADD) {
2636                         return LDB_ERR_CONSTRAINT_VIOLATION;
2637                 } else {
2638                         return LDB_ERR_UNWILLING_TO_PERFORM;
2639                 }
2640         }
2641
2642         /* Fetched DN has to reference a "nTDSDSA" entry */
2643         ret = dsdb_module_search(ac->module, ac, &res, res_dn, LDB_SCOPE_BASE,
2644                                  no_attrs,
2645                                  DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED,
2646                                  ac->req, "(objectClass=nTDSDSA)");
2647         if (ret != LDB_SUCCESS) {
2648                 return ret;
2649         }
2650         if (res->count != 1) {
2651                 ldb_set_errstring(ldb,
2652                                   "samldb: 'fSMORoleOwner' attributes have to reference 'nTDSDSA' entries!");
2653                 return LDB_ERR_UNWILLING_TO_PERFORM;
2654         }
2655
2656         talloc_free(res);
2657
2658         return LDB_SUCCESS;
2659 }
2660
2661
2662 /* add */
2663 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
2664 {
2665         struct ldb_context *ldb;
2666         struct samldb_ctx *ac;
2667         struct ldb_message_element *el;
2668         int ret;
2669
2670         ldb = ldb_module_get_ctx(module);
2671         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
2672
2673         /* do not manipulate our control entries */
2674         if (ldb_dn_is_special(req->op.add.message->dn)) {
2675                 return ldb_next_request(module, req);
2676         }
2677
2678         el = ldb_msg_find_element(req->op.add.message, "userParameters");
2679         if (el != NULL && ldb_req_is_untrusted(req)) {
2680                 const char *reason = "samldb_add: "
2681                         "setting userParameters is not supported over LDAP, "
2682                         "see https://bugzilla.samba.org/show_bug.cgi?id=8077";
2683                 ldb_debug(ldb, LDB_DEBUG_WARNING, "%s", reason);
2684                 return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, reason);
2685         }
2686
2687         ac = samldb_ctx_init(module, req);
2688         if (ac == NULL) {
2689                 return ldb_operr(ldb);
2690         }
2691
2692         /* build the new msg */
2693         ac->msg = ldb_msg_copy_shallow(ac, req->op.add.message);
2694         if (ac->msg == NULL) {
2695                 talloc_free(ac);
2696                 ldb_debug(ldb, LDB_DEBUG_FATAL,
2697                           "samldb_add: ldb_msg_copy_shallow failed!\n");
2698                 return ldb_operr(ldb);
2699         }
2700
2701         el = ldb_msg_find_element(ac->msg, "fSMORoleOwner");
2702         if (el != NULL) {
2703                 ret = samldb_fsmo_role_owner_check(ac);
2704                 if (ret != LDB_SUCCESS) {
2705                         return ret;
2706                 }
2707         }
2708
2709         if (samdb_find_attribute(ldb, ac->msg,
2710                                  "objectclass", "user") != NULL) {
2711                 ac->type = SAMLDB_TYPE_USER;
2712
2713                 ret = samldb_prim_group_trigger(ac);
2714                 if (ret != LDB_SUCCESS) {
2715                         return ret;
2716                 }
2717
2718                 ret = samldb_objectclass_trigger(ac);
2719                 if (ret != LDB_SUCCESS) {
2720                         return ret;
2721                 }
2722
2723                 return samldb_fill_object(ac);
2724         }
2725
2726         if (samdb_find_attribute(ldb, ac->msg,
2727                                  "objectclass", "group") != NULL) {
2728                 ac->type = SAMLDB_TYPE_GROUP;
2729
2730                 ret = samldb_objectclass_trigger(ac);
2731                 if (ret != LDB_SUCCESS) {
2732                         return ret;
2733                 }
2734
2735                 return samldb_fill_object(ac);
2736         }
2737
2738         /* perhaps a foreignSecurityPrincipal? */
2739         if (samdb_find_attribute(ldb, ac->msg,
2740                                  "objectclass",
2741                                  "foreignSecurityPrincipal") != NULL) {
2742                 return samldb_fill_foreignSecurityPrincipal_object(ac);
2743         }
2744
2745         if (samdb_find_attribute(ldb, ac->msg,
2746                                  "objectclass", "classSchema") != NULL) {
2747                 ret = samldb_schema_info_update(ac);
2748                 if (ret != LDB_SUCCESS) {
2749                         talloc_free(ac);
2750                         return ret;
2751                 }
2752
2753                 ac->type = SAMLDB_TYPE_CLASS;
2754                 return samldb_fill_object(ac);
2755         }
2756
2757         if (samdb_find_attribute(ldb, ac->msg,
2758                                  "objectclass", "attributeSchema") != NULL) {
2759                 ret = samldb_schema_info_update(ac);
2760                 if (ret != LDB_SUCCESS) {
2761                         talloc_free(ac);
2762                         return ret;
2763                 }
2764
2765                 ac->type = SAMLDB_TYPE_ATTRIBUTE;
2766                 return samldb_fill_object(ac);
2767         }
2768
2769         talloc_free(ac);
2770
2771         /* nothing matched, go on */
2772         return ldb_next_request(module, req);
2773 }
2774
2775 /* modify */
2776 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
2777 {
2778         struct ldb_context *ldb;
2779         struct samldb_ctx *ac;
2780         struct ldb_message_element *el, *el2;
2781         bool modified = false;
2782         int ret;
2783
2784         if (ldb_dn_is_special(req->op.mod.message->dn)) {
2785                 /* do not manipulate our control entries */
2786                 return ldb_next_request(module, req);
2787         }
2788
2789         ldb = ldb_module_get_ctx(module);
2790
2791         /* make sure that "objectSid" is not specified */
2792         el = ldb_msg_find_element(req->op.mod.message, "objectSid");
2793         if (el != NULL) {
2794                 if (ldb_request_get_control(req, LDB_CONTROL_PROVISION_OID) == NULL) {
2795                         ldb_set_errstring(ldb,
2796                                           "samldb: objectSid must not be specified!");
2797                         return LDB_ERR_UNWILLING_TO_PERFORM;
2798                 }
2799         }
2800         /* make sure that "sAMAccountType" is not specified */
2801         el = ldb_msg_find_element(req->op.mod.message, "sAMAccountType");
2802         if (el != NULL) {
2803                 ldb_set_errstring(ldb,
2804                                   "samldb: sAMAccountType must not be specified!");
2805                 return LDB_ERR_UNWILLING_TO_PERFORM;
2806         }
2807         /* make sure that "isCriticalSystemObject" is not specified */
2808         el = ldb_msg_find_element(req->op.mod.message, "isCriticalSystemObject");
2809         if (el != NULL) {
2810                 if (ldb_request_get_control(req, LDB_CONTROL_RELAX_OID) == NULL) {
2811                         ldb_set_errstring(ldb,
2812                                           "samldb: isCriticalSystemObject must not be specified!");
2813                         return LDB_ERR_UNWILLING_TO_PERFORM;
2814                 }
2815         }
2816
2817         /* msDS-IntId is not allowed to be modified
2818          * except when modification comes from replication */
2819         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
2820                 if (!ldb_request_get_control(req,
2821                                              DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
2822                         return LDB_ERR_CONSTRAINT_VIOLATION;
2823                 }
2824         }
2825
2826         el = ldb_msg_find_element(req->op.mod.message, "userParameters");
2827         if (el != NULL && ldb_req_is_untrusted(req)) {
2828                 const char *reason = "samldb: "
2829                         "setting userParameters is not supported over LDAP, "
2830                         "see https://bugzilla.samba.org/show_bug.cgi?id=8077";
2831                 ldb_debug(ldb, LDB_DEBUG_WARNING, "%s", reason);
2832                 return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, reason);
2833         }
2834
2835         ac = samldb_ctx_init(module, req);
2836         if (ac == NULL) {
2837                 return ldb_operr(ldb);
2838         }
2839
2840         /* build the new msg */
2841         ac->msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
2842         if (ac->msg == NULL) {
2843                 talloc_free(ac);
2844                 ldb_debug(ldb, LDB_DEBUG_FATAL,
2845                           "samldb_modify: ldb_msg_copy_shallow failed!\n");
2846                 return ldb_operr(ldb);
2847         }
2848
2849         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
2850         if (el != NULL) {
2851                 ret = samldb_prim_group_trigger(ac);
2852                 if (ret != LDB_SUCCESS) {
2853                         return ret;
2854                 }
2855         }
2856
2857         el = ldb_msg_find_element(ac->msg, "userAccountControl");
2858         if (el != NULL) {
2859                 modified = true;
2860                 ret = samldb_user_account_control_change(ac);
2861                 if (ret != LDB_SUCCESS) {
2862                         return ret;
2863                 }
2864         }
2865
2866         el = ldb_msg_find_element(ac->msg, "lockoutTime");
2867         if (el != NULL) {
2868                 modified = true;
2869                 ret = samldb_lockout_time(ac);
2870                 if (ret != LDB_SUCCESS) {
2871                         return ret;
2872                 }
2873         }
2874
2875         el = ldb_msg_find_element(ac->msg, "groupType");
2876         if (el != NULL) {
2877                 modified = true;
2878                 ret = samldb_group_type_change(ac);
2879                 if (ret != LDB_SUCCESS) {
2880                         return ret;
2881                 }
2882         }
2883
2884         el = ldb_msg_find_element(ac->msg, "sAMAccountName");
2885         if (el != NULL) {
2886                 ret = samldb_sam_accountname_check(ac);
2887                 if (ret != LDB_SUCCESS) {
2888                         return ret;
2889                 }
2890         }
2891
2892         el = ldb_msg_find_element(ac->msg, "member");
2893         if (el != NULL) {
2894                 ret = samldb_member_check(ac);
2895                 if (ret != LDB_SUCCESS) {
2896                         return ret;
2897                 }
2898         }
2899
2900         el = ldb_msg_find_element(ac->msg, "description");
2901         if (el != NULL) {
2902                 ret = samldb_description_check(ac, &modified);
2903                 if (ret != LDB_SUCCESS) {
2904                         return ret;
2905                 }
2906         }
2907
2908         el = ldb_msg_find_element(ac->msg, "dNSHostName");
2909         el2 = ldb_msg_find_element(ac->msg, "sAMAccountName");
2910         if ((el != NULL) || (el2 != NULL)) {
2911                 modified = true;
2912                 ret = samldb_service_principal_names_change(ac);
2913                 if (ret != LDB_SUCCESS) {
2914                         return ret;
2915                 }
2916         }
2917
2918         el = ldb_msg_find_element(ac->msg, "fSMORoleOwner");
2919         if (el != NULL) {
2920                 ret = samldb_fsmo_role_owner_check(ac);
2921                 if (ret != LDB_SUCCESS) {
2922                         return ret;
2923                 }
2924         }
2925
2926         if (modified) {
2927                 struct ldb_request *child_req;
2928
2929                 /* Now perform the real modifications as a child request */
2930                 ret = ldb_build_mod_req(&child_req, ldb, ac,
2931                                         ac->msg,
2932                                         req->controls,
2933                                         req, dsdb_next_callback,
2934                                         req);
2935                 LDB_REQ_SET_LOCATION(child_req);
2936                 if (ret != LDB_SUCCESS) {
2937                         return ret;
2938                 }
2939
2940                 return ldb_next_request(module, child_req);
2941         }
2942
2943         talloc_free(ac);
2944
2945         /* no change which interests us, go on */
2946         return ldb_next_request(module, req);
2947 }
2948
2949 /* delete */
2950
2951 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
2952 {
2953         struct ldb_context *ldb;
2954         struct dom_sid *sid;
2955         uint32_t rid;
2956         NTSTATUS status;
2957         int ret;
2958         struct ldb_result *res;
2959         const char * const attrs[] = { "objectSid", "isDeleted", NULL };
2960         const char * const noattrs[] = { NULL };
2961
2962         ldb = ldb_module_get_ctx(ac->module);
2963
2964         /* Finds out the SID/RID of the SAM object */
2965         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->req->op.del.dn,
2966                                         attrs,
2967                                         DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED,
2968                                         ac->req);
2969         if (ret != LDB_SUCCESS) {
2970                 return ret;
2971         }
2972
2973         if (ldb_msg_check_string_attribute(res->msgs[0], "isDeleted", "TRUE")) {
2974                 return LDB_SUCCESS;
2975         }
2976
2977         sid = samdb_result_dom_sid(ac, res->msgs[0], "objectSid");
2978         if (sid == NULL) {
2979                 /* No SID - it might not be a SAM object - therefore ok */
2980                 return LDB_SUCCESS;
2981         }
2982         status = dom_sid_split_rid(ac, sid, NULL, &rid);
2983         if (!NT_STATUS_IS_OK(status)) {
2984                 return ldb_operr(ldb);
2985         }
2986         if (rid == 0) {
2987                 /* Special object (security principal?) */
2988                 return LDB_SUCCESS;
2989         }
2990         /* do not allow deletion of well-known sids */
2991         if (rid < DSDB_SAMDB_MINIMUM_ALLOWED_RID &&
2992             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
2993                 return LDB_ERR_OTHER;
2994         }
2995
2996         /* Deny delete requests from groups which are primary ones */
2997         ret = dsdb_module_search(ac->module, ac, &res,
2998                                  ldb_get_default_basedn(ldb),
2999                                  LDB_SCOPE_SUBTREE, noattrs,
3000                                  DSDB_FLAG_NEXT_MODULE,
3001                                  ac->req,
3002                                  "(&(primaryGroupID=%u)(objectClass=user))", rid);
3003         if (ret != LDB_SUCCESS) {
3004                 return ret;
3005         }
3006         if (res->count > 0) {
3007                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
3008         }
3009
3010         return LDB_SUCCESS;
3011 }
3012
3013 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
3014 {
3015         struct samldb_ctx *ac;
3016         int ret;
3017
3018         if (ldb_dn_is_special(req->op.del.dn)) {
3019                 /* do not manipulate our control entries */
3020                 return ldb_next_request(module, req);
3021         }
3022
3023         ac = samldb_ctx_init(module, req);
3024         if (ac == NULL) {
3025                 return ldb_operr(ldb_module_get_ctx(module));
3026         }
3027
3028         ret = samldb_prim_group_users_check(ac);
3029         if (ret != LDB_SUCCESS) {
3030                 return ret;
3031         }
3032
3033         talloc_free(ac);
3034
3035         return ldb_next_request(module, req);
3036 }
3037
3038 /* rename */
3039
3040 static int check_rename_constraints(struct ldb_message *msg,
3041                                     struct samldb_ctx *ac,
3042                                     struct ldb_dn *olddn, struct ldb_dn *newdn)
3043 {
3044         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
3045         struct ldb_dn *dn1, *dn2, *nc_root;
3046         int32_t systemFlags;
3047         bool move_op = false;
3048         bool rename_op = false;
3049         int ret;
3050
3051         /* Skip the checks if old and new DN are the same, or if we have the
3052          * relax control specified or if the returned objects is already
3053          * deleted and needs only to be moved for consistency. */
3054
3055         if (ldb_dn_compare(olddn, newdn) == 0) {
3056                 return LDB_SUCCESS;
3057         }
3058         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) != NULL) {
3059                 return LDB_SUCCESS;
3060         }
3061         if (ldb_msg_find_attr_as_bool(msg, "isDeleted", false)) {
3062                 return LDB_SUCCESS;
3063         }
3064
3065         /* Objects under CN=System */
3066
3067         dn1 = ldb_dn_copy(ac, ldb_get_default_basedn(ldb));
3068         if (dn1 == NULL) return ldb_oom(ldb);
3069
3070         if ( ! ldb_dn_add_child_fmt(dn1, "CN=System")) {
3071                 talloc_free(dn1);
3072                 return LDB_ERR_OPERATIONS_ERROR;
3073         }
3074
3075         if ((ldb_dn_compare_base(dn1, olddn) == 0) &&
3076             (ldb_dn_compare_base(dn1, newdn) != 0)) {
3077                 talloc_free(dn1);
3078                 ldb_asprintf_errstring(ldb,
3079                                        "subtree_rename: Cannot move/rename %s. Objects under CN=System have to stay under it!",
3080                                        ldb_dn_get_linearized(olddn));
3081                 return LDB_ERR_OTHER;
3082         }
3083
3084         talloc_free(dn1);
3085
3086         /* LSA objects */
3087
3088         if ((samdb_find_attribute(ldb, msg, "objectClass", "secret") != NULL) ||
3089             (samdb_find_attribute(ldb, msg, "objectClass", "trustedDomain") != NULL)) {
3090                 ldb_asprintf_errstring(ldb,
3091                                        "subtree_rename: Cannot move/rename %s. It's an LSA-specific object!",
3092                                        ldb_dn_get_linearized(olddn));
3093                 return LDB_ERR_UNWILLING_TO_PERFORM;
3094         }
3095
3096         /* systemFlags */
3097
3098         dn1 = ldb_dn_get_parent(ac, olddn);
3099         if (dn1 == NULL) return ldb_oom(ldb);
3100         dn2 = ldb_dn_get_parent(ac, newdn);
3101         if (dn2 == NULL) return ldb_oom(ldb);
3102
3103         if (ldb_dn_compare(dn1, dn2) == 0) {
3104                 rename_op = true;
3105         } else {
3106                 move_op = true;
3107         }
3108
3109         talloc_free(dn1);
3110         talloc_free(dn2);
3111
3112         systemFlags = ldb_msg_find_attr_as_int(msg, "systemFlags", 0);
3113
3114         /* Fetch name context */
3115
3116         ret = dsdb_find_nc_root(ldb, ac, olddn, &nc_root);
3117         if (ret != LDB_SUCCESS) {
3118                 return ret;
3119         }
3120
3121         if (ldb_dn_compare(nc_root, ldb_get_schema_basedn(ldb)) == 0) {
3122                 if (move_op) {
3123                         ldb_asprintf_errstring(ldb,
3124                                                "subtree_rename: Cannot move %s within schema partition",
3125                                                ldb_dn_get_linearized(olddn));
3126                         return LDB_ERR_UNWILLING_TO_PERFORM;
3127                 }
3128                 if (rename_op &&
3129                     (systemFlags & SYSTEM_FLAG_SCHEMA_BASE_OBJECT) != 0) {
3130                         ldb_asprintf_errstring(ldb,
3131                                                "subtree_rename: Cannot rename %s within schema partition",
3132                                                ldb_dn_get_linearized(olddn));
3133                         return LDB_ERR_UNWILLING_TO_PERFORM;
3134                 }
3135         } else if (ldb_dn_compare(nc_root, ldb_get_config_basedn(ldb)) == 0) {
3136                 if (move_op &&
3137                     (systemFlags & SYSTEM_FLAG_CONFIG_ALLOW_MOVE) == 0) {
3138                         /* Here we have to do more: control the
3139                          * "ALLOW_LIMITED_MOVE" flag. This means that the
3140                          * grand-grand-parents of two objects have to be equal
3141                          * in order to perform the move (this is used for
3142                          * moving "server" objects in the "sites" container). */
3143                         bool limited_move =
3144                                 systemFlags & SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE;
3145
3146                         if (limited_move) {
3147                                 dn1 = ldb_dn_copy(ac, olddn);
3148                                 if (dn1 == NULL) return ldb_oom(ldb);
3149                                 dn2 = ldb_dn_copy(ac, newdn);
3150                                 if (dn2 == NULL) return ldb_oom(ldb);
3151
3152                                 limited_move &= ldb_dn_remove_child_components(dn1, 3);
3153                                 limited_move &= ldb_dn_remove_child_components(dn2, 3);
3154                                 limited_move &= ldb_dn_compare(dn1, dn2) == 0;
3155
3156                                 talloc_free(dn1);
3157                                 talloc_free(dn2);
3158                         }
3159
3160                         if (!limited_move) {
3161                                 ldb_asprintf_errstring(ldb,
3162                                                        "subtree_rename: Cannot move %s to %s in config partition",
3163                                                        ldb_dn_get_linearized(olddn), ldb_dn_get_linearized(newdn));
3164                                 return LDB_ERR_UNWILLING_TO_PERFORM;
3165                         }
3166                 }
3167                 if (rename_op &&
3168                     (systemFlags & SYSTEM_FLAG_CONFIG_ALLOW_RENAME) == 0) {
3169                         ldb_asprintf_errstring(ldb,
3170                                                "subtree_rename: Cannot rename %s to %s within config partition",
3171                                                ldb_dn_get_linearized(olddn), ldb_dn_get_linearized(newdn));
3172                         return LDB_ERR_UNWILLING_TO_PERFORM;
3173                 }
3174         } else if (ldb_dn_compare(nc_root, ldb_get_default_basedn(ldb)) == 0) {
3175                 if (move_op &&
3176                     (systemFlags & SYSTEM_FLAG_DOMAIN_DISALLOW_MOVE) != 0) {
3177                         ldb_asprintf_errstring(ldb,
3178                                                "subtree_rename: Cannot move %s to %s - DISALLOW_MOVE set",
3179                                                ldb_dn_get_linearized(olddn), ldb_dn_get_linearized(newdn));
3180                         return LDB_ERR_UNWILLING_TO_PERFORM;
3181                 }
3182                 if (rename_op &&
3183                     (systemFlags & SYSTEM_FLAG_DOMAIN_DISALLOW_RENAME) != 0) {
3184                         ldb_asprintf_errstring(ldb,
3185                                                        "subtree_rename: Cannot rename %s to %s - DISALLOW_RENAME set",
3186                                                ldb_dn_get_linearized(olddn), ldb_dn_get_linearized(newdn));
3187                         return LDB_ERR_UNWILLING_TO_PERFORM;
3188                 }
3189         }
3190
3191         talloc_free(nc_root);
3192
3193         return LDB_SUCCESS;
3194 }
3195
3196
3197 static int samldb_rename_search_base_callback(struct ldb_request *req,
3198                                                struct ldb_reply *ares)
3199 {
3200         struct samldb_ctx *ac;
3201         int ret;
3202
3203         ac = talloc_get_type(req->context, struct samldb_ctx);
3204
3205         if (!ares) {
3206                 return ldb_module_done(ac->req, NULL, NULL,
3207                                         LDB_ERR_OPERATIONS_ERROR);
3208         }
3209         if (ares->error != LDB_SUCCESS) {
3210                 return ldb_module_done(ac->req, ares->controls,
3211                                         ares->response, ares->error);
3212         }
3213
3214         switch (ares->type) {
3215         case LDB_REPLY_ENTRY:
3216                 /*
3217                  * This is the root entry of the originating move
3218                  * respectively rename request. It has been already
3219                  * stored in the list using "subtree_rename_search()".
3220                  * Only this one is subject to constraint checking.
3221                  */
3222                 ret = check_rename_constraints(ares->message, ac,
3223                                                ac->req->op.rename.olddn,
3224                                                ac->req->op.rename.newdn);
3225                 if (ret != LDB_SUCCESS) {
3226                         return ldb_module_done(ac->req, NULL, NULL,
3227                                                ret);
3228                 }
3229                 break;
3230
3231         case LDB_REPLY_REFERRAL:
3232                 /* ignore */
3233                 break;
3234
3235         case LDB_REPLY_DONE:
3236
3237                 /*
3238                  * Great, no problem with the rename, so go ahead as
3239                  * if we never were here
3240                  */
3241                 ret = ldb_next_request(ac->module, ac->req);
3242                 talloc_free(ares);
3243                 return ret;
3244         }
3245
3246         talloc_free(ares);
3247         return LDB_SUCCESS;
3248 }
3249
3250
3251 /* rename */
3252 static int samldb_rename(struct ldb_module *module, struct ldb_request *req)
3253 {
3254         struct ldb_context *ldb;
3255         static const char * const attrs[] = { "objectClass", "systemFlags",
3256                                               "isDeleted", NULL };
3257         struct ldb_request *search_req;
3258         struct samldb_ctx *ac;
3259         int ret;
3260
3261         if (ldb_dn_is_special(req->op.rename.olddn)) { /* do not manipulate our control entries */
3262                 return ldb_next_request(module, req);
3263         }
3264
3265         ldb = ldb_module_get_ctx(module);
3266
3267         ac = samldb_ctx_init(module, req);
3268         if (!ac) {
3269                 return ldb_oom(ldb);
3270         }
3271
3272         ret = ldb_build_search_req(&search_req, ldb, ac,
3273                                    req->op.rename.olddn,
3274                                    LDB_SCOPE_BASE,
3275                                    "(objectClass=*)",
3276                                    attrs,
3277                                    NULL,
3278                                    ac,
3279                                    samldb_rename_search_base_callback,
3280                                    req);
3281         LDB_REQ_SET_LOCATION(search_req);
3282         if (ret != LDB_SUCCESS) {
3283                 return ret;
3284         }
3285
3286         ret = ldb_request_add_control(search_req, LDB_CONTROL_SHOW_RECYCLED_OID,
3287                                       true, NULL);
3288         if (ret != LDB_SUCCESS) {
3289                 return ret;
3290         }
3291
3292         return ldb_next_request(ac->module, search_req);
3293 }
3294
3295 /* extended */
3296
3297 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
3298 {
3299         struct ldb_context *ldb = ldb_module_get_ctx(module);
3300         struct dsdb_fsmo_extended_op *exop;
3301         int ret;
3302
3303         exop = talloc_get_type(req->op.extended.data,
3304                                struct dsdb_fsmo_extended_op);
3305         if (!exop) {
3306                 ldb_set_errstring(ldb,
3307                                   "samldb_extended_allocate_rid_pool: invalid extended data");
3308                 return LDB_ERR_PROTOCOL_ERROR;
3309         }
3310
3311         ret = ridalloc_allocate_rid_pool_fsmo(module, exop, req);
3312         if (ret != LDB_SUCCESS) {
3313                 return ret;
3314         }
3315
3316         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
3317 }
3318
3319 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
3320 {
3321         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
3322                 return samldb_extended_allocate_rid_pool(module, req);
3323         }
3324
3325         return ldb_next_request(module, req);
3326 }
3327
3328
3329 static const struct ldb_module_ops ldb_samldb_module_ops = {
3330         .name          = "samldb",
3331         .add           = samldb_add,
3332         .modify        = samldb_modify,
3333         .del           = samldb_delete,
3334         .rename        = samldb_rename,
3335         .extended      = samldb_extended
3336 };
3337
3338
3339 int ldb_samldb_module_init(const char *version)
3340 {
3341         LDB_MODULE_CHECK_VERSION(version);
3342         return ldb_register_module(&ldb_samldb_module_ops);
3343 }