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