s4:samldb LDB module - refactor the "primaryGroupID" check on user creation
[sfrench/samba-autobuild/.git] / source4 / dsdb / samdb / ldb_modules / samldb.c
1 /*
2    SAM ldb module
3
4    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
5    Copyright (C) Simo Sorce  2004-2008
6    Copyright (C) Matthias Dieter Wallnöfer 2009-2010
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /*
23  *  Name: ldb
24  *
25  *  Component: ldb samldb module
26  *
27  *  Description: add embedded user/group creation functionality
28  *
29  *  Author: Simo Sorce
30  */
31
32 #include "includes.h"
33 #include "libcli/ldap/ldap_ndr.h"
34 #include "ldb_module.h"
35 #include "dsdb/samdb/samdb.h"
36 #include "dsdb/samdb/ldb_modules/util.h"
37 #include "libcli/security/security.h"
38 #include "librpc/gen_ndr/ndr_security.h"
39 #include "../lib/util/util_ldb.h"
40 #include "ldb_wrap.h"
41 #include "param/param.h"
42
43 struct samldb_ctx;
44
45 typedef int (*samldb_step_fn_t)(struct samldb_ctx *);
46
47 struct samldb_step {
48         struct samldb_step *next;
49         samldb_step_fn_t fn;
50 };
51
52 struct samldb_ctx {
53         struct ldb_module *module;
54         struct ldb_request *req;
55
56         /* used for add operations */
57         const char *type;
58
59         /* the resulting message */
60         struct ldb_message *msg;
61
62         /* holds a generic dn */
63         struct ldb_dn *dn;
64
65         /* used in "samldb_find_for_defaultObjectCategory" */
66         struct ldb_dn *res_dn;
67
68         /* all the async steps necessary to complete the operation */
69         struct samldb_step *steps;
70         struct samldb_step *curstep;
71
72         /* If someone set an ares to forward controls and response back to the caller */
73         struct ldb_reply *ares;
74 };
75
76 static struct samldb_ctx *samldb_ctx_init(struct ldb_module *module,
77                                           struct ldb_request *req)
78 {
79         struct ldb_context *ldb;
80         struct samldb_ctx *ac;
81
82         ldb = ldb_module_get_ctx(module);
83
84         ac = talloc_zero(req, struct samldb_ctx);
85         if (ac == NULL) {
86                 ldb_oom(ldb);
87                 return NULL;
88         }
89
90         ac->module = module;
91         ac->req = req;
92
93         return ac;
94 }
95
96 static int samldb_add_step(struct samldb_ctx *ac, samldb_step_fn_t fn)
97 {
98         struct samldb_step *step, *stepper;
99
100         step = talloc_zero(ac, struct samldb_step);
101         if (step == NULL) {
102                 return ldb_oom(ldb_module_get_ctx(ac->module));
103         }
104
105         step->fn = fn;
106
107         if (ac->steps == NULL) {
108                 ac->steps = step;
109                 ac->curstep = step;
110         } else {
111                 if (ac->curstep == NULL)
112                         return ldb_operr(ldb_module_get_ctx(ac->module));
113                 for (stepper = ac->curstep; stepper->next != NULL;
114                         stepper = stepper->next);
115                 stepper->next = step;
116         }
117
118         return LDB_SUCCESS;
119 }
120
121 static int samldb_first_step(struct samldb_ctx *ac)
122 {
123         if (ac->steps == NULL) {
124                 return ldb_operr(ldb_module_get_ctx(ac->module));
125         }
126
127         ac->curstep = ac->steps;
128         return ac->curstep->fn(ac);
129 }
130
131 static int samldb_next_step(struct samldb_ctx *ac)
132 {
133         if (ac->curstep->next) {
134                 ac->curstep = ac->curstep->next;
135                 return ac->curstep->fn(ac);
136         }
137
138         /* we exit the samldb module here */
139         /* If someone set an ares to forward controls and response back to the caller, use them */
140         if (ac->ares) {
141                 return ldb_module_done(ac->req, ac->ares->controls,
142                                        ac->ares->response, LDB_SUCCESS);
143         } else {
144                 return ldb_module_done(ac->req, NULL, NULL, LDB_SUCCESS);
145         }
146 }
147
148
149 /* sAMAccountName handling */
150
151 static int samldb_generate_sAMAccountName(struct ldb_context *ldb, struct ldb_message *msg)
152 {
153         char *name;
154
155         /* Format: $000000-000000000000 */
156
157         name = talloc_asprintf(msg, "$%.6X-%.6X%.6X",
158                                 (unsigned int)generate_random(),
159                                 (unsigned int)generate_random(),
160                                 (unsigned int)generate_random());
161         if (name == NULL) {
162                 return ldb_oom(ldb);
163         }
164         return ldb_msg_add_steal_string(msg, "sAMAccountName", name);
165 }
166
167 static int samldb_check_sAMAccountName(struct samldb_ctx *ac)
168 {
169         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
170         const char *name;
171         int ret;
172
173         if (ldb_msg_find_element(ac->msg, "sAMAccountName") == NULL) {
174                 ret = samldb_generate_sAMAccountName(ldb, ac->msg);
175                 if (ret != LDB_SUCCESS) {
176                         return ret;
177                 }
178         }
179
180         name = ldb_msg_find_attr_as_string(ac->msg, "sAMAccountName", NULL);
181         if (name == NULL) {
182                 return ldb_operr(ldb);
183         }
184
185         ret = samdb_search_count(ldb, NULL, "(sAMAccountName=%s)",
186                                  ldb_binary_encode_string(ac, name));
187         if ((ret < 0) || (ret > 1)) {
188                 return ldb_operr(ldb);
189         }
190         if (ret == 1) {
191                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
192         }
193
194         return samldb_next_step(ac);
195 }
196
197 /* sAMAccountType handling */
198
199 static int samldb_check_sAMAccountType(struct samldb_ctx *ac)
200 {
201         struct ldb_context *ldb;
202         unsigned int account_type;
203         unsigned int group_type;
204         unsigned int uac;
205         int ret;
206
207         ldb = ldb_module_get_ctx(ac->module);
208
209         /* make sure sAMAccountType is not specified */
210         if (ldb_msg_find_element(ac->msg, "sAMAccountType") != NULL) {
211                 ldb_asprintf_errstring(ldb,
212                         "sAMAccountType must not be specified!");
213                 return LDB_ERR_UNWILLING_TO_PERFORM;
214         }
215
216         if (strcmp("user", ac->type) == 0) {
217                 uac = samdb_result_uint(ac->msg, "userAccountControl", 0);
218                 if (uac == 0) {
219                         ldb_asprintf_errstring(ldb,
220                                 "userAccountControl invalid!");
221                         return LDB_ERR_UNWILLING_TO_PERFORM;
222                 } else {
223                         account_type = ds_uf2atype(uac);
224                         ret = samdb_msg_add_uint(ldb,
225                                                  ac->msg, ac->msg,
226                                                  "sAMAccountType",
227                                                  account_type);
228                         if (ret != LDB_SUCCESS) {
229                                 return ret;
230                         }
231                 }
232         } else if (strcmp("group", ac->type) == 0) {
233                 group_type = samdb_result_uint(ac->msg, "groupType", 0);
234                 if (group_type == 0) {
235                         ldb_asprintf_errstring(ldb,
236                                 "groupType invalid!\n");
237                         return LDB_ERR_UNWILLING_TO_PERFORM;
238                 } else {
239                         account_type = ds_gtype2atype(group_type);
240                         ret = samdb_msg_add_uint(ldb,
241                                                  ac->msg, ac->msg,
242                                                  "sAMAccountType",
243                                                  account_type);
244                         if (ret != LDB_SUCCESS) {
245                                 return ret;
246                         }
247                 }
248         }
249
250         return samldb_next_step(ac);
251 }
252
253 /* primaryGroupID handling */
254
255 static int samldb_check_primaryGroupID(struct samldb_ctx *ac)
256 {
257         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
258         struct ldb_dn *prim_group_dn;
259         uint32_t rid;
260         struct dom_sid *sid;
261         int ret;
262
263         rid = samdb_result_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
264         if (rid == (uint32_t) -1) {
265                 rid = DOMAIN_RID_USERS;
266                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
267                                          "primaryGroupID", rid);
268                 if (ret != LDB_SUCCESS) {
269                         return ret;
270                 }
271         }
272
273         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
274         if (sid == NULL) {
275                 return ldb_operr(ldb);
276         }
277
278         prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSID=%s)",
279                                         dom_sid_string(ac, sid));
280         if (prim_group_dn == NULL) {
281                 ldb_asprintf_errstring(ldb,
282                                        "Failed to find primary group with RID %u!",
283                                        rid);
284                 return LDB_ERR_UNWILLING_TO_PERFORM;
285         }
286
287         return samldb_next_step(ac);
288 }
289
290
291 static bool samldb_msg_add_sid(struct ldb_message *msg,
292                                 const char *name,
293                                 const struct dom_sid *sid)
294 {
295         struct ldb_val v;
296         enum ndr_err_code ndr_err;
297
298         ndr_err = ndr_push_struct_blob(&v, msg, sid,
299                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
300         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
301                 return false;
302         }
303         return (ldb_msg_add_value(msg, name, &v, NULL) == 0);
304 }
305
306
307 /* allocate a SID using our RID Set */
308 static int samldb_allocate_sid(struct samldb_ctx *ac)
309 {
310         uint32_t rid;
311         struct dom_sid *sid;
312         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
313         int ret;
314
315         ret = ridalloc_allocate_rid(ac->module, &rid);
316         if (ret != LDB_SUCCESS) {
317                 return ret;
318         }
319
320         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
321         if (sid == NULL) {
322                 return ldb_module_oom(ac->module);
323         }
324
325         if ( ! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
326                 return ldb_operr(ldb);
327         }
328
329         return samldb_next_step(ac);
330 }
331
332 /*
333   see if a krbtgt_number is available
334  */
335 static bool samldb_krbtgtnumber_available(struct samldb_ctx *ac, unsigned krbtgt_number)
336 {
337         TALLOC_CTX *tmp_ctx = talloc_new(ac);
338         struct ldb_result *res;
339         const char *attrs[] = { NULL };
340         int ret;
341
342         ret = dsdb_module_search(ac->module, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE,
343                                  attrs, DSDB_FLAG_NEXT_MODULE,
344                                  "msDC-SecondaryKrbTgtNumber=%u", krbtgt_number);
345         if (ret == LDB_SUCCESS && res->count == 0) {
346                 talloc_free(tmp_ctx);
347                 return true;
348         }
349         talloc_free(tmp_ctx);
350         return false;
351 }
352
353 /* special handling for add in RODC join */
354 static int samldb_rodc_add(struct samldb_ctx *ac)
355 {
356         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
357         unsigned krbtgt_number, i_start, i;
358         int ret;
359
360         /* find a unused msDC-SecondaryKrbTgtNumber */
361         i_start = generate_random() & 0xFFFF;
362         if (i_start == 0) {
363                 i_start = 1;
364         }
365
366         for (i=i_start; i<=0xFFFF; i++) {
367                 if (samldb_krbtgtnumber_available(ac, i)) {
368                         krbtgt_number = i;
369                         goto found;
370                 }
371         }
372         for (i=1; i<i_start; i++) {
373                 if (samldb_krbtgtnumber_available(ac, i)) {
374                         krbtgt_number = i;
375                         goto found;
376                 }
377         }
378
379         ldb_asprintf_errstring(ldb_module_get_ctx(ac->module),
380                                "%08X: Unable to find available msDS-SecondaryKrbTgtNumber",
381                                W_ERROR_V(WERR_NO_SYSTEM_RESOURCES));
382         return LDB_ERR_OTHER;
383
384 found:
385         ret = ldb_msg_add_empty(ac->msg, "msDS-SecondaryKrbTgtNumber", LDB_FLAG_INTERNAL_DISABLE_VALIDATION, NULL);
386         if (ret != LDB_SUCCESS) {
387                 return ldb_operr(ldb);
388         }
389
390         ret = ldb_msg_add_fmt(ac->msg, "msDS-SecondaryKrbTgtNumber", "%u", krbtgt_number);
391         if (ret != LDB_SUCCESS) {
392                 return ldb_operr(ldb);
393         }
394
395         ret = ldb_msg_add_fmt(ac->msg, "sAMAccountName", "krbtgt_%u", krbtgt_number);
396         if (ret != LDB_SUCCESS) {
397                 return ldb_operr(ldb);
398         }
399
400         return samldb_next_step(ac);
401 }
402
403
404 /*
405  * samldb_find_for_defaultObjectCategory (async)
406  */
407
408 static int samldb_find_for_defaultObjectCategory_callback(struct ldb_request *req,
409                                                           struct ldb_reply *ares)
410 {
411         struct ldb_context *ldb;
412         struct samldb_ctx *ac;
413         int ret;
414
415         ac = talloc_get_type(req->context, struct samldb_ctx);
416         ldb = ldb_module_get_ctx(ac->module);
417
418         if (!ares) {
419                 ret = LDB_ERR_OPERATIONS_ERROR;
420                 goto done;
421         }
422         if (ares->error != LDB_SUCCESS) {
423                 if (ares->error == LDB_ERR_NO_SUCH_OBJECT) {
424                         if (ldb_request_get_control(ac->req,
425                                                     LDB_CONTROL_RELAX_OID) != NULL) {
426                                 /* Don't be pricky when the DN doesn't exist */
427                                 /* if we have the RELAX control specified */
428                                 ac->res_dn = req->op.search.base;
429                                 return samldb_next_step(ac);
430                         } else {
431                                 ldb_set_errstring(ldb,
432                                         "samldb_find_defaultObjectCategory: "
433                                         "Invalid DN for 'defaultObjectCategory'!");
434                                 ares->error = LDB_ERR_CONSTRAINT_VIOLATION;
435                         }
436                 }
437
438                 return ldb_module_done(ac->req, ares->controls,
439                                        ares->response, ares->error);
440         }
441
442         switch (ares->type) {
443         case LDB_REPLY_ENTRY:
444                 ac->res_dn = talloc_steal(ac, ares->message->dn);
445
446                 ret = LDB_SUCCESS;
447                 break;
448
449         case LDB_REPLY_REFERRAL:
450                 /* ignore */
451                 talloc_free(ares);
452                 ret = LDB_SUCCESS;
453                 break;
454
455         case LDB_REPLY_DONE:
456                 talloc_free(ares);
457
458                 if (ac->res_dn != NULL) {
459                         /* when found go on */
460                         ret = samldb_next_step(ac);
461                 } else {
462                         ret = LDB_ERR_OPERATIONS_ERROR;
463                 }
464                 break;
465         }
466
467 done:
468         if (ret != LDB_SUCCESS) {
469                 return ldb_module_done(ac->req, NULL, NULL, ret);
470         }
471
472         return LDB_SUCCESS;
473 }
474
475 static int samldb_find_for_defaultObjectCategory(struct samldb_ctx *ac)
476 {
477         struct ldb_context *ldb;
478         struct ldb_request *req;
479         static const char *no_attrs[] = { NULL };
480         int ret;
481
482         ldb = ldb_module_get_ctx(ac->module);
483
484         ac->res_dn = NULL;
485
486         ret = ldb_build_search_req(&req, ldb, ac,
487                                    ac->dn, LDB_SCOPE_BASE,
488                                    "(objectClass=classSchema)", no_attrs,
489                                    NULL, ac,
490                                    samldb_find_for_defaultObjectCategory_callback,
491                                    ac->req);
492         if (ret != LDB_SUCCESS) {
493                 return ret;
494         }
495
496         ret = dsdb_request_add_controls(req,
497                                         DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT);
498         if (ret != LDB_SUCCESS) {
499                 return ret;
500         }
501
502         return ldb_next_request(ac->module, req);
503 }
504
505 /**
506  * msDS-IntId attributeSchema attribute handling
507  * during LDB_ADD request processing
508  */
509 static int samldb_add_handle_msDS_IntId(struct samldb_ctx *ac)
510 {
511         int ret;
512         bool id_exists;
513         uint32_t msds_intid;
514         uint32_t system_flags;
515         struct ldb_context *ldb;
516         struct ldb_result *ldb_res;
517         struct ldb_dn *schema_dn;
518
519         ldb = ldb_module_get_ctx(ac->module);
520         schema_dn = ldb_get_schema_basedn(ldb);
521
522         /* replicated update should always go through */
523         if (ldb_request_get_control(ac->req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
524                 return LDB_SUCCESS;
525         }
526
527         /* msDS-IntId is handled by system and should never be
528          * passed by clients */
529         if (ldb_msg_find_element(ac->msg, "msDS-IntId")) {
530                 return LDB_ERR_UNWILLING_TO_PERFORM;
531         }
532
533         /* do not generate msDS-IntId if Relax control is passed */
534         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
535                 return LDB_SUCCESS;
536         }
537
538         /* check Functional Level */
539         if (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003) {
540                 return LDB_SUCCESS;
541         }
542
543         /* check systemFlags for SCHEMA_BASE_OBJECT flag */
544         system_flags = ldb_msg_find_attr_as_uint(ac->msg, "systemFlags", 0);
545         if (system_flags & SYSTEM_FLAG_SCHEMA_BASE_OBJECT) {
546                 return LDB_SUCCESS;
547         }
548
549         /* Generate new value for msDs-IntId
550          * Value should be in 0x80000000..0xBFFFFFFF range */
551         msds_intid = generate_random() % 0X3FFFFFFF;
552         msds_intid += 0x80000000;
553
554         /* probe id values until unique one is found */
555         do {
556                 msds_intid++;
557                 if (msds_intid > 0xBFFFFFFF) {
558                         msds_intid = 0x80000001;
559                 }
560
561                 ret = dsdb_module_search(ac->module, ac,
562                                          &ldb_res,
563                                          schema_dn, LDB_SCOPE_ONELEVEL, NULL,
564                                          DSDB_FLAG_NEXT_MODULE,
565                                          "(msDS-IntId=%d)", msds_intid);
566                 if (ret != LDB_SUCCESS) {
567                         ldb_debug_set(ldb, LDB_DEBUG_ERROR,
568                                       __location__": Searching for msDS-IntId=%d failed - %s\n",
569                                       msds_intid,
570                                       ldb_errstring(ldb));
571                         return ldb_operr(ldb);
572                 }
573                 id_exists = (ldb_res->count > 0);
574
575                 talloc_free(ldb_res);
576         } while(id_exists);
577
578         return ldb_msg_add_fmt(ac->msg, "msDS-IntId", "%d", msds_intid);
579 }
580
581
582 /*
583  * samldb_add_entry (async)
584  */
585
586 static int samldb_add_entry_callback(struct ldb_request *req,
587                                         struct ldb_reply *ares)
588 {
589         struct ldb_context *ldb;
590         struct samldb_ctx *ac;
591         int ret;
592
593         ac = talloc_get_type(req->context, struct samldb_ctx);
594         ldb = ldb_module_get_ctx(ac->module);
595
596         if (!ares) {
597                 return ldb_module_done(ac->req, NULL, NULL,
598                                         LDB_ERR_OPERATIONS_ERROR);
599         }
600
601         if (ares->type == LDB_REPLY_REFERRAL) {
602                 return ldb_module_send_referral(ac->req, ares->referral);
603         }
604
605         if (ares->error != LDB_SUCCESS) {
606                 return ldb_module_done(ac->req, ares->controls,
607                                         ares->response, ares->error);
608         }
609         if (ares->type != LDB_REPLY_DONE) {
610                 ldb_set_errstring(ldb,
611                         "Invalid reply type!\n");
612                 return ldb_module_done(ac->req, NULL, NULL,
613                                         LDB_ERR_OPERATIONS_ERROR);
614         }
615
616         /* The caller may wish to get controls back from the add */
617         ac->ares = talloc_steal(ac, ares);
618
619         ret = samldb_next_step(ac);
620         if (ret != LDB_SUCCESS) {
621                 return ldb_module_done(ac->req, NULL, NULL, ret);
622         }
623         return ret;
624 }
625
626 static int samldb_add_entry(struct samldb_ctx *ac)
627 {
628         struct ldb_context *ldb;
629         struct ldb_request *req;
630         int ret;
631
632         ldb = ldb_module_get_ctx(ac->module);
633
634         ret = ldb_build_add_req(&req, ldb, ac,
635                                 ac->msg,
636                                 ac->req->controls,
637                                 ac, samldb_add_entry_callback,
638                                 ac->req);
639         if (ret != LDB_SUCCESS) {
640                 return ret;
641         }
642
643         return ldb_next_request(ac->module, req);
644 }
645
646 /*
647  * return true if msg carries an attributeSchema that is intended to be RODC
648  * filtered but is also a system-critical attribute.
649  */
650 static bool check_rodc_critical_attribute(struct ldb_message *msg)
651 {
652         uint32_t schemaFlagsEx, searchFlags, rodc_filtered_flags;
653
654         schemaFlagsEx = ldb_msg_find_attr_as_uint(msg, "schemaFlagsEx", 0);
655         searchFlags = ldb_msg_find_attr_as_uint(msg, "searchFlags", 0);
656         rodc_filtered_flags = (SEARCH_FLAG_RODC_ATTRIBUTE | SEARCH_FLAG_CONFIDENTIAL);
657
658         if ((schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) &&
659                 ((searchFlags & rodc_filtered_flags) == rodc_filtered_flags)) {
660                 return true;
661         } else {
662                 return false;
663         }
664 }
665
666
667 static int samldb_fill_object(struct samldb_ctx *ac, const char *type)
668 {
669         struct ldb_context *ldb;
670         struct loadparm_context *lp_ctx;
671         enum sid_generator sid_generator;
672         int ret;
673         struct ldb_control *rodc_control;
674         struct dom_sid *sid;
675
676         ldb = ldb_module_get_ctx(ac->module);
677
678         /* Add informations for the different account types */
679         ac->type = type;
680         if (strcmp(ac->type, "user") == 0) {
681                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
682                         "userAccountControl", "546");
683                 if (ret != LDB_SUCCESS) return ret;
684                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
685                         "badPwdCount", "0");
686                 if (ret != LDB_SUCCESS) return ret;
687                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
688                         "codePage", "0");
689                 if (ret != LDB_SUCCESS) return ret;
690                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
691                         "countryCode", "0");
692                 if (ret != LDB_SUCCESS) return ret;
693                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
694                         "badPasswordTime", "0");
695                 if (ret != LDB_SUCCESS) return ret;
696                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
697                         "lastLogoff", "0");
698                 if (ret != LDB_SUCCESS) return ret;
699                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
700                         "lastLogon", "0");
701                 if (ret != LDB_SUCCESS) return ret;
702                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
703                         "pwdLastSet", "0");
704                 if (ret != LDB_SUCCESS) return ret;
705                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
706                         "accountExpires", "9223372036854775807");
707                 if (ret != LDB_SUCCESS) return ret;
708                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
709                         "logonCount", "0");
710                 if (ret != LDB_SUCCESS) return ret;
711         } else if (strcmp(ac->type, "group") == 0) {
712                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
713                         "groupType", "-2147483646");
714                 if (ret != LDB_SUCCESS) return ret;
715         } else if (strcmp(ac->type, "classSchema") == 0) {
716                 const struct ldb_val *rdn_value, *def_obj_cat_val;
717
718                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
719                                                   "rdnAttId", "cn");
720                 if (ret != LDB_SUCCESS) return ret;
721
722                 /* do not allow to mark an attributeSchema as RODC filtered if it
723                  * is system-critical */
724                 if (check_rodc_critical_attribute(ac->msg)) {
725                         ldb_asprintf_errstring(ldb, "Refusing schema add of %s - cannot combine critical class with RODC filtering",
726                                                ldb_dn_get_linearized(ac->msg->dn));
727                         return LDB_ERR_UNWILLING_TO_PERFORM;
728                 }
729
730
731                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
732                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
733                         /* the RDN has prefix "CN" */
734                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
735                                 samdb_cn_to_lDAPDisplayName(ac,
736                                         (const char *) rdn_value->data));
737                         if (ret != LDB_SUCCESS) {
738                                 ldb_oom(ldb);
739                                 return ret;
740                         }
741                 }
742
743                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
744                         struct GUID guid;
745                         /* a new GUID */
746                         guid = GUID_random();
747                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
748                         if (ret != LDB_SUCCESS) {
749                                 ldb_oom(ldb);
750                                 return ret;
751                         }
752                 }
753
754                 def_obj_cat_val = ldb_msg_find_ldb_val(ac->msg,
755                                                        "defaultObjectCategory");
756                 if (def_obj_cat_val != NULL) {
757                         /* "defaultObjectCategory" has been set by the caller.
758                          * Do some checks for consistency.
759                          * NOTE: The real constraint check (that
760                          * 'defaultObjectCategory' is the DN of the new
761                          * objectclass or any parent of it) is still incomplete.
762                          * For now we say that 'defaultObjectCategory' is valid
763                          * if it exists and it is of objectclass "classSchema".
764                          */
765                         ac->dn = ldb_dn_from_ldb_val(ac, ldb, def_obj_cat_val);
766                         if (ac->dn == NULL) {
767                                 ldb_set_errstring(ldb,
768                                                   "Invalid DN for 'defaultObjectCategory'!");
769                                 return LDB_ERR_CONSTRAINT_VIOLATION;
770                         }
771                 } else {
772                         /* "defaultObjectCategory" has not been set by the
773                          * caller. Use the entry DN for it. */
774                         ac->dn = ac->msg->dn;
775
776                         ret = samdb_msg_add_string(ldb, ac, ac->msg,
777                                                    "defaultObjectCategory",
778                                                    ldb_dn_get_linearized(ac->dn));
779                         if (ret != LDB_SUCCESS) {
780                                 ldb_oom(ldb);
781                                 return ret;
782                         }
783                 }
784
785                 ret = samldb_add_step(ac, samldb_add_entry);
786                 if (ret != LDB_SUCCESS) return ret;
787
788                 /* Now perform the checks for the 'defaultObjectCategory'. The
789                  * lookup DN was already saved in "ac->dn" */
790                 ret = samldb_add_step(ac, samldb_find_for_defaultObjectCategory);
791                 if (ret != LDB_SUCCESS) return ret;
792
793                 return samldb_first_step(ac);
794         } else if (strcmp(ac->type, "attributeSchema") == 0) {
795                 const struct ldb_val *rdn_value;
796                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
797                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
798                         /* the RDN has prefix "CN" */
799                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
800                                 samdb_cn_to_lDAPDisplayName(ac,
801                                         (const char *) rdn_value->data));
802                         if (ret != LDB_SUCCESS) {
803                                 ldb_oom(ldb);
804                                 return ret;
805                         }
806                 }
807
808                 /* do not allow to mark an attributeSchema as RODC filtered if it
809                  * is system-critical */
810                 if (check_rodc_critical_attribute(ac->msg)) {
811                         ldb_asprintf_errstring(ldb, "Refusing schema add of %s - cannot combine critical attribute with RODC filtering",
812                                                ldb_dn_get_linearized(ac->msg->dn));
813                         return LDB_ERR_UNWILLING_TO_PERFORM;
814                 }
815
816                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
817                                                   "isSingleValued", "FALSE");
818                 if (ret != LDB_SUCCESS) return ret;
819
820                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
821                         struct GUID guid;
822                         /* a new GUID */
823                         guid = GUID_random();
824                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
825                         if (ret != LDB_SUCCESS) {
826                                 ldb_oom(ldb);
827                                 return ret;
828                         }
829                 }
830
831                 /* handle msDS-IntID attribute */
832                 ret = samldb_add_handle_msDS_IntId(ac);
833                 if (ret != LDB_SUCCESS) return ret;
834
835                 ret = samldb_add_step(ac, samldb_add_entry);
836                 if (ret != LDB_SUCCESS) return ret;
837
838                 return samldb_first_step(ac);
839         } else {
840                 ldb_asprintf_errstring(ldb,
841                         "Invalid entry type!");
842                 return LDB_ERR_OPERATIONS_ERROR;
843         }
844
845         rodc_control = ldb_request_get_control(ac->req, LDB_CONTROL_RODC_DCPROMO_OID);
846         if (rodc_control) {
847                 /* see [MS-ADTS] 3.1.1.3.4.1.23 LDAP_SERVER_RODC_DCPROMO_OID */
848                 rodc_control->critical = false;
849                 ret = samldb_add_step(ac, samldb_rodc_add);
850                 if (ret != LDB_SUCCESS) return ret;
851         }
852
853         /* check if we have a valid sAMAccountName */
854         ret = samldb_add_step(ac, samldb_check_sAMAccountName);
855         if (ret != LDB_SUCCESS) return ret;
856
857         /* check account_type/group_type */
858         ret = samldb_add_step(ac, samldb_check_sAMAccountType);
859         if (ret != LDB_SUCCESS) return ret;
860
861         /* check if we have a valid primary group ID */
862         if (strcmp(ac->type, "user") == 0) {
863                 ret = samldb_add_step(ac, samldb_check_primaryGroupID);
864                 if (ret != LDB_SUCCESS) return ret;
865         }
866
867         lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
868                  struct loadparm_context);
869
870         /* don't allow objectSID to be specified without the RELAX control */
871         sid = samdb_result_dom_sid(ac, ac->msg, "objectSid");
872         if (sid && !ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) &&
873             !dsdb_module_am_system(ac->module)) {
874                 ldb_asprintf_errstring(ldb, "No SID may be specified in user/group creation for %s",
875                                        ldb_dn_get_linearized(ac->msg->dn));
876                 return LDB_ERR_UNWILLING_TO_PERFORM;
877         }
878
879         if (sid == NULL) {
880                 sid_generator = lpcfg_sid_generator(lp_ctx);
881                 if (sid_generator == SID_GENERATOR_INTERNAL) {
882                         ret = samldb_add_step(ac, samldb_allocate_sid);
883                         if (ret != LDB_SUCCESS) return ret;
884                 }
885         }
886
887         /* finally proceed with adding the entry */
888         ret = samldb_add_step(ac, samldb_add_entry);
889         if (ret != LDB_SUCCESS) return ret;
890
891         return samldb_first_step(ac);
892 }
893
894 static int samldb_fill_foreignSecurityPrincipal_object(struct samldb_ctx *ac)
895 {
896         struct ldb_context *ldb;
897         struct dom_sid *sid;
898         int ret;
899
900         ldb = ldb_module_get_ctx(ac->module);
901
902         sid = samdb_result_dom_sid(ac->msg, ac->msg, "objectSid");
903         if (sid == NULL) {
904                 sid = dom_sid_parse_talloc(ac->msg,
905                                            (const char *)ldb_dn_get_rdn_val(ac->msg->dn)->data);
906                 if (sid == NULL) {
907                         ldb_set_errstring(ldb,
908                                         "No valid SID found in "
909                                         "ForeignSecurityPrincipal CN!");
910                         return LDB_ERR_CONSTRAINT_VIOLATION;
911                 }
912                 if (! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
913                         return ldb_operr(ldb);
914                 }
915         }
916
917         /* finally proceed with adding the entry */
918         ret = samldb_add_step(ac, samldb_add_entry);
919         if (ret != LDB_SUCCESS) return ret;
920
921         return samldb_first_step(ac);
922 }
923
924 static int samldb_schema_info_update(struct samldb_ctx *ac)
925 {
926         WERROR werr;
927         struct ldb_context *ldb;
928         struct dsdb_schema *schema;
929
930         /* replicated update should always go through */
931         if (ldb_request_get_control(ac->req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
932                 return LDB_SUCCESS;
933         }
934
935         /* do not update schemaInfo during provisioning */
936         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
937                 return LDB_SUCCESS;
938         }
939
940         ldb = ldb_module_get_ctx(ac->module);
941         schema = dsdb_get_schema(ldb, NULL);
942         if (!schema) {
943                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
944                               "samldb_schema_info_update: no dsdb_schema loaded");
945                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
946                 return ldb_operr(ldb);
947         }
948
949         werr = dsdb_module_schema_info_update(ac->module, schema, DSDB_FLAG_NEXT_MODULE);
950         if (!W_ERROR_IS_OK(werr)) {
951                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
952                               "samldb_schema_info_update: "
953                               "dsdb_module_schema_info_update failed with %s",
954                               win_errstr(werr));
955                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
956                 return ldb_operr(ldb);
957         }
958
959         return LDB_SUCCESS;
960 }
961
962
963 static int samldb_prim_group_change(struct samldb_ctx *ac)
964 {
965         struct ldb_context *ldb;
966         const char * attrs[] = { "primaryGroupID", "memberOf", NULL };
967         struct ldb_result *res;
968         struct ldb_message_element *el;
969         struct ldb_message *msg;
970         uint32_t rid;
971         struct dom_sid *sid;
972         struct ldb_dn *prev_prim_group_dn, *new_prim_group_dn;
973         int ret;
974
975         ldb = ldb_module_get_ctx(ac->module);
976
977         /* Fetch informations from the existing object */
978
979         ret = ldb_search(ldb, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
980                          NULL);
981         if (ret != LDB_SUCCESS) {
982                 return ret;
983         }
984
985         /* Finds out the DN of the old primary group */
986
987         rid = samdb_result_uint(res->msgs[0], "primaryGroupID", (uint32_t) -1);
988         if (rid == (uint32_t) -1) {
989                 /* User objects do always have a mandatory "primaryGroupID"
990                  * attribute. If this doesn't exist then the object is of the
991                  * wrong type. This is the exact Windows error code */
992                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
993         }
994
995         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
996         if (sid == NULL) {
997                 return ldb_operr(ldb);
998         }
999
1000         prev_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSID=%s)",
1001                                              dom_sid_string(ac, sid));
1002         if (prev_prim_group_dn == NULL) {
1003                 return ldb_operr(ldb);
1004         }
1005
1006         /* Finds out the DN of the new primary group */
1007
1008         rid = samdb_result_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1009         if (rid == (uint32_t) -1) {
1010                 /* we aren't affected of any primary group change */
1011                 return LDB_SUCCESS;
1012         }
1013
1014         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1015         if (sid == NULL) {
1016                 return ldb_operr(ldb);
1017         }
1018
1019         new_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSID=%s)",
1020                                             dom_sid_string(ac, sid));
1021         if (new_prim_group_dn == NULL) {
1022                 /* Here we know if the specified new primary group candidate is
1023                  * valid or not. */
1024                 return LDB_ERR_UNWILLING_TO_PERFORM;
1025         }
1026
1027         /* Only update the "member" attributes when we really do have a change */
1028         if (ldb_dn_compare(new_prim_group_dn, prev_prim_group_dn) != 0) {
1029                 /* We need to be already a normal member of the new primary
1030                  * group in order to be successful. */
1031                 el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1032                                           ldb_dn_get_linearized(new_prim_group_dn));
1033                 if (el == NULL) {
1034                         return LDB_ERR_UNWILLING_TO_PERFORM;
1035                 }
1036
1037                 /* Remove the "member" attribute on the new primary group */
1038                 msg = talloc_zero(ac, struct ldb_message);
1039                 msg->dn = new_prim_group_dn;
1040
1041                 ret = samdb_msg_add_delval(ldb, ac, msg, "member",
1042                                            ldb_dn_get_linearized(ac->msg->dn));
1043                 if (ret != LDB_SUCCESS) {
1044                         return ret;
1045                 }
1046
1047                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1048                 if (ret != LDB_SUCCESS) {
1049                         return ret;
1050                 }
1051
1052                 /* Add a "member" attribute for the previous primary group */
1053                 msg = talloc_zero(ac, struct ldb_message);
1054                 msg->dn = prev_prim_group_dn;
1055
1056                 ret = samdb_msg_add_addval(ldb, ac, msg, "member",
1057                                            ldb_dn_get_linearized(ac->msg->dn));
1058                 if (ret != LDB_SUCCESS) {
1059                         return ret;
1060                 }
1061
1062                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1063                 if (ret != LDB_SUCCESS) {
1064                         return ret;
1065                 }
1066         }
1067
1068         return LDB_SUCCESS;
1069 }
1070
1071
1072 static int samldb_member_check(struct samldb_ctx *ac)
1073 {
1074         struct ldb_context *ldb;
1075         struct ldb_message_element *el;
1076         struct ldb_dn *member_dn, *group_dn;
1077         uint32_t prim_group_rid;
1078         struct dom_sid *sid;
1079         unsigned int i;
1080
1081         ldb = ldb_module_get_ctx(ac->module);
1082
1083         el = ldb_msg_find_element(ac->msg, "member");
1084         if (el == NULL) {
1085                 /* we aren't affected */
1086                 return LDB_SUCCESS;
1087         }
1088
1089         for (i = 0; i < el->num_values; i++) {
1090                 /* Denies to add "member"s to groups which are primary ones
1091                  * for them */
1092                 member_dn = ldb_dn_from_ldb_val(ac, ldb, &el->values[i]);
1093                 if (!ldb_dn_validate(member_dn)) {
1094                         return ldb_operr(ldb);
1095                 }
1096
1097                 prim_group_rid = samdb_search_uint(ldb, ac, (uint32_t) -1,
1098                                                    member_dn, "primaryGroupID",
1099                                                    NULL);
1100                 if (prim_group_rid == (uint32_t) -1) {
1101                         /* the member hasn't to be a user account -> therefore
1102                          * no check needed in this case. */
1103                         continue;
1104                 }
1105
1106                 sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
1107                                       prim_group_rid);
1108                 if (sid == NULL) {
1109                         return ldb_operr(ldb);
1110                 }
1111
1112                 group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSID=%s)",
1113                                            dom_sid_string(ac, sid));
1114                 if (group_dn == NULL) {
1115                         return ldb_operr(ldb);
1116                 }
1117
1118                 if (ldb_dn_compare(group_dn, ac->msg->dn) == 0) {
1119                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
1120                 }
1121         }
1122
1123         return LDB_SUCCESS;
1124 }
1125
1126
1127 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
1128 {
1129         struct ldb_context *ldb;
1130         struct dom_sid *sid;
1131         uint32_t rid;
1132         NTSTATUS status;
1133         int count;
1134
1135         ldb = ldb_module_get_ctx(ac->module);
1136
1137         /* Finds out the SID/RID of the SAM object */
1138         sid = samdb_search_dom_sid(ldb, ac, ac->req->op.del.dn, "objectSID",
1139                                    NULL);
1140         if (sid == NULL) {
1141                 /* No SID - it might not be a SAM object - therefore ok */
1142                 return LDB_SUCCESS;
1143         }
1144         status = dom_sid_split_rid(ac, sid, NULL, &rid);
1145         if (!NT_STATUS_IS_OK(status)) {
1146                 return ldb_operr(ldb);
1147         }
1148         if (rid == 0) {
1149                 /* Special object (security principal?) */
1150                 return LDB_SUCCESS;
1151         }
1152
1153         /* Deny delete requests from groups which are primary ones */
1154         count = samdb_search_count(ldb, NULL,
1155                                    "(&(primaryGroupID=%u)(objectClass=user))",
1156                                    rid);
1157         if (count < 0) {
1158                 return ldb_operr(ldb);
1159         }
1160         if (count > 0) {
1161                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1162         }
1163
1164         return LDB_SUCCESS;
1165 }
1166
1167
1168 /* add */
1169 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
1170 {
1171         struct ldb_context *ldb;
1172         struct samldb_ctx *ac;
1173         int ret;
1174
1175         ldb = ldb_module_get_ctx(module);
1176         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
1177
1178         /* do not manipulate our control entries */
1179         if (ldb_dn_is_special(req->op.add.message->dn)) {
1180                 return ldb_next_request(module, req);
1181         }
1182
1183         ac = samldb_ctx_init(module, req);
1184         if (ac == NULL) {
1185                 return ldb_operr(ldb);
1186         }
1187
1188         /* build the new msg */
1189         ac->msg = ldb_msg_copy(ac, ac->req->op.add.message);
1190         if (!ac->msg) {
1191                 talloc_free(ac);
1192                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1193                           "samldb_add: ldb_msg_copy failed!\n");
1194                 return ldb_operr(ldb);
1195         }
1196
1197         if (samdb_find_attribute(ldb, ac->msg,
1198                                  "objectclass", "user") != NULL) {
1199                 return samldb_fill_object(ac, "user");
1200         }
1201
1202         if (samdb_find_attribute(ldb, ac->msg,
1203                                  "objectclass", "group") != NULL) {
1204                 return samldb_fill_object(ac, "group");
1205         }
1206
1207         /* perhaps a foreignSecurityPrincipal? */
1208         if (samdb_find_attribute(ldb, ac->msg,
1209                                  "objectclass",
1210                                  "foreignSecurityPrincipal") != NULL) {
1211                 return samldb_fill_foreignSecurityPrincipal_object(ac);
1212         }
1213
1214         if (samdb_find_attribute(ldb, ac->msg,
1215                                  "objectclass", "classSchema") != NULL) {
1216                 ret = samldb_schema_info_update(ac);
1217                 if (ret != LDB_SUCCESS) {
1218                         talloc_free(ac);
1219                         return ret;
1220                 }
1221
1222                 return samldb_fill_object(ac, "classSchema");
1223         }
1224
1225         if (samdb_find_attribute(ldb, ac->msg,
1226                                  "objectclass", "attributeSchema") != NULL) {
1227                 ret = samldb_schema_info_update(ac);
1228                 if (ret != LDB_SUCCESS) {
1229                         talloc_free(ac);
1230                         return ret;
1231                 }
1232
1233                 return samldb_fill_object(ac, "attributeSchema");
1234         }
1235
1236         talloc_free(ac);
1237
1238         /* nothing matched, go on */
1239         return ldb_next_request(module, req);
1240 }
1241
1242 /* modify */
1243 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
1244 {
1245         struct ldb_context *ldb;
1246         struct samldb_ctx *ac;
1247         struct ldb_message *msg;
1248         struct ldb_message_element *el, *el2;
1249         int ret;
1250         uint32_t account_type;
1251
1252         if (ldb_dn_is_special(req->op.mod.message->dn)) {
1253                 /* do not manipulate our control entries */
1254                 return ldb_next_request(module, req);
1255         }
1256
1257         ldb = ldb_module_get_ctx(module);
1258
1259         if (ldb_msg_find_element(req->op.mod.message, "sAMAccountType") != NULL) {
1260                 ldb_asprintf_errstring(ldb,
1261                         "sAMAccountType must not be specified!");
1262                 return LDB_ERR_UNWILLING_TO_PERFORM;
1263         }
1264
1265         /* msDS-IntId is not allowed to be modified
1266          * except when modification comes from replication */
1267         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
1268                 if (!ldb_request_get_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
1269                         return LDB_ERR_CONSTRAINT_VIOLATION;
1270                 }
1271         }
1272
1273         ac = samldb_ctx_init(module, req);
1274         if (ac == NULL) {
1275                 return ldb_operr(ldb);
1276         }
1277
1278         /* TODO: do not modify original request, create a new one */
1279
1280         el = ldb_msg_find_element(req->op.mod.message, "groupType");
1281         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1282                 uint32_t group_type;
1283
1284                 req->op.mod.message = msg = ldb_msg_copy_shallow(req,
1285                         req->op.mod.message);
1286
1287                 group_type = strtoul((const char *)el->values[0].data, NULL, 0);
1288                 account_type =  ds_gtype2atype(group_type);
1289                 ret = samdb_msg_add_uint(ldb, msg, msg,
1290                                          "sAMAccountType",
1291                                          account_type);
1292                 if (ret != LDB_SUCCESS) {
1293                         return ret;
1294                 }
1295                 el2 = ldb_msg_find_element(msg, "sAMAccountType");
1296                 el2->flags = LDB_FLAG_MOD_REPLACE;
1297         }
1298         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1299                 return LDB_ERR_UNWILLING_TO_PERFORM;
1300         }
1301
1302         el = ldb_msg_find_element(req->op.mod.message, "primaryGroupID");
1303         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1304                 req->op.mod.message = ac->msg = ldb_msg_copy_shallow(req,
1305                         req->op.mod.message);
1306
1307                 ret = samldb_prim_group_change(ac);
1308                 if (ret != LDB_SUCCESS) {
1309                         return ret;
1310                 }
1311         }
1312         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1313                 return LDB_ERR_UNWILLING_TO_PERFORM;
1314         }
1315
1316         el = ldb_msg_find_element(req->op.mod.message, "userAccountControl");
1317         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1318                 uint32_t user_account_control;
1319
1320                 req->op.mod.message = msg = ldb_msg_copy_shallow(req,
1321                         req->op.mod.message);
1322
1323                 user_account_control = strtoul((const char *)el->values[0].data,
1324                         NULL, 0);
1325                 account_type = ds_uf2atype(user_account_control);
1326                 ret = samdb_msg_add_uint(ldb, msg, msg,
1327                                          "sAMAccountType",
1328                                          account_type);
1329                 if (ret != LDB_SUCCESS) {
1330                         return ret;
1331                 }
1332                 el2 = ldb_msg_find_element(msg, "sAMAccountType");
1333                 el2->flags = LDB_FLAG_MOD_REPLACE;
1334
1335                 if (user_account_control & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1336                         ret = samdb_msg_add_string(ldb, msg, msg,
1337                                                    "isCriticalSystemObject", "TRUE");
1338                         if (ret != LDB_SUCCESS) {
1339                                 return ret;
1340                         }
1341                         el2 = ldb_msg_find_element(msg, "isCriticalSystemObject");
1342                         el2->flags = LDB_FLAG_MOD_REPLACE;
1343
1344                         /* DCs have primaryGroupID of DOMAIN_RID_DCS */
1345                         if (!ldb_msg_find_element(msg, "primaryGroupID")) {
1346                                 uint32_t rid;
1347                                 if (user_account_control & UF_SERVER_TRUST_ACCOUNT) {
1348                                         rid = DOMAIN_RID_DCS;
1349                                 } else {
1350                                         /* read-only DC */
1351                                         rid = DOMAIN_RID_READONLY_DCS;
1352                                 }
1353                                 ret = samdb_msg_add_uint(ldb, msg, msg,
1354                                                          "primaryGroupID", rid);
1355                                 if (ret != LDB_SUCCESS) {
1356                                         return ret;
1357                                 }
1358                                 el2 = ldb_msg_find_element(msg, "primaryGroupID");
1359                                 el2->flags = LDB_FLAG_MOD_REPLACE;
1360                         }
1361                 }
1362         }
1363         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1364                 return LDB_ERR_UNWILLING_TO_PERFORM;
1365         }
1366
1367         el = ldb_msg_find_element(req->op.mod.message, "member");
1368         if (el && el->flags & (LDB_FLAG_MOD_ADD|LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1369                 req->op.mod.message = ac->msg = ldb_msg_copy_shallow(req,
1370                         req->op.mod.message);
1371
1372                 ret = samldb_member_check(ac);
1373                 if (ret != LDB_SUCCESS) {
1374                         return ret;
1375                 }
1376         }
1377
1378         return ldb_next_request(module, req);
1379 }
1380
1381 /* delete */
1382 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
1383 {
1384         struct samldb_ctx *ac;
1385         int ret;
1386
1387         if (ldb_dn_is_special(req->op.del.dn)) {
1388                 /* do not manipulate our control entries */
1389                 return ldb_next_request(module, req);
1390         }
1391
1392         ac = samldb_ctx_init(module, req);
1393         if (ac == NULL)
1394                 return ldb_operr(ldb_module_get_ctx(module));
1395
1396         ret = samldb_prim_group_users_check(ac);
1397         if (ret != LDB_SUCCESS) {
1398                 return ret;
1399         }
1400
1401         return ldb_next_request(module, req);
1402 }
1403
1404 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
1405 {
1406         struct ldb_context *ldb = ldb_module_get_ctx(module);
1407         struct dsdb_fsmo_extended_op *exop;
1408         int ret;
1409
1410         exop = talloc_get_type(req->op.extended.data, struct dsdb_fsmo_extended_op);
1411         if (!exop) {
1412                 ldb_debug(ldb, LDB_DEBUG_FATAL, "samldb_extended_allocate_rid_pool: invalid extended data\n");
1413                 return LDB_ERR_PROTOCOL_ERROR;
1414         }
1415
1416         ret = ridalloc_allocate_rid_pool_fsmo(module, exop);
1417         if (ret != LDB_SUCCESS) {
1418                 return ret;
1419         }
1420
1421         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1422 }
1423
1424 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
1425 {
1426         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
1427                 return samldb_extended_allocate_rid_pool(module, req);
1428         }
1429
1430         return ldb_next_request(module, req);
1431 }
1432
1433
1434 _PUBLIC_ const struct ldb_module_ops ldb_samldb_module_ops = {
1435         .name          = "samldb",
1436         .add           = samldb_add,
1437         .modify        = samldb_modify,
1438         .del           = samldb_delete,
1439         .extended      = samldb_extended
1440 };
1441