s4:samldb LDB module - get rid of the SID context variable
[metze/samba/wip.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 static bool samldb_msg_add_sid(struct ldb_message *msg,
254                                 const char *name,
255                                 const struct dom_sid *sid)
256 {
257         struct ldb_val v;
258         enum ndr_err_code ndr_err;
259
260         ndr_err = ndr_push_struct_blob(&v, msg, sid,
261                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
262         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
263                 return false;
264         }
265         return (ldb_msg_add_value(msg, name, &v, NULL) == 0);
266 }
267
268
269 /* allocate a SID using our RID Set */
270 static int samldb_allocate_sid(struct samldb_ctx *ac)
271 {
272         uint32_t rid;
273         struct dom_sid *sid;
274         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
275         int ret;
276
277         ret = ridalloc_allocate_rid(ac->module, &rid);
278         if (ret != LDB_SUCCESS) {
279                 return ret;
280         }
281
282         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
283         if (sid == NULL) {
284                 return ldb_module_oom(ac->module);
285         }
286
287         if ( ! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
288                 return ldb_operr(ldb);
289         }
290
291         return samldb_next_step(ac);
292 }
293
294 /*
295   see if a krbtgt_number is available
296  */
297 static bool samldb_krbtgtnumber_available(struct samldb_ctx *ac, unsigned krbtgt_number)
298 {
299         TALLOC_CTX *tmp_ctx = talloc_new(ac);
300         struct ldb_result *res;
301         const char *attrs[] = { NULL };
302         int ret;
303
304         ret = dsdb_module_search(ac->module, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE,
305                                  attrs, DSDB_FLAG_NEXT_MODULE,
306                                  "msDC-SecondaryKrbTgtNumber=%u", krbtgt_number);
307         if (ret == LDB_SUCCESS && res->count == 0) {
308                 talloc_free(tmp_ctx);
309                 return true;
310         }
311         talloc_free(tmp_ctx);
312         return false;
313 }
314
315 /* special handling for add in RODC join */
316 static int samldb_rodc_add(struct samldb_ctx *ac)
317 {
318         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
319         unsigned krbtgt_number, i_start, i;
320         int ret;
321
322         /* find a unused msDC-SecondaryKrbTgtNumber */
323         i_start = generate_random() & 0xFFFF;
324         if (i_start == 0) {
325                 i_start = 1;
326         }
327
328         for (i=i_start; i<=0xFFFF; i++) {
329                 if (samldb_krbtgtnumber_available(ac, i)) {
330                         krbtgt_number = i;
331                         goto found;
332                 }
333         }
334         for (i=1; i<i_start; i++) {
335                 if (samldb_krbtgtnumber_available(ac, i)) {
336                         krbtgt_number = i;
337                         goto found;
338                 }
339         }
340
341         ldb_asprintf_errstring(ldb_module_get_ctx(ac->module),
342                                "%08X: Unable to find available msDS-SecondaryKrbTgtNumber",
343                                W_ERROR_V(WERR_NO_SYSTEM_RESOURCES));
344         return LDB_ERR_OTHER;
345
346 found:
347         ret = ldb_msg_add_empty(ac->msg, "msDS-SecondaryKrbTgtNumber", LDB_FLAG_INTERNAL_DISABLE_VALIDATION, NULL);
348         if (ret != LDB_SUCCESS) {
349                 return ldb_operr(ldb);
350         }
351
352         ret = ldb_msg_add_fmt(ac->msg, "msDS-SecondaryKrbTgtNumber", "%u", krbtgt_number);
353         if (ret != LDB_SUCCESS) {
354                 return ldb_operr(ldb);
355         }
356
357         ret = ldb_msg_add_fmt(ac->msg, "sAMAccountName", "krbtgt_%u", krbtgt_number);
358         if (ret != LDB_SUCCESS) {
359                 return ldb_operr(ldb);
360         }
361
362         return samldb_next_step(ac);
363 }
364
365 /*
366  * samldb_dn_from_sid (async)
367  */
368
369 static int samldb_dn_from_sid(struct samldb_ctx *ac);
370
371 static int samldb_dn_from_sid_callback(struct ldb_request *req,
372         struct ldb_reply *ares)
373 {
374         struct ldb_context *ldb;
375         struct samldb_ctx *ac;
376         int ret;
377
378         ac = talloc_get_type(req->context, struct samldb_ctx);
379         ldb = ldb_module_get_ctx(ac->module);
380
381         if (!ares) {
382                 ret = LDB_ERR_OPERATIONS_ERROR;
383                 goto done;
384         }
385         if (ares->error != LDB_SUCCESS) {
386                 return ldb_module_done(ac->req, ares->controls,
387                                         ares->response, ares->error);
388         }
389
390         switch (ares->type) {
391         case LDB_REPLY_ENTRY:
392                 /* save entry */
393                 if (ac->res_dn != NULL) {
394                         /* one too many! */
395                         ldb_set_errstring(ldb,
396                                 "Invalid number of results while searching "
397                                 "for domain objects!");
398                         ret = LDB_ERR_OPERATIONS_ERROR;
399                         break;
400                 }
401                 ac->res_dn = ldb_dn_copy(ac, ares->message->dn);
402
403                 talloc_free(ares);
404                 ret = LDB_SUCCESS;
405                 break;
406
407         case LDB_REPLY_REFERRAL:
408                 /* ignore */
409                 talloc_free(ares);
410                 ret = LDB_SUCCESS;
411                 break;
412
413         case LDB_REPLY_DONE:
414                 talloc_free(ares);
415
416                 /* found or not found, go on */
417                 ret = samldb_next_step(ac);
418                 break;
419         }
420
421 done:
422         if (ret != LDB_SUCCESS) {
423                 return ldb_module_done(ac->req, NULL, NULL, ret);
424         }
425
426         return LDB_SUCCESS;
427 }
428
429 /* Finds the DN "res_dn" of an object with a given SID "sid" */
430 static int samldb_dn_from_sid(struct samldb_ctx *ac)
431 {
432         struct ldb_context *ldb;
433         static const char * const attrs[] = { NULL };
434         struct ldb_request *req;
435         char *filter;
436         int ret;
437
438         ldb = ldb_module_get_ctx(ac->module);
439
440         if (ac->sid == NULL)
441                 return ldb_operr(ldb);
442
443         filter = talloc_asprintf(ac, "(objectSid=%s)",
444                 ldap_encode_ndr_dom_sid(ac, ac->sid));
445         if (filter == NULL)
446                 return ldb_oom(ldb);
447
448         ret = ldb_build_search_req(&req, ldb, ac,
449                                 ldb_get_default_basedn(ldb),
450                                 LDB_SCOPE_SUBTREE,
451                                 filter, attrs,
452                                 NULL,
453                                 ac, samldb_dn_from_sid_callback,
454                                 ac->req);
455         if (ret != LDB_SUCCESS)
456                 return ret;
457
458         return ldb_next_request(ac->module, req);
459 }
460
461
462 static int samldb_check_primaryGroupID_1(struct samldb_ctx *ac)
463 {
464         struct ldb_context *ldb;
465         uint32_t rid;
466
467         ldb = ldb_module_get_ctx(ac->module);
468
469         rid = samdb_result_uint(ac->msg, "primaryGroupID", ~0);
470         ac->sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
471         if (ac->sid == NULL)
472                 return ldb_operr(ldb);
473         ac->res_dn = NULL;
474
475         return samldb_next_step(ac);
476 }
477
478 static int samldb_check_primaryGroupID_2(struct samldb_ctx *ac)
479 {
480         if (ac->res_dn == NULL) {
481                 struct ldb_context *ldb;
482                 ldb = ldb_module_get_ctx(ac->module);
483                 ldb_asprintf_errstring(ldb,
484                                        "Failed to find group sid %s!",
485                                        dom_sid_string(ac->sid, ac->sid));
486                 return LDB_ERR_UNWILLING_TO_PERFORM;
487         }
488
489         return samldb_next_step(ac);
490 }
491
492
493 /*
494  * samldb_find_for_defaultObjectCategory (async)
495  */
496
497 static int samldb_find_for_defaultObjectCategory_callback(struct ldb_request *req,
498                                                           struct ldb_reply *ares)
499 {
500         struct ldb_context *ldb;
501         struct samldb_ctx *ac;
502         int ret;
503
504         ac = talloc_get_type(req->context, struct samldb_ctx);
505         ldb = ldb_module_get_ctx(ac->module);
506
507         if (!ares) {
508                 ret = LDB_ERR_OPERATIONS_ERROR;
509                 goto done;
510         }
511         if (ares->error != LDB_SUCCESS) {
512                 if (ares->error == LDB_ERR_NO_SUCH_OBJECT) {
513                         if (ldb_request_get_control(ac->req,
514                                                     LDB_CONTROL_RELAX_OID) != NULL) {
515                                 /* Don't be pricky when the DN doesn't exist */
516                                 /* if we have the RELAX control specified */
517                                 ac->res_dn = req->op.search.base;
518                                 return samldb_next_step(ac);
519                         } else {
520                                 ldb_set_errstring(ldb,
521                                         "samldb_find_defaultObjectCategory: "
522                                         "Invalid DN for 'defaultObjectCategory'!");
523                                 ares->error = LDB_ERR_CONSTRAINT_VIOLATION;
524                         }
525                 }
526
527                 return ldb_module_done(ac->req, ares->controls,
528                                        ares->response, ares->error);
529         }
530
531         switch (ares->type) {
532         case LDB_REPLY_ENTRY:
533                 ac->res_dn = talloc_steal(ac, ares->message->dn);
534
535                 ret = LDB_SUCCESS;
536                 break;
537
538         case LDB_REPLY_REFERRAL:
539                 /* ignore */
540                 talloc_free(ares);
541                 ret = LDB_SUCCESS;
542                 break;
543
544         case LDB_REPLY_DONE:
545                 talloc_free(ares);
546
547                 if (ac->res_dn != NULL) {
548                         /* when found go on */
549                         ret = samldb_next_step(ac);
550                 } else {
551                         ret = LDB_ERR_OPERATIONS_ERROR;
552                 }
553                 break;
554         }
555
556 done:
557         if (ret != LDB_SUCCESS) {
558                 return ldb_module_done(ac->req, NULL, NULL, ret);
559         }
560
561         return LDB_SUCCESS;
562 }
563
564 static int samldb_find_for_defaultObjectCategory(struct samldb_ctx *ac)
565 {
566         struct ldb_context *ldb;
567         struct ldb_request *req;
568         static const char *no_attrs[] = { NULL };
569         int ret;
570
571         ldb = ldb_module_get_ctx(ac->module);
572
573         ac->res_dn = NULL;
574
575         ret = ldb_build_search_req(&req, ldb, ac,
576                                    ac->dn, LDB_SCOPE_BASE,
577                                    "(objectClass=classSchema)", no_attrs,
578                                    NULL, ac,
579                                    samldb_find_for_defaultObjectCategory_callback,
580                                    ac->req);
581         if (ret != LDB_SUCCESS) {
582                 return ret;
583         }
584
585         ret = dsdb_request_add_controls(req,
586                                         DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT);
587         if (ret != LDB_SUCCESS) {
588                 return ret;
589         }
590
591         return ldb_next_request(ac->module, req);
592 }
593
594 /**
595  * msDS-IntId attributeSchema attribute handling
596  * during LDB_ADD request processing
597  */
598 static int samldb_add_handle_msDS_IntId(struct samldb_ctx *ac)
599 {
600         int ret;
601         bool id_exists;
602         uint32_t msds_intid;
603         uint32_t system_flags;
604         struct ldb_context *ldb;
605         struct ldb_result *ldb_res;
606         struct ldb_dn *schema_dn;
607
608         ldb = ldb_module_get_ctx(ac->module);
609         schema_dn = ldb_get_schema_basedn(ldb);
610
611         /* replicated update should always go through */
612         if (ldb_request_get_control(ac->req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
613                 return LDB_SUCCESS;
614         }
615
616         /* msDS-IntId is handled by system and should never be
617          * passed by clients */
618         if (ldb_msg_find_element(ac->msg, "msDS-IntId")) {
619                 return LDB_ERR_UNWILLING_TO_PERFORM;
620         }
621
622         /* do not generate msDS-IntId if Relax control is passed */
623         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
624                 return LDB_SUCCESS;
625         }
626
627         /* check Functional Level */
628         if (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003) {
629                 return LDB_SUCCESS;
630         }
631
632         /* check systemFlags for SCHEMA_BASE_OBJECT flag */
633         system_flags = ldb_msg_find_attr_as_uint(ac->msg, "systemFlags", 0);
634         if (system_flags & SYSTEM_FLAG_SCHEMA_BASE_OBJECT) {
635                 return LDB_SUCCESS;
636         }
637
638         /* Generate new value for msDs-IntId
639          * Value should be in 0x80000000..0xBFFFFFFF range */
640         msds_intid = generate_random() % 0X3FFFFFFF;
641         msds_intid += 0x80000000;
642
643         /* probe id values until unique one is found */
644         do {
645                 msds_intid++;
646                 if (msds_intid > 0xBFFFFFFF) {
647                         msds_intid = 0x80000001;
648                 }
649
650                 ret = dsdb_module_search(ac->module, ac,
651                                          &ldb_res,
652                                          schema_dn, LDB_SCOPE_ONELEVEL, NULL,
653                                          DSDB_FLAG_NEXT_MODULE,
654                                          "(msDS-IntId=%d)", msds_intid);
655                 if (ret != LDB_SUCCESS) {
656                         ldb_debug_set(ldb, LDB_DEBUG_ERROR,
657                                       __location__": Searching for msDS-IntId=%d failed - %s\n",
658                                       msds_intid,
659                                       ldb_errstring(ldb));
660                         return ldb_operr(ldb);
661                 }
662                 id_exists = (ldb_res->count > 0);
663
664                 talloc_free(ldb_res);
665         } while(id_exists);
666
667         return ldb_msg_add_fmt(ac->msg, "msDS-IntId", "%d", msds_intid);
668 }
669
670
671 /*
672  * samldb_add_entry (async)
673  */
674
675 static int samldb_add_entry_callback(struct ldb_request *req,
676                                         struct ldb_reply *ares)
677 {
678         struct ldb_context *ldb;
679         struct samldb_ctx *ac;
680         int ret;
681
682         ac = talloc_get_type(req->context, struct samldb_ctx);
683         ldb = ldb_module_get_ctx(ac->module);
684
685         if (!ares) {
686                 return ldb_module_done(ac->req, NULL, NULL,
687                                         LDB_ERR_OPERATIONS_ERROR);
688         }
689
690         if (ares->type == LDB_REPLY_REFERRAL) {
691                 return ldb_module_send_referral(ac->req, ares->referral);
692         }
693
694         if (ares->error != LDB_SUCCESS) {
695                 return ldb_module_done(ac->req, ares->controls,
696                                         ares->response, ares->error);
697         }
698         if (ares->type != LDB_REPLY_DONE) {
699                 ldb_set_errstring(ldb,
700                         "Invalid reply type!\n");
701                 return ldb_module_done(ac->req, NULL, NULL,
702                                         LDB_ERR_OPERATIONS_ERROR);
703         }
704
705         /* The caller may wish to get controls back from the add */
706         ac->ares = talloc_steal(ac, ares);
707
708         ret = samldb_next_step(ac);
709         if (ret != LDB_SUCCESS) {
710                 return ldb_module_done(ac->req, NULL, NULL, ret);
711         }
712         return ret;
713 }
714
715 static int samldb_add_entry(struct samldb_ctx *ac)
716 {
717         struct ldb_context *ldb;
718         struct ldb_request *req;
719         int ret;
720
721         ldb = ldb_module_get_ctx(ac->module);
722
723         ret = ldb_build_add_req(&req, ldb, ac,
724                                 ac->msg,
725                                 ac->req->controls,
726                                 ac, samldb_add_entry_callback,
727                                 ac->req);
728         if (ret != LDB_SUCCESS) {
729                 return ret;
730         }
731
732         return ldb_next_request(ac->module, req);
733 }
734
735 /*
736  * return true if msg carries an attributeSchema that is intended to be RODC
737  * filtered but is also a system-critical attribute.
738  */
739 static bool check_rodc_critical_attribute(struct ldb_message *msg)
740 {
741         uint32_t schemaFlagsEx, searchFlags, rodc_filtered_flags;
742
743         schemaFlagsEx = ldb_msg_find_attr_as_uint(msg, "schemaFlagsEx", 0);
744         searchFlags = ldb_msg_find_attr_as_uint(msg, "searchFlags", 0);
745         rodc_filtered_flags = (SEARCH_FLAG_RODC_ATTRIBUTE | SEARCH_FLAG_CONFIDENTIAL);
746
747         if ((schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) &&
748                 ((searchFlags & rodc_filtered_flags) == rodc_filtered_flags)) {
749                 return true;
750         } else {
751                 return false;
752         }
753 }
754
755
756 static int samldb_fill_object(struct samldb_ctx *ac, const char *type)
757 {
758         struct ldb_context *ldb;
759         struct loadparm_context *lp_ctx;
760         enum sid_generator sid_generator;
761         int ret;
762         struct ldb_control *rodc_control;
763         struct dom_sid *sid;
764
765         ldb = ldb_module_get_ctx(ac->module);
766
767         /* Add informations for the different account types */
768         ac->type = type;
769         if (strcmp(ac->type, "user") == 0) {
770                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
771                         "userAccountControl", "546");
772                 if (ret != LDB_SUCCESS) return ret;
773                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
774                         "badPwdCount", "0");
775                 if (ret != LDB_SUCCESS) return ret;
776                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
777                         "codePage", "0");
778                 if (ret != LDB_SUCCESS) return ret;
779                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
780                         "countryCode", "0");
781                 if (ret != LDB_SUCCESS) return ret;
782                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
783                         "badPasswordTime", "0");
784                 if (ret != LDB_SUCCESS) return ret;
785                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
786                         "lastLogoff", "0");
787                 if (ret != LDB_SUCCESS) return ret;
788                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
789                         "lastLogon", "0");
790                 if (ret != LDB_SUCCESS) return ret;
791                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
792                         "pwdLastSet", "0");
793                 if (ret != LDB_SUCCESS) return ret;
794                 if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
795                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
796                                                  "primaryGroupID", DOMAIN_RID_USERS);
797                         if (ret != LDB_SUCCESS) return ret;
798                 }
799                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
800                         "accountExpires", "9223372036854775807");
801                 if (ret != LDB_SUCCESS) return ret;
802                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
803                         "logonCount", "0");
804                 if (ret != LDB_SUCCESS) return ret;
805         } else if (strcmp(ac->type, "group") == 0) {
806                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
807                         "groupType", "-2147483646");
808                 if (ret != LDB_SUCCESS) return ret;
809         } else if (strcmp(ac->type, "classSchema") == 0) {
810                 const struct ldb_val *rdn_value, *def_obj_cat_val;
811
812                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
813                                                   "rdnAttId", "cn");
814                 if (ret != LDB_SUCCESS) return ret;
815
816                 /* do not allow to mark an attributeSchema as RODC filtered if it
817                  * is system-critical */
818                 if (check_rodc_critical_attribute(ac->msg)) {
819                         ldb_asprintf_errstring(ldb, "Refusing schema add of %s - cannot combine critical class with RODC filtering",
820                                                ldb_dn_get_linearized(ac->msg->dn));
821                         return LDB_ERR_UNWILLING_TO_PERFORM;
822                 }
823
824
825                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
826                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
827                         /* the RDN has prefix "CN" */
828                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
829                                 samdb_cn_to_lDAPDisplayName(ac,
830                                         (const char *) rdn_value->data));
831                         if (ret != LDB_SUCCESS) {
832                                 ldb_oom(ldb);
833                                 return ret;
834                         }
835                 }
836
837                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
838                         struct GUID guid;
839                         /* a new GUID */
840                         guid = GUID_random();
841                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
842                         if (ret != LDB_SUCCESS) {
843                                 ldb_oom(ldb);
844                                 return ret;
845                         }
846                 }
847
848                 def_obj_cat_val = ldb_msg_find_ldb_val(ac->msg,
849                                                        "defaultObjectCategory");
850                 if (def_obj_cat_val != NULL) {
851                         /* "defaultObjectCategory" has been set by the caller.
852                          * Do some checks for consistency.
853                          * NOTE: The real constraint check (that
854                          * 'defaultObjectCategory' is the DN of the new
855                          * objectclass or any parent of it) is still incomplete.
856                          * For now we say that 'defaultObjectCategory' is valid
857                          * if it exists and it is of objectclass "classSchema".
858                          */
859                         ac->dn = ldb_dn_from_ldb_val(ac, ldb, def_obj_cat_val);
860                         if (ac->dn == NULL) {
861                                 ldb_set_errstring(ldb,
862                                                   "Invalid DN for 'defaultObjectCategory'!");
863                                 return LDB_ERR_CONSTRAINT_VIOLATION;
864                         }
865                 } else {
866                         /* "defaultObjectCategory" has not been set by the
867                          * caller. Use the entry DN for it. */
868                         ac->dn = ac->msg->dn;
869
870                         ret = samdb_msg_add_string(ldb, ac, ac->msg,
871                                                    "defaultObjectCategory",
872                                                    ldb_dn_get_linearized(ac->dn));
873                         if (ret != LDB_SUCCESS) {
874                                 ldb_oom(ldb);
875                                 return ret;
876                         }
877                 }
878
879                 ret = samldb_add_step(ac, samldb_add_entry);
880                 if (ret != LDB_SUCCESS) return ret;
881
882                 /* Now perform the checks for the 'defaultObjectCategory'. The
883                  * lookup DN was already saved in "ac->dn" */
884                 ret = samldb_add_step(ac, samldb_find_for_defaultObjectCategory);
885                 if (ret != LDB_SUCCESS) return ret;
886
887                 return samldb_first_step(ac);
888         } else if (strcmp(ac->type, "attributeSchema") == 0) {
889                 const struct ldb_val *rdn_value;
890                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
891                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
892                         /* the RDN has prefix "CN" */
893                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
894                                 samdb_cn_to_lDAPDisplayName(ac,
895                                         (const char *) rdn_value->data));
896                         if (ret != LDB_SUCCESS) {
897                                 ldb_oom(ldb);
898                                 return ret;
899                         }
900                 }
901
902                 /* do not allow to mark an attributeSchema as RODC filtered if it
903                  * is system-critical */
904                 if (check_rodc_critical_attribute(ac->msg)) {
905                         ldb_asprintf_errstring(ldb, "Refusing schema add of %s - cannot combine critical attribute with RODC filtering",
906                                                ldb_dn_get_linearized(ac->msg->dn));
907                         return LDB_ERR_UNWILLING_TO_PERFORM;
908                 }
909
910                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
911                                                   "isSingleValued", "FALSE");
912                 if (ret != LDB_SUCCESS) return ret;
913
914                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
915                         struct GUID guid;
916                         /* a new GUID */
917                         guid = GUID_random();
918                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
919                         if (ret != LDB_SUCCESS) {
920                                 ldb_oom(ldb);
921                                 return ret;
922                         }
923                 }
924
925                 /* handle msDS-IntID attribute */
926                 ret = samldb_add_handle_msDS_IntId(ac);
927                 if (ret != LDB_SUCCESS) return ret;
928
929                 ret = samldb_add_step(ac, samldb_add_entry);
930                 if (ret != LDB_SUCCESS) return ret;
931
932                 return samldb_first_step(ac);
933         } else {
934                 ldb_asprintf_errstring(ldb,
935                         "Invalid entry type!");
936                 return LDB_ERR_OPERATIONS_ERROR;
937         }
938
939         rodc_control = ldb_request_get_control(ac->req, LDB_CONTROL_RODC_DCPROMO_OID);
940         if (rodc_control) {
941                 /* see [MS-ADTS] 3.1.1.3.4.1.23 LDAP_SERVER_RODC_DCPROMO_OID */
942                 rodc_control->critical = false;
943                 ret = samldb_add_step(ac, samldb_rodc_add);
944                 if (ret != LDB_SUCCESS) return ret;
945         }
946
947         /* check if we have a valid sAMAccountName */
948         ret = samldb_add_step(ac, samldb_check_sAMAccountName);
949         if (ret != LDB_SUCCESS) return ret;
950
951         /* check account_type/group_type */
952         ret = samldb_add_step(ac, samldb_check_sAMAccountType);
953         if (ret != LDB_SUCCESS) return ret;
954
955         /* check if we have a valid primary group ID */
956         if (strcmp(ac->type, "user") == 0) {
957                 ret = samldb_add_step(ac, samldb_check_primaryGroupID_1);
958                 if (ret != LDB_SUCCESS) return ret;
959                 ret = samldb_add_step(ac, samldb_dn_from_sid);
960                 if (ret != LDB_SUCCESS) return ret;
961                 ret = samldb_add_step(ac, samldb_check_primaryGroupID_2);
962                 if (ret != LDB_SUCCESS) return ret;
963         }
964
965         lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
966                  struct loadparm_context);
967
968         /* don't allow objectSID to be specified without the RELAX control */
969         sid = samdb_result_dom_sid(ac, ac->msg, "objectSid");
970         if (sid && !ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) &&
971             !dsdb_module_am_system(ac->module)) {
972                 ldb_asprintf_errstring(ldb, "No SID may be specified in user/group creation for %s",
973                                        ldb_dn_get_linearized(ac->msg->dn));
974                 return LDB_ERR_UNWILLING_TO_PERFORM;
975         }
976
977         if (sid == NULL) {
978                 sid_generator = lpcfg_sid_generator(lp_ctx);
979                 if (sid_generator == SID_GENERATOR_INTERNAL) {
980                         ret = samldb_add_step(ac, samldb_allocate_sid);
981                         if (ret != LDB_SUCCESS) return ret;
982                 }
983         }
984
985         /* finally proceed with adding the entry */
986         ret = samldb_add_step(ac, samldb_add_entry);
987         if (ret != LDB_SUCCESS) return ret;
988
989         return samldb_first_step(ac);
990 }
991
992 static int samldb_fill_foreignSecurityPrincipal_object(struct samldb_ctx *ac)
993 {
994         struct ldb_context *ldb;
995         struct dom_sid *sid;
996         int ret;
997
998         ldb = ldb_module_get_ctx(ac->module);
999
1000         sid = samdb_result_dom_sid(ac->msg, ac->msg, "objectSid");
1001         if (sid == NULL) {
1002                 sid = dom_sid_parse_talloc(ac->msg,
1003                                            (const char *)ldb_dn_get_rdn_val(ac->msg->dn)->data);
1004                 if (sid == NULL) {
1005                         ldb_set_errstring(ldb,
1006                                         "No valid SID found in "
1007                                         "ForeignSecurityPrincipal CN!");
1008                         return LDB_ERR_CONSTRAINT_VIOLATION;
1009                 }
1010                 if (! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
1011                         return ldb_operr(ldb);
1012                 }
1013         }
1014
1015         /* finally proceed with adding the entry */
1016         ret = samldb_add_step(ac, samldb_add_entry);
1017         if (ret != LDB_SUCCESS) return ret;
1018
1019         return samldb_first_step(ac);
1020 }
1021
1022 static int samldb_schema_info_update(struct samldb_ctx *ac)
1023 {
1024         WERROR werr;
1025         struct ldb_context *ldb;
1026         struct dsdb_schema *schema;
1027
1028         /* replicated update should always go through */
1029         if (ldb_request_get_control(ac->req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
1030                 return LDB_SUCCESS;
1031         }
1032
1033         /* do not update schemaInfo during provisioning */
1034         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
1035                 return LDB_SUCCESS;
1036         }
1037
1038         ldb = ldb_module_get_ctx(ac->module);
1039         schema = dsdb_get_schema(ldb, NULL);
1040         if (!schema) {
1041                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
1042                               "samldb_schema_info_update: no dsdb_schema loaded");
1043                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
1044                 return ldb_operr(ldb);
1045         }
1046
1047         werr = dsdb_module_schema_info_update(ac->module, schema, DSDB_FLAG_NEXT_MODULE);
1048         if (!W_ERROR_IS_OK(werr)) {
1049                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
1050                               "samldb_schema_info_update: "
1051                               "dsdb_module_schema_info_update failed with %s",
1052                               win_errstr(werr));
1053                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
1054                 return ldb_operr(ldb);
1055         }
1056
1057         return LDB_SUCCESS;
1058 }
1059
1060
1061 static int samldb_prim_group_change(struct samldb_ctx *ac)
1062 {
1063         struct ldb_context *ldb;
1064         const char * attrs[] = { "primaryGroupID", "memberOf", NULL };
1065         struct ldb_result *res;
1066         struct ldb_message_element *el;
1067         struct ldb_message *msg;
1068         uint32_t rid;
1069         struct dom_sid *sid;
1070         struct ldb_dn *prev_prim_group_dn, *new_prim_group_dn;
1071         int ret;
1072
1073         ldb = ldb_module_get_ctx(ac->module);
1074
1075         /* Fetch informations from the existing object */
1076
1077         ret = ldb_search(ldb, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1078                          NULL);
1079         if (ret != LDB_SUCCESS) {
1080                 return ret;
1081         }
1082
1083         /* Finds out the DN of the old primary group */
1084
1085         rid = samdb_result_uint(res->msgs[0], "primaryGroupID", (uint32_t) -1);
1086         if (rid == (uint32_t) -1) {
1087                 /* User objects do always have a mandatory "primaryGroupID"
1088                  * attribute. If this doesn't exist then the object is of the
1089                  * wrong type. This is the exact Windows error code */
1090                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1091         }
1092
1093         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1094         if (sid == NULL) {
1095                 return ldb_operr(ldb);
1096         }
1097
1098         prev_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSID=%s)",
1099                                              dom_sid_string(ac, sid));
1100         if (prev_prim_group_dn == NULL) {
1101                 return ldb_operr(ldb);
1102         }
1103
1104         /* Finds out the DN of the new primary group */
1105
1106         rid = samdb_result_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1107         if (rid == (uint32_t) -1) {
1108                 /* we aren't affected of any primary group change */
1109                 return LDB_SUCCESS;
1110         }
1111
1112         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1113         if (sid == NULL) {
1114                 return ldb_operr(ldb);
1115         }
1116
1117         new_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSID=%s)",
1118                                             dom_sid_string(ac, sid));
1119         if (new_prim_group_dn == NULL) {
1120                 /* Here we know if the specified new primary group candidate is
1121                  * valid or not. */
1122                 return LDB_ERR_UNWILLING_TO_PERFORM;
1123         }
1124
1125         /* Only update the "member" attributes when we really do have a change */
1126         if (ldb_dn_compare(new_prim_group_dn, prev_prim_group_dn) != 0) {
1127                 /* We need to be already a normal member of the new primary
1128                  * group in order to be successful. */
1129                 el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1130                                           ldb_dn_get_linearized(new_prim_group_dn));
1131                 if (el == NULL) {
1132                         return LDB_ERR_UNWILLING_TO_PERFORM;
1133                 }
1134
1135                 /* Remove the "member" attribute on the new primary group */
1136                 msg = talloc_zero(ac, struct ldb_message);
1137                 msg->dn = new_prim_group_dn;
1138
1139                 ret = samdb_msg_add_delval(ldb, ac, msg, "member",
1140                                            ldb_dn_get_linearized(ac->msg->dn));
1141                 if (ret != LDB_SUCCESS) {
1142                         return ret;
1143                 }
1144
1145                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1146                 if (ret != LDB_SUCCESS) {
1147                         return ret;
1148                 }
1149
1150                 /* Add a "member" attribute for the previous primary group */
1151                 msg = talloc_zero(ac, struct ldb_message);
1152                 msg->dn = prev_prim_group_dn;
1153
1154                 ret = samdb_msg_add_addval(ldb, ac, msg, "member",
1155                                            ldb_dn_get_linearized(ac->msg->dn));
1156                 if (ret != LDB_SUCCESS) {
1157                         return ret;
1158                 }
1159
1160                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1161                 if (ret != LDB_SUCCESS) {
1162                         return ret;
1163                 }
1164         }
1165
1166         return LDB_SUCCESS;
1167 }
1168
1169
1170 static int samldb_member_check(struct samldb_ctx *ac)
1171 {
1172         struct ldb_context *ldb;
1173         struct ldb_message_element *el;
1174         struct ldb_dn *member_dn, *group_dn;
1175         uint32_t prim_group_rid;
1176         struct dom_sid *sid;
1177         unsigned int i;
1178
1179         ldb = ldb_module_get_ctx(ac->module);
1180
1181         el = ldb_msg_find_element(ac->msg, "member");
1182         if (el == NULL) {
1183                 /* we aren't affected */
1184                 return LDB_SUCCESS;
1185         }
1186
1187         for (i = 0; i < el->num_values; i++) {
1188                 /* Denies to add "member"s to groups which are primary ones
1189                  * for them */
1190                 member_dn = ldb_dn_from_ldb_val(ac, ldb, &el->values[i]);
1191                 if (!ldb_dn_validate(member_dn)) {
1192                         return ldb_operr(ldb);
1193                 }
1194
1195                 prim_group_rid = samdb_search_uint(ldb, ac, (uint32_t) -1,
1196                                                    member_dn, "primaryGroupID",
1197                                                    NULL);
1198                 if (prim_group_rid == (uint32_t) -1) {
1199                         /* the member hasn't to be a user account -> therefore
1200                          * no check needed in this case. */
1201                         continue;
1202                 }
1203
1204                 sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
1205                                       prim_group_rid);
1206                 if (sid == NULL) {
1207                         return ldb_operr(ldb);
1208                 }
1209
1210                 group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSID=%s)",
1211                                            dom_sid_string(ac, sid));
1212                 if (group_dn == NULL) {
1213                         return ldb_operr(ldb);
1214                 }
1215
1216                 if (ldb_dn_compare(group_dn, ac->msg->dn) == 0) {
1217                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
1218                 }
1219         }
1220
1221         return LDB_SUCCESS;
1222 }
1223
1224
1225 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
1226 {
1227         struct ldb_context *ldb;
1228         struct dom_sid *sid;
1229         uint32_t rid;
1230         NTSTATUS status;
1231         int count;
1232
1233         ldb = ldb_module_get_ctx(ac->module);
1234
1235         /* Finds out the SID/RID of the SAM object */
1236         sid = samdb_search_dom_sid(ldb, ac, ac->req->op.del.dn, "objectSID",
1237                                    NULL);
1238         if (sid == NULL) {
1239                 /* No SID - it might not be a SAM object - therefore ok */
1240                 return LDB_SUCCESS;
1241         }
1242         status = dom_sid_split_rid(ac, sid, NULL, &rid);
1243         if (!NT_STATUS_IS_OK(status)) {
1244                 return ldb_operr(ldb);
1245         }
1246         if (rid == 0) {
1247                 /* Special object (security principal?) */
1248                 return LDB_SUCCESS;
1249         }
1250
1251         /* Deny delete requests from groups which are primary ones */
1252         count = samdb_search_count(ldb, NULL,
1253                                    "(&(primaryGroupID=%u)(objectClass=user))",
1254                                    rid);
1255         if (count < 0) {
1256                 return ldb_operr(ldb);
1257         }
1258         if (count > 0) {
1259                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1260         }
1261
1262         return LDB_SUCCESS;
1263 }
1264
1265
1266 /* add */
1267 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
1268 {
1269         struct ldb_context *ldb;
1270         struct samldb_ctx *ac;
1271         int ret;
1272
1273         ldb = ldb_module_get_ctx(module);
1274         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
1275
1276         /* do not manipulate our control entries */
1277         if (ldb_dn_is_special(req->op.add.message->dn)) {
1278                 return ldb_next_request(module, req);
1279         }
1280
1281         ac = samldb_ctx_init(module, req);
1282         if (ac == NULL) {
1283                 return ldb_operr(ldb);
1284         }
1285
1286         /* build the new msg */
1287         ac->msg = ldb_msg_copy(ac, ac->req->op.add.message);
1288         if (!ac->msg) {
1289                 talloc_free(ac);
1290                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1291                           "samldb_add: ldb_msg_copy failed!\n");
1292                 return ldb_operr(ldb);
1293         }
1294
1295         if (samdb_find_attribute(ldb, ac->msg,
1296                                  "objectclass", "user") != NULL) {
1297                 return samldb_fill_object(ac, "user");
1298         }
1299
1300         if (samdb_find_attribute(ldb, ac->msg,
1301                                  "objectclass", "group") != NULL) {
1302                 return samldb_fill_object(ac, "group");
1303         }
1304
1305         /* perhaps a foreignSecurityPrincipal? */
1306         if (samdb_find_attribute(ldb, ac->msg,
1307                                  "objectclass",
1308                                  "foreignSecurityPrincipal") != NULL) {
1309                 return samldb_fill_foreignSecurityPrincipal_object(ac);
1310         }
1311
1312         if (samdb_find_attribute(ldb, ac->msg,
1313                                  "objectclass", "classSchema") != NULL) {
1314                 ret = samldb_schema_info_update(ac);
1315                 if (ret != LDB_SUCCESS) {
1316                         talloc_free(ac);
1317                         return ret;
1318                 }
1319
1320                 return samldb_fill_object(ac, "classSchema");
1321         }
1322
1323         if (samdb_find_attribute(ldb, ac->msg,
1324                                  "objectclass", "attributeSchema") != NULL) {
1325                 ret = samldb_schema_info_update(ac);
1326                 if (ret != LDB_SUCCESS) {
1327                         talloc_free(ac);
1328                         return ret;
1329                 }
1330
1331                 return samldb_fill_object(ac, "attributeSchema");
1332         }
1333
1334         talloc_free(ac);
1335
1336         /* nothing matched, go on */
1337         return ldb_next_request(module, req);
1338 }
1339
1340 /* modify */
1341 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
1342 {
1343         struct ldb_context *ldb;
1344         struct samldb_ctx *ac;
1345         struct ldb_message *msg;
1346         struct ldb_message_element *el, *el2;
1347         int ret;
1348         uint32_t account_type;
1349
1350         if (ldb_dn_is_special(req->op.mod.message->dn)) {
1351                 /* do not manipulate our control entries */
1352                 return ldb_next_request(module, req);
1353         }
1354
1355         ldb = ldb_module_get_ctx(module);
1356
1357         if (ldb_msg_find_element(req->op.mod.message, "sAMAccountType") != NULL) {
1358                 ldb_asprintf_errstring(ldb,
1359                         "sAMAccountType must not be specified!");
1360                 return LDB_ERR_UNWILLING_TO_PERFORM;
1361         }
1362
1363         /* msDS-IntId is not allowed to be modified
1364          * except when modification comes from replication */
1365         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
1366                 if (!ldb_request_get_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
1367                         return LDB_ERR_CONSTRAINT_VIOLATION;
1368                 }
1369         }
1370
1371         ac = samldb_ctx_init(module, req);
1372         if (ac == NULL) {
1373                 return ldb_operr(ldb);
1374         }
1375
1376         /* TODO: do not modify original request, create a new one */
1377
1378         el = ldb_msg_find_element(req->op.mod.message, "groupType");
1379         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1380                 uint32_t group_type;
1381
1382                 req->op.mod.message = msg = ldb_msg_copy_shallow(req,
1383                         req->op.mod.message);
1384
1385                 group_type = strtoul((const char *)el->values[0].data, NULL, 0);
1386                 account_type =  ds_gtype2atype(group_type);
1387                 ret = samdb_msg_add_uint(ldb, msg, msg,
1388                                          "sAMAccountType",
1389                                          account_type);
1390                 if (ret != LDB_SUCCESS) {
1391                         return ret;
1392                 }
1393                 el2 = ldb_msg_find_element(msg, "sAMAccountType");
1394                 el2->flags = LDB_FLAG_MOD_REPLACE;
1395         }
1396         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1397                 return LDB_ERR_UNWILLING_TO_PERFORM;
1398         }
1399
1400         el = ldb_msg_find_element(req->op.mod.message, "primaryGroupID");
1401         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1402                 req->op.mod.message = ac->msg = ldb_msg_copy_shallow(req,
1403                         req->op.mod.message);
1404
1405                 ret = samldb_prim_group_change(ac);
1406                 if (ret != LDB_SUCCESS) {
1407                         return ret;
1408                 }
1409         }
1410         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1411                 return LDB_ERR_UNWILLING_TO_PERFORM;
1412         }
1413
1414         el = ldb_msg_find_element(req->op.mod.message, "userAccountControl");
1415         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1416                 uint32_t user_account_control;
1417
1418                 req->op.mod.message = msg = ldb_msg_copy_shallow(req,
1419                         req->op.mod.message);
1420
1421                 user_account_control = strtoul((const char *)el->values[0].data,
1422                         NULL, 0);
1423                 account_type = ds_uf2atype(user_account_control);
1424                 ret = samdb_msg_add_uint(ldb, msg, msg,
1425                                          "sAMAccountType",
1426                                          account_type);
1427                 if (ret != LDB_SUCCESS) {
1428                         return ret;
1429                 }
1430                 el2 = ldb_msg_find_element(msg, "sAMAccountType");
1431                 el2->flags = LDB_FLAG_MOD_REPLACE;
1432
1433                 if (user_account_control & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1434                         ret = samdb_msg_add_string(ldb, msg, msg,
1435                                                    "isCriticalSystemObject", "TRUE");
1436                         if (ret != LDB_SUCCESS) {
1437                                 return ret;
1438                         }
1439                         el2 = ldb_msg_find_element(msg, "isCriticalSystemObject");
1440                         el2->flags = LDB_FLAG_MOD_REPLACE;
1441
1442                         /* DCs have primaryGroupID of DOMAIN_RID_DCS */
1443                         if (!ldb_msg_find_element(msg, "primaryGroupID")) {
1444                                 uint32_t rid;
1445                                 if (user_account_control & UF_SERVER_TRUST_ACCOUNT) {
1446                                         rid = DOMAIN_RID_DCS;
1447                                 } else {
1448                                         /* read-only DC */
1449                                         rid = DOMAIN_RID_READONLY_DCS;
1450                                 }
1451                                 ret = samdb_msg_add_uint(ldb, msg, msg,
1452                                                          "primaryGroupID", rid);
1453                                 if (ret != LDB_SUCCESS) {
1454                                         return ret;
1455                                 }
1456                                 el2 = ldb_msg_find_element(msg, "primaryGroupID");
1457                                 el2->flags = LDB_FLAG_MOD_REPLACE;
1458                         }
1459                 }
1460         }
1461         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1462                 return LDB_ERR_UNWILLING_TO_PERFORM;
1463         }
1464
1465         el = ldb_msg_find_element(req->op.mod.message, "member");
1466         if (el && el->flags & (LDB_FLAG_MOD_ADD|LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1467                 req->op.mod.message = ac->msg = ldb_msg_copy_shallow(req,
1468                         req->op.mod.message);
1469
1470                 ret = samldb_member_check(ac);
1471                 if (ret != LDB_SUCCESS) {
1472                         return ret;
1473                 }
1474         }
1475
1476         return ldb_next_request(module, req);
1477 }
1478
1479 /* delete */
1480 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
1481 {
1482         struct samldb_ctx *ac;
1483         int ret;
1484
1485         if (ldb_dn_is_special(req->op.del.dn)) {
1486                 /* do not manipulate our control entries */
1487                 return ldb_next_request(module, req);
1488         }
1489
1490         ac = samldb_ctx_init(module, req);
1491         if (ac == NULL)
1492                 return ldb_operr(ldb_module_get_ctx(module));
1493
1494         ret = samldb_prim_group_users_check(ac);
1495         if (ret != LDB_SUCCESS) {
1496                 return ret;
1497         }
1498
1499         return ldb_next_request(module, req);
1500 }
1501
1502 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
1503 {
1504         struct ldb_context *ldb = ldb_module_get_ctx(module);
1505         struct dsdb_fsmo_extended_op *exop;
1506         int ret;
1507
1508         exop = talloc_get_type(req->op.extended.data, struct dsdb_fsmo_extended_op);
1509         if (!exop) {
1510                 ldb_debug(ldb, LDB_DEBUG_FATAL, "samldb_extended_allocate_rid_pool: invalid extended data\n");
1511                 return LDB_ERR_PROTOCOL_ERROR;
1512         }
1513
1514         ret = ridalloc_allocate_rid_pool_fsmo(module, exop);
1515         if (ret != LDB_SUCCESS) {
1516                 return ret;
1517         }
1518
1519         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1520 }
1521
1522 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
1523 {
1524         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
1525                 return samldb_extended_allocate_rid_pool(module, req);
1526         }
1527
1528         return ldb_next_request(module, req);
1529 }
1530
1531
1532 _PUBLIC_ const struct ldb_module_ops ldb_samldb_module_ops = {
1533         .name          = "samldb",
1534         .add           = samldb_add,
1535         .modify        = samldb_modify,
1536         .del           = samldb_delete,
1537         .extended      = samldb_extended
1538 };
1539