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