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