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