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