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