s4:samldb LDB module - "sAMAccountName" checker
[metze/samba/wip.git] / source4 / dsdb / samdb / ldb_modules / samldb.c
1 /*
2    SAM ldb module
3
4    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
5    Copyright (C) Simo Sorce  2004-2008
6    Copyright (C) Matthias Dieter Wallnöfer 2009-2010
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /*
23  *  Name: ldb
24  *
25  *  Component: ldb samldb module
26  *
27  *  Description: various internal DSDB triggers - most for SAM specific objects
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 "dsdb/samdb/ldb_modules/ridalloc.h"
38 #include "libcli/security/security.h"
39 #include "librpc/gen_ndr/ndr_security.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. If someone set an "ares" to forward
136          * 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,
149                                           struct ldb_message *msg)
150 {
151         char *name;
152
153         /* Format: $000000-000000000000 */
154
155         name = talloc_asprintf(msg, "$%.6X-%.6X%.6X",
156                                 (unsigned int)generate_random(),
157                                 (unsigned int)generate_random(),
158                                 (unsigned int)generate_random());
159         if (name == NULL) {
160                 return ldb_oom(ldb);
161         }
162         return ldb_msg_add_steal_string(msg, "sAMAccountName", name);
163 }
164
165 static int samldb_check_sAMAccountName(struct samldb_ctx *ac)
166 {
167         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
168         const char *name;
169         int ret;
170
171         if (ldb_msg_find_element(ac->msg, "sAMAccountName") == NULL) {
172                 ret = samldb_generate_sAMAccountName(ldb, ac->msg);
173                 if (ret != LDB_SUCCESS) {
174                         return ret;
175                 }
176         }
177
178         name = ldb_msg_find_attr_as_string(ac->msg, "sAMAccountName", NULL);
179         if (name == NULL) {
180                 return ldb_operr(ldb);
181         }
182
183         ret = samdb_search_count(ldb, ac, NULL, "(sAMAccountName=%s)",
184                                  ldb_binary_encode_string(ac, name));
185         if ((ret < 0) || (ret > 1)) {
186                 return ldb_operr(ldb);
187         }
188         if (ret == 1) {
189                 ldb_asprintf_errstring(ldb,
190                                        "samldb: Account name (sAMAccountName) '%s' already in use!",
191                                        name);
192                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
193         }
194
195         return samldb_next_step(ac);
196 }
197
198
199 static bool samldb_msg_add_sid(struct ldb_message *msg,
200                                 const char *name,
201                                 const struct dom_sid *sid)
202 {
203         struct ldb_val v;
204         enum ndr_err_code ndr_err;
205
206         ndr_err = ndr_push_struct_blob(&v, msg, sid,
207                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
208         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
209                 return false;
210         }
211         return (ldb_msg_add_value(msg, name, &v, NULL) == 0);
212 }
213
214
215 /* allocate a SID using our RID Set */
216 static int samldb_allocate_sid(struct samldb_ctx *ac)
217 {
218         uint32_t rid;
219         struct dom_sid *sid;
220         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
221         int ret;
222
223         ret = ridalloc_allocate_rid(ac->module, &rid);
224         if (ret != LDB_SUCCESS) {
225                 return ret;
226         }
227
228         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
229         if (sid == NULL) {
230                 return ldb_module_oom(ac->module);
231         }
232
233         if ( ! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
234                 return ldb_operr(ldb);
235         }
236
237         return samldb_next_step(ac);
238 }
239
240 /*
241   see if a krbtgt_number is available
242  */
243 static bool samldb_krbtgtnumber_available(struct samldb_ctx *ac,
244                                           uint32_t krbtgt_number)
245 {
246         TALLOC_CTX *tmp_ctx = talloc_new(ac);
247         struct ldb_result *res;
248         const char *no_attrs[] = { NULL };
249         int ret;
250
251         ret = dsdb_module_search(ac->module, tmp_ctx, &res, NULL,
252                                  LDB_SCOPE_SUBTREE, no_attrs,
253                                  DSDB_FLAG_NEXT_MODULE,
254                                  "(msDC-SecondaryKrbTgtNumber=%u)",
255                                  krbtgt_number);
256         if (ret == LDB_SUCCESS && res->count == 0) {
257                 talloc_free(tmp_ctx);
258                 return true;
259         }
260         talloc_free(tmp_ctx);
261         return false;
262 }
263
264 /* special handling for add in RODC join */
265 static int samldb_rodc_add(struct samldb_ctx *ac)
266 {
267         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
268         uint32_t krbtgt_number, i_start, i;
269         int ret;
270         char *newpass;
271
272         /* find a unused msDC-SecondaryKrbTgtNumber */
273         i_start = generate_random() & 0xFFFF;
274         if (i_start == 0) {
275                 i_start = 1;
276         }
277
278         for (i=i_start; i<=0xFFFF; i++) {
279                 if (samldb_krbtgtnumber_available(ac, i)) {
280                         krbtgt_number = i;
281                         goto found;
282                 }
283         }
284         for (i=1; i<i_start; i++) {
285                 if (samldb_krbtgtnumber_available(ac, i)) {
286                         krbtgt_number = i;
287                         goto found;
288                 }
289         }
290
291         ldb_asprintf_errstring(ldb,
292                                "%08X: Unable to find available msDS-SecondaryKrbTgtNumber",
293                                W_ERROR_V(WERR_NO_SYSTEM_RESOURCES));
294         return LDB_ERR_OTHER;
295
296 found:
297         ret = ldb_msg_add_empty(ac->msg, "msDS-SecondaryKrbTgtNumber",
298                                 LDB_FLAG_INTERNAL_DISABLE_VALIDATION, NULL);
299         if (ret != LDB_SUCCESS) {
300                 return ldb_operr(ldb);
301         }
302
303         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
304                                  "msDS-SecondaryKrbTgtNumber", krbtgt_number);
305         if (ret != LDB_SUCCESS) {
306                 return ldb_operr(ldb);
307         }
308
309         ret = ldb_msg_add_fmt(ac->msg, "sAMAccountName", "krbtgt_%u",
310                               krbtgt_number);
311         if (ret != LDB_SUCCESS) {
312                 return ldb_operr(ldb);
313         }
314
315         newpass = generate_random_password(ac->msg, 128, 255);
316         if (newpass == NULL) {
317                 return ldb_operr(ldb);
318         }
319
320         ret = ldb_msg_add_steal_string(ac->msg, "clearTextPassword", newpass);
321         if (ret != LDB_SUCCESS) {
322                 return ldb_operr(ldb);
323         }
324
325         return samldb_next_step(ac);
326 }
327
328 static int samldb_find_for_defaultObjectCategory(struct samldb_ctx *ac)
329 {
330         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
331         struct ldb_result *res;
332         const char *no_attrs[] = { NULL };
333         int ret;
334
335         ac->res_dn = NULL;
336
337         ret = dsdb_module_search(ac->module, ac, &res,
338                                  ac->dn, LDB_SCOPE_BASE, no_attrs,
339                                  DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT
340                                  | DSDB_FLAG_NEXT_MODULE,
341                                  "(objectClass=classSchema)");
342         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
343                 /* Don't be pricky when the DN doesn't exist if we have the */
344                 /* RELAX control specified */
345                 if (ldb_request_get_control(ac->req,
346                                             LDB_CONTROL_RELAX_OID) == NULL) {
347                         ldb_set_errstring(ldb,
348                                           "samldb_find_defaultObjectCategory: "
349                                           "Invalid DN for 'defaultObjectCategory'!");
350                         return LDB_ERR_CONSTRAINT_VIOLATION;
351                 }
352         }
353         if ((ret != LDB_ERR_NO_SUCH_OBJECT) && (ret != LDB_SUCCESS)) {
354                 return ret;
355         }
356
357         ac->res_dn = ac->dn;
358
359         return samldb_next_step(ac);
360 }
361
362 /**
363  * msDS-IntId attributeSchema attribute handling
364  * during LDB_ADD request processing
365  */
366 static int samldb_add_handle_msDS_IntId(struct samldb_ctx *ac)
367 {
368         int ret;
369         bool id_exists;
370         uint32_t msds_intid;
371         int32_t system_flags;
372         struct ldb_context *ldb;
373         struct ldb_result *ldb_res;
374         struct ldb_dn *schema_dn;
375
376         ldb = ldb_module_get_ctx(ac->module);
377         schema_dn = ldb_get_schema_basedn(ldb);
378
379         /* replicated update should always go through */
380         if (ldb_request_get_control(ac->req,
381                                     DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
382                 return LDB_SUCCESS;
383         }
384
385         /* msDS-IntId is handled by system and should never be
386          * passed by clients */
387         if (ldb_msg_find_element(ac->msg, "msDS-IntId")) {
388                 return LDB_ERR_UNWILLING_TO_PERFORM;
389         }
390
391         /* do not generate msDS-IntId if Relax control is passed */
392         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
393                 return LDB_SUCCESS;
394         }
395
396         /* check Functional Level */
397         if (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003) {
398                 return LDB_SUCCESS;
399         }
400
401         /* check systemFlags for SCHEMA_BASE_OBJECT flag */
402         system_flags = ldb_msg_find_attr_as_int(ac->msg, "systemFlags", 0);
403         if (system_flags & SYSTEM_FLAG_SCHEMA_BASE_OBJECT) {
404                 return LDB_SUCCESS;
405         }
406
407         /* Generate new value for msDs-IntId
408          * Value should be in 0x80000000..0xBFFFFFFF range */
409         msds_intid = generate_random() % 0X3FFFFFFF;
410         msds_intid += 0x80000000;
411
412         /* probe id values until unique one is found */
413         do {
414                 msds_intid++;
415                 if (msds_intid > 0xBFFFFFFF) {
416                         msds_intid = 0x80000001;
417                 }
418
419                 ret = dsdb_module_search(ac->module, ac,
420                                          &ldb_res,
421                                          schema_dn, LDB_SCOPE_ONELEVEL, NULL,
422                                          DSDB_FLAG_NEXT_MODULE,
423                                          "(msDS-IntId=%d)", msds_intid);
424                 if (ret != LDB_SUCCESS) {
425                         ldb_debug_set(ldb, LDB_DEBUG_ERROR,
426                                       __location__": Searching for msDS-IntId=%d failed - %s\n",
427                                       msds_intid,
428                                       ldb_errstring(ldb));
429                         return ldb_operr(ldb);
430                 }
431                 id_exists = (ldb_res->count > 0);
432
433                 talloc_free(ldb_res);
434         } while(id_exists);
435
436         return samdb_msg_add_int(ldb, ac->msg, ac->msg, "msDS-IntId",
437                                  msds_intid);
438 }
439
440
441 /*
442  * samldb_add_entry (async)
443  */
444
445 static int samldb_add_entry_callback(struct ldb_request *req,
446                                         struct ldb_reply *ares)
447 {
448         struct ldb_context *ldb;
449         struct samldb_ctx *ac;
450         int ret;
451
452         ac = talloc_get_type(req->context, struct samldb_ctx);
453         ldb = ldb_module_get_ctx(ac->module);
454
455         if (!ares) {
456                 return ldb_module_done(ac->req, NULL, NULL,
457                                         LDB_ERR_OPERATIONS_ERROR);
458         }
459
460         if (ares->type == LDB_REPLY_REFERRAL) {
461                 return ldb_module_send_referral(ac->req, ares->referral);
462         }
463
464         if (ares->error != LDB_SUCCESS) {
465                 return ldb_module_done(ac->req, ares->controls,
466                                         ares->response, ares->error);
467         }
468         if (ares->type != LDB_REPLY_DONE) {
469                 ldb_set_errstring(ldb,
470                         "Invalid reply type!\n");
471                 return ldb_module_done(ac->req, NULL, NULL,
472                                         LDB_ERR_OPERATIONS_ERROR);
473         }
474
475         /* The caller may wish to get controls back from the add */
476         ac->ares = talloc_steal(ac, ares);
477
478         ret = samldb_next_step(ac);
479         if (ret != LDB_SUCCESS) {
480                 return ldb_module_done(ac->req, NULL, NULL, ret);
481         }
482         return ret;
483 }
484
485 static int samldb_add_entry(struct samldb_ctx *ac)
486 {
487         struct ldb_context *ldb;
488         struct ldb_request *req;
489         int ret;
490
491         ldb = ldb_module_get_ctx(ac->module);
492
493         ret = ldb_build_add_req(&req, ldb, ac,
494                                 ac->msg,
495                                 ac->req->controls,
496                                 ac, samldb_add_entry_callback,
497                                 ac->req);
498         LDB_REQ_SET_LOCATION(req);
499         if (ret != LDB_SUCCESS) {
500                 return ret;
501         }
502
503         return ldb_next_request(ac->module, req);
504 }
505
506 /*
507  * return true if msg carries an attributeSchema that is intended to be RODC
508  * filtered but is also a system-critical attribute.
509  */
510 static bool check_rodc_critical_attribute(struct ldb_message *msg)
511 {
512         uint32_t schemaFlagsEx, searchFlags, rodc_filtered_flags;
513
514         schemaFlagsEx = ldb_msg_find_attr_as_uint(msg, "schemaFlagsEx", 0);
515         searchFlags = ldb_msg_find_attr_as_uint(msg, "searchFlags", 0);
516         rodc_filtered_flags = (SEARCH_FLAG_RODC_ATTRIBUTE
517                               | SEARCH_FLAG_CONFIDENTIAL);
518
519         if ((schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) &&
520                 ((searchFlags & rodc_filtered_flags) == rodc_filtered_flags)) {
521                 return true;
522         } else {
523                 return false;
524         }
525 }
526
527
528 static int samldb_fill_object(struct samldb_ctx *ac)
529 {
530         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
531         int ret;
532
533         /* Add informations for the different account types */
534         if (strcmp(ac->type, "user") == 0) {
535                 struct ldb_control *rodc_control = ldb_request_get_control(ac->req,
536                                                                            LDB_CONTROL_RODC_DCPROMO_OID);
537                 if (rodc_control != NULL) {
538                         /* see [MS-ADTS] 3.1.1.3.4.1.23 LDAP_SERVER_RODC_DCPROMO_OID */
539                         rodc_control->critical = false;
540                         ret = samldb_add_step(ac, samldb_rodc_add);
541                         if (ret != LDB_SUCCESS) return ret;
542                 }
543
544                 /* check if we have a valid sAMAccountName */
545                 ret = samldb_add_step(ac, samldb_check_sAMAccountName);
546                 if (ret != LDB_SUCCESS) return ret;
547
548                 ret = samldb_add_step(ac, samldb_add_entry);
549                 if (ret != LDB_SUCCESS) return ret;
550
551         } else if (strcmp(ac->type, "group") == 0) {
552                 /* check if we have a valid sAMAccountName */
553                 ret = samldb_add_step(ac, samldb_check_sAMAccountName);
554                 if (ret != LDB_SUCCESS) return ret;
555
556                 ret = samldb_add_step(ac, samldb_add_entry);
557                 if (ret != LDB_SUCCESS) return ret;
558
559         } else if (strcmp(ac->type, "classSchema") == 0) {
560                 const struct ldb_val *rdn_value, *def_obj_cat_val;
561
562                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
563                                                   "rdnAttId", "cn");
564                 if (ret != LDB_SUCCESS) return ret;
565
566                 /* do not allow to mark an attributeSchema as RODC filtered if it
567                  * is system-critical */
568                 if (check_rodc_critical_attribute(ac->msg)) {
569                         ldb_asprintf_errstring(ldb, "Refusing schema add of %s - cannot combine critical class with RODC filtering",
570                                                ldb_dn_get_linearized(ac->msg->dn));
571                         return LDB_ERR_UNWILLING_TO_PERFORM;
572                 }
573
574                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
575                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
576                         /* the RDN has prefix "CN" */
577                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
578                                 samdb_cn_to_lDAPDisplayName(ac->msg,
579                                                             (const char *) rdn_value->data));
580                         if (ret != LDB_SUCCESS) {
581                                 ldb_oom(ldb);
582                                 return ret;
583                         }
584                 }
585
586                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
587                         struct GUID guid;
588                         /* a new GUID */
589                         guid = GUID_random();
590                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
591                         if (ret != LDB_SUCCESS) {
592                                 ldb_oom(ldb);
593                                 return ret;
594                         }
595                 }
596
597                 def_obj_cat_val = ldb_msg_find_ldb_val(ac->msg,
598                                                        "defaultObjectCategory");
599                 if (def_obj_cat_val != NULL) {
600                         /* "defaultObjectCategory" has been set by the caller.
601                          * Do some checks for consistency.
602                          * NOTE: The real constraint check (that
603                          * 'defaultObjectCategory' is the DN of the new
604                          * objectclass or any parent of it) is still incomplete.
605                          * For now we say that 'defaultObjectCategory' is valid
606                          * if it exists and it is of objectclass "classSchema".
607                          */
608                         ac->dn = ldb_dn_from_ldb_val(ac, ldb, def_obj_cat_val);
609                         if (ac->dn == NULL) {
610                                 ldb_set_errstring(ldb,
611                                                   "Invalid DN for 'defaultObjectCategory'!");
612                                 return LDB_ERR_CONSTRAINT_VIOLATION;
613                         }
614                 } else {
615                         /* "defaultObjectCategory" has not been set by the
616                          * caller. Use the entry DN for it. */
617                         ac->dn = ac->msg->dn;
618
619                         ret = ldb_msg_add_string(ac->msg, "defaultObjectCategory",
620                                                  ldb_dn_alloc_linearized(ac->msg, ac->dn));
621                         if (ret != LDB_SUCCESS) {
622                                 ldb_oom(ldb);
623                                 return ret;
624                         }
625                 }
626
627                 ret = samldb_add_step(ac, samldb_add_entry);
628                 if (ret != LDB_SUCCESS) return ret;
629
630                 /* Now perform the checks for the 'defaultObjectCategory'. The
631                  * lookup DN was already saved in "ac->dn" */
632                 ret = samldb_add_step(ac, samldb_find_for_defaultObjectCategory);
633                 if (ret != LDB_SUCCESS) return ret;
634
635         } else if (strcmp(ac->type, "attributeSchema") == 0) {
636                 const struct ldb_val *rdn_value;
637                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
638                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
639                         /* the RDN has prefix "CN" */
640                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
641                                 samdb_cn_to_lDAPDisplayName(ac->msg,
642                                                             (const char *) rdn_value->data));
643                         if (ret != LDB_SUCCESS) {
644                                 ldb_oom(ldb);
645                                 return ret;
646                         }
647                 }
648
649                 /* do not allow to mark an attributeSchema as RODC filtered if it
650                  * is system-critical */
651                 if (check_rodc_critical_attribute(ac->msg)) {
652                         ldb_asprintf_errstring(ldb,
653                                                "samldb: refusing schema add of %s - cannot combine critical attribute with RODC filtering",
654                                                ldb_dn_get_linearized(ac->msg->dn));
655                         return LDB_ERR_UNWILLING_TO_PERFORM;
656                 }
657
658                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
659                                                   "isSingleValued", "FALSE");
660                 if (ret != LDB_SUCCESS) return ret;
661
662                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
663                         struct GUID guid;
664                         /* a new GUID */
665                         guid = GUID_random();
666                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
667                         if (ret != LDB_SUCCESS) {
668                                 ldb_oom(ldb);
669                                 return ret;
670                         }
671                 }
672
673                 /* handle msDS-IntID attribute */
674                 ret = samldb_add_handle_msDS_IntId(ac);
675                 if (ret != LDB_SUCCESS) return ret;
676
677                 ret = samldb_add_step(ac, samldb_add_entry);
678                 if (ret != LDB_SUCCESS) return ret;
679
680         } else {
681                 ldb_asprintf_errstring(ldb,
682                         "Invalid entry type!");
683                 return LDB_ERR_OPERATIONS_ERROR;
684         }
685
686         return samldb_first_step(ac);
687 }
688
689 static int samldb_fill_foreignSecurityPrincipal_object(struct samldb_ctx *ac)
690 {
691         struct ldb_context *ldb;
692         struct dom_sid *sid;
693         int ret;
694
695         ldb = ldb_module_get_ctx(ac->module);
696
697         sid = samdb_result_dom_sid(ac->msg, ac->msg, "objectSid");
698         if (sid == NULL) {
699                 sid = dom_sid_parse_talloc(ac->msg,
700                                            (const char *)ldb_dn_get_rdn_val(ac->msg->dn)->data);
701                 if (sid == NULL) {
702                         ldb_set_errstring(ldb,
703                                           "samldb: No valid SID found in ForeignSecurityPrincipal CN!");
704                         return LDB_ERR_CONSTRAINT_VIOLATION;
705                 }
706                 if (! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
707                         return ldb_operr(ldb);
708                 }
709         }
710
711         /* finally proceed with adding the entry */
712         ret = samldb_add_step(ac, samldb_add_entry);
713         if (ret != LDB_SUCCESS) return ret;
714
715         return samldb_first_step(ac);
716 }
717
718 static int samldb_schema_info_update(struct samldb_ctx *ac)
719 {
720         int ret;
721         struct ldb_context *ldb;
722         struct dsdb_schema *schema;
723
724         /* replicated update should always go through */
725         if (ldb_request_get_control(ac->req,
726                                     DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
727                 return LDB_SUCCESS;
728         }
729
730         /* do not update schemaInfo during provisioning */
731         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
732                 return LDB_SUCCESS;
733         }
734
735         ldb = ldb_module_get_ctx(ac->module);
736         schema = dsdb_get_schema(ldb, NULL);
737         if (!schema) {
738                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
739                               "samldb_schema_info_update: no dsdb_schema loaded");
740                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
741                 return ldb_operr(ldb);
742         }
743
744         ret = dsdb_module_schema_info_update(ac->module, schema,
745                                              DSDB_FLAG_NEXT_MODULE);
746         if (ret != LDB_SUCCESS) {
747                 ldb_asprintf_errstring(ldb,
748                                        "samldb_schema_info_update: dsdb_module_schema_info_update failed with %s",
749                                        ldb_errstring(ldb));
750                 return ret;
751         }
752
753         return LDB_SUCCESS;
754 }
755
756 /*
757  * Gets back a single-valued attribute by the rules of the SAM triggers when
758  * performing a modify operation
759  */
760 static int samldb_get_single_valued_attr(struct samldb_ctx *ac,
761                                          const char *attr_name,
762                                          struct ldb_message_element **attr)
763 {
764         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
765         struct ldb_message_element *el = NULL;
766         unsigned int i;
767
768         /* We've to walk over all modification entries and consider the
769          * "attr_name" ones.
770          *
771          * 1.) Add operations aren't allowed and there is returned
772          *     "ATTRIBUTE_OR_VALUE_EXISTS".
773          * 2.) Replace operations are allowed but the last one is taken
774          * 3.) Delete operations are also not allowed and there is returned
775          *     "UNWILLING_TO_PERFORM".
776          *
777          * If "el" is afterwards NULL then that means we've nothing to do here.
778          */
779         for (i = 0; i < ac->msg->num_elements; i++) {
780                 if (ldb_attr_cmp(ac->msg->elements[i].name, attr_name) != 0) {
781                         continue;
782                 }
783
784                 el = &ac->msg->elements[i];
785                 if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD) {
786                         ldb_asprintf_errstring(ldb,
787                                                "samldb: attribute '%s' already exists!",
788                                                attr_name);
789                         return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
790                 }
791                 if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE) {
792                         ldb_asprintf_errstring(ldb,
793                                                "samldb: attribute '%s' cannot be deleted!",
794                                                attr_name);
795                         return LDB_ERR_UNWILLING_TO_PERFORM;
796                 }
797         }
798
799         *attr = el;
800         return LDB_SUCCESS;
801 }
802
803 /*
804  * "Objectclass" trigger (MS-SAMR 3.1.1.8.1)
805  *
806  * Has to be invoked on "add" and "modify" operations on "user", "computer" and
807  * "group" objects.
808  * ac->msg contains the "add"/"modify" message
809  * ac->type contains the object type (main objectclass)
810  */
811 static int samldb_objectclass_trigger(struct samldb_ctx *ac)
812 {
813         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
814         struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb,
815                                          "loadparm"), struct loadparm_context);
816         struct ldb_message_element *el, *el2;
817         enum sid_generator sid_generator;
818         struct dom_sid *sid;
819         const char *tempstr;
820         int ret;
821
822         /* make sure that "sAMAccountType" is not specified */
823         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
824         if (el != NULL) {
825                 ldb_set_errstring(ldb,
826                                   "samldb: sAMAccountType must not be specified!");
827                 return LDB_ERR_UNWILLING_TO_PERFORM;
828         }
829
830         /* Step 1: objectSid assignment */
831
832         /* Don't allow the objectSid to be changed. But beside the RELAX
833          * control we have also to guarantee that it can always be set with
834          * SYSTEM permissions. This is needed for the "samba3sam" backend. */
835         sid = samdb_result_dom_sid(ac, ac->msg, "objectSid");
836         if ((sid != NULL) && (!dsdb_module_am_system(ac->module)) &&
837             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
838                 ldb_set_errstring(ldb,
839                                   "samldb: objectSid must not be specified!");
840                 return LDB_ERR_UNWILLING_TO_PERFORM;
841         }
842
843         /* but generate a new SID when we do have an add operations */
844         if ((sid == NULL) && (ac->req->operation == LDB_ADD)) {
845                 sid_generator = lpcfg_sid_generator(lp_ctx);
846                 if (sid_generator == SID_GENERATOR_INTERNAL) {
847                         ret = samldb_add_step(ac, samldb_allocate_sid);
848                         if (ret != LDB_SUCCESS) return ret;
849                 }
850         }
851
852         if (strcmp(ac->type, "user") == 0) {
853                 /* Step 1.2: Default values */
854                 tempstr = talloc_asprintf(ac->msg, "%d", UF_NORMAL_ACCOUNT);
855                 if (tempstr == NULL) return ldb_operr(ldb);
856                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
857                         "userAccountControl", tempstr);
858                 if (ret != LDB_SUCCESS) return ret;
859                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
860                         "badPwdCount", "0");
861                 if (ret != LDB_SUCCESS) return ret;
862                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
863                         "codePage", "0");
864                 if (ret != LDB_SUCCESS) return ret;
865                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
866                         "countryCode", "0");
867                 if (ret != LDB_SUCCESS) return ret;
868                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
869                         "badPasswordTime", "0");
870                 if (ret != LDB_SUCCESS) return ret;
871                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
872                         "lastLogoff", "0");
873                 if (ret != LDB_SUCCESS) return ret;
874                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
875                         "lastLogon", "0");
876                 if (ret != LDB_SUCCESS) return ret;
877                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
878                         "pwdLastSet", "0");
879                 if (ret != LDB_SUCCESS) return ret;
880                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
881                         "accountExpires", "9223372036854775807");
882                 if (ret != LDB_SUCCESS) return ret;
883                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
884                         "logonCount", "0");
885                 if (ret != LDB_SUCCESS) return ret;
886
887                 el = ldb_msg_find_element(ac->msg, "userAccountControl");
888                 if (el != NULL) {
889                         uint32_t user_account_control, account_type;
890
891                         /* Step 1.3: "userAccountControl" -> "sAMAccountType" mapping */
892                         user_account_control = ldb_msg_find_attr_as_uint(ac->msg,
893                                                                          "userAccountControl",
894                                                                          0);
895
896                         /* Temporary duplicate accounts aren't allowed */
897                         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
898                                 return LDB_ERR_OTHER;
899                         }
900
901                         account_type = ds_uf2atype(user_account_control);
902                         if (account_type == 0) {
903                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
904                                 return LDB_ERR_UNWILLING_TO_PERFORM;
905                         }
906                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
907                                                  "sAMAccountType",
908                                                  account_type);
909                         if (ret != LDB_SUCCESS) {
910                                 return ret;
911                         }
912                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
913                         el2->flags = LDB_FLAG_MOD_REPLACE;
914
915                         if (user_account_control &
916                             (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
917                                 ret = samdb_msg_set_string(ldb, ac->msg, ac->msg,
918                                                            "isCriticalSystemObject",
919                                                            "TRUE");
920                                 if (ret != LDB_SUCCESS) {
921                                         return ret;
922                                 }
923                                 el2 = ldb_msg_find_element(ac->msg,
924                                                            "isCriticalSystemObject");
925                                 el2->flags = LDB_FLAG_MOD_REPLACE;
926                         }
927
928                         /* Step 1.4: "userAccountControl" -> "primaryGroupID" mapping */
929                         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
930                                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
931                                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
932                                                          "primaryGroupID", rid);
933                                 if (ret != LDB_SUCCESS) {
934                                         return ret;
935                                 }
936                                 el2 = ldb_msg_find_element(ac->msg,
937                                                            "primaryGroupID");
938                                 el2->flags = LDB_FLAG_MOD_REPLACE;
939                         }
940
941                         /* Step 1.5: Add additional flags when needed */
942                         if ((user_account_control & UF_NORMAL_ACCOUNT) &&
943                             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
944                                 user_account_control |= UF_ACCOUNTDISABLE;
945                                 user_account_control |= UF_PASSWD_NOTREQD;
946
947                                 ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
948                                                          "userAccountControl",
949                                                          user_account_control);
950                                 if (ret != LDB_SUCCESS) {
951                                         return ret;
952                                 }
953                         }
954                 }
955
956         } else if (strcmp(ac->type, "group") == 0) {
957                 /* Step 2.2: Default values */
958                 tempstr = talloc_asprintf(ac->msg, "%d",
959                                           GTYPE_SECURITY_GLOBAL_GROUP);
960                 if (tempstr == NULL) return ldb_operr(ldb);
961                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
962                         "groupType", tempstr);
963                 if (ret != LDB_SUCCESS) return ret;
964
965                 /* Step 2.3: "groupType" -> "sAMAccountType" */
966                 el = ldb_msg_find_element(ac->msg, "groupType");
967                 if (el != NULL) {
968                         uint32_t group_type, account_type;
969
970                         group_type = ldb_msg_find_attr_as_uint(ac->msg,
971                                                                "groupType", 0);
972
973                         /* The creation of builtin groups requires the
974                          * RELAX control */
975                         if (group_type == GTYPE_SECURITY_BUILTIN_LOCAL_GROUP) {
976                                 if (ldb_request_get_control(ac->req,
977                                                             LDB_CONTROL_RELAX_OID) == NULL) {
978                                         return LDB_ERR_UNWILLING_TO_PERFORM;
979                                 }
980                         }
981
982                         account_type = ds_gtype2atype(group_type);
983                         if (account_type == 0) {
984                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
985                                 return LDB_ERR_UNWILLING_TO_PERFORM;
986                         }
987                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
988                                                  "sAMAccountType",
989                                                  account_type);
990                         if (ret != LDB_SUCCESS) {
991                                 return ret;
992                         }
993                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
994                         el2->flags = LDB_FLAG_MOD_REPLACE;
995                 }
996         }
997
998         return LDB_SUCCESS;
999 }
1000
1001 /*
1002  * "Primary group ID" trigger (MS-SAMR 3.1.1.8.2)
1003  *
1004  * Has to be invoked on "add" and "modify" operations on "user" and "computer"
1005  * objects.
1006  * ac->msg contains the "add"/"modify" message
1007  */
1008
1009 static int samldb_prim_group_set(struct samldb_ctx *ac)
1010 {
1011         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1012         struct ldb_dn *prim_group_dn;
1013         uint32_t rid;
1014         struct dom_sid *sid;
1015
1016         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1017         if (rid == (uint32_t) -1) {
1018                 /* we aren't affected of any primary group set */
1019                 return LDB_SUCCESS;
1020
1021         } else if (!ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
1022                 ldb_set_errstring(ldb,
1023                                   "The primary group isn't settable on add operations!");
1024                 return LDB_ERR_UNWILLING_TO_PERFORM;
1025         }
1026
1027         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1028         if (sid == NULL) {
1029                 return ldb_operr(ldb);
1030         }
1031
1032         prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1033                                         ldap_encode_ndr_dom_sid(ac, sid));
1034         if (prim_group_dn == NULL) {
1035                 ldb_asprintf_errstring(ldb,
1036                                        "Failed to find primary group with RID %u!",
1037                                        rid);
1038                 return LDB_ERR_UNWILLING_TO_PERFORM;
1039         }
1040
1041         return LDB_SUCCESS;
1042 }
1043
1044 static int samldb_prim_group_change(struct samldb_ctx *ac)
1045 {
1046         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1047         const char * attrs[] = { "primaryGroupID", "memberOf", NULL };
1048         struct ldb_result *res;
1049         struct ldb_message_element *el;
1050         struct ldb_message *msg;
1051         uint32_t rid;
1052         struct dom_sid *sid;
1053         struct ldb_dn *prev_prim_group_dn, *new_prim_group_dn;
1054         int ret;
1055
1056         ret = samldb_get_single_valued_attr(ac, "primaryGroupID", &el);
1057         if (ret != LDB_SUCCESS) {
1058                 return ret;
1059         }
1060         if (el == NULL) {
1061                 /* we are not affected */
1062                 return LDB_SUCCESS;
1063         }
1064
1065         /* Fetch informations from the existing object */
1066
1067         ret = ldb_search(ldb, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1068                          NULL);
1069         if (ret != LDB_SUCCESS) {
1070                 return ret;
1071         }
1072         if (res->count != 1) {
1073                 return ldb_operr(ldb);
1074         }
1075
1076         /* Finds out the DN of the old primary group */
1077
1078         rid = ldb_msg_find_attr_as_uint(res->msgs[0], "primaryGroupID", (uint32_t) -1);
1079         if (rid == (uint32_t) -1) {
1080                 /* User objects do always have a mandatory "primaryGroupID"
1081                  * attribute. If this doesn't exist then the object is of the
1082                  * wrong type. This is the exact Windows error code */
1083                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1084         }
1085
1086         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1087         if (sid == NULL) {
1088                 return ldb_operr(ldb);
1089         }
1090
1091         prev_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1092                                              ldap_encode_ndr_dom_sid(ac, sid));
1093         if (prev_prim_group_dn == NULL) {
1094                 return ldb_operr(ldb);
1095         }
1096
1097         /* Finds out the DN of the new primary group
1098          * Notice: in order to parse the primary group ID correctly we create
1099          * a temporary message here. */
1100
1101         msg = ldb_msg_new(ac->msg);
1102         if (msg == NULL) {
1103                 return ldb_module_oom(ac->module);
1104         }
1105         ret = ldb_msg_add(msg, el, 0);
1106         if (ret != LDB_SUCCESS) {
1107                 return ret;
1108         }
1109         rid = ldb_msg_find_attr_as_uint(msg, "primaryGroupID", (uint32_t) -1);
1110         talloc_free(msg);
1111         if (rid == (uint32_t) -1) {
1112                 /* we aren't affected of any primary group change */
1113                 return LDB_SUCCESS;
1114         }
1115
1116         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1117         if (sid == NULL) {
1118                 return ldb_operr(ldb);
1119         }
1120
1121         new_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1122                                             ldap_encode_ndr_dom_sid(ac, sid));
1123         if (new_prim_group_dn == NULL) {
1124                 /* Here we know if the specified new primary group candidate is
1125                  * valid or not. */
1126                 return LDB_ERR_UNWILLING_TO_PERFORM;
1127         }
1128
1129         /* Only update the "member" attributes when we really do have a change */
1130         if (ldb_dn_compare(new_prim_group_dn, prev_prim_group_dn) != 0) {
1131                 /* We need to be already a normal member of the new primary
1132                  * group in order to be successful. */
1133                 el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1134                                           ldb_dn_get_linearized(new_prim_group_dn));
1135                 if (el == NULL) {
1136                         return LDB_ERR_UNWILLING_TO_PERFORM;
1137                 }
1138
1139                 /* Remove the "member" attribute on the new primary group */
1140                 msg = ldb_msg_new(ac->msg);
1141                 if (msg == NULL) {
1142                         return ldb_module_oom(ac->module);
1143                 }
1144                 msg->dn = new_prim_group_dn;
1145
1146                 ret = samdb_msg_add_delval(ldb, msg, msg, "member",
1147                                            ldb_dn_get_linearized(ac->msg->dn));
1148                 if (ret != LDB_SUCCESS) {
1149                         return ret;
1150                 }
1151
1152                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1153                 if (ret != LDB_SUCCESS) {
1154                         return ret;
1155                 }
1156                 talloc_free(msg);
1157
1158                 /* Add a "member" attribute for the previous primary group */
1159                 msg = ldb_msg_new(ac->msg);
1160                 if (msg == NULL) {
1161                         return ldb_module_oom(ac->module);
1162                 }
1163                 msg->dn = prev_prim_group_dn;
1164
1165                 ret = samdb_msg_add_addval(ldb, msg, msg, "member",
1166                                            ldb_dn_get_linearized(ac->msg->dn));
1167                 if (ret != LDB_SUCCESS) {
1168                         return ret;
1169                 }
1170
1171                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1172                 if (ret != LDB_SUCCESS) {
1173                         return ret;
1174                 }
1175                 talloc_free(msg);
1176         }
1177
1178         talloc_free(res);
1179
1180         return LDB_SUCCESS;
1181 }
1182
1183 static int samldb_prim_group_trigger(struct samldb_ctx *ac)
1184 {
1185         int ret;
1186
1187         if (ac->req->operation == LDB_ADD) {
1188                 ret = samldb_prim_group_set(ac);
1189         } else {
1190                 ret = samldb_prim_group_change(ac);
1191         }
1192
1193         return ret;
1194 }
1195
1196 static int samldb_user_account_control_change(struct samldb_ctx *ac)
1197 {
1198         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1199         uint32_t user_account_control, account_type;
1200         struct ldb_message_element *el;
1201         struct ldb_message *tmp_msg;
1202         int ret;
1203
1204         ret = samldb_get_single_valued_attr(ac, "userAccountControl", &el);
1205         if (ret != LDB_SUCCESS) {
1206                 return ret;
1207         }
1208         if (el == NULL) {
1209                 /* we are not affected */
1210                 return LDB_SUCCESS;
1211         }
1212
1213         /* Create a temporary message for fetching the "userAccountControl" */
1214         tmp_msg = ldb_msg_new(ac->msg);
1215         if (tmp_msg == NULL) {
1216                 return ldb_module_oom(ac->module);
1217         }
1218         ret = ldb_msg_add(tmp_msg, el, 0);
1219         if (ret != LDB_SUCCESS) {
1220                 return ret;
1221         }
1222         user_account_control = ldb_msg_find_attr_as_uint(tmp_msg,
1223                                                          "userAccountControl",
1224                                                          0);
1225         talloc_free(tmp_msg);
1226
1227         /* Temporary duplicate accounts aren't allowed */
1228         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
1229                 return LDB_ERR_OTHER;
1230         }
1231
1232         account_type = ds_uf2atype(user_account_control);
1233         if (account_type == 0) {
1234                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1235                 return LDB_ERR_UNWILLING_TO_PERFORM;
1236         }
1237         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1238                                  account_type);
1239         if (ret != LDB_SUCCESS) {
1240                 return ret;
1241         }
1242         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1243         el->flags = LDB_FLAG_MOD_REPLACE;
1244
1245         if (user_account_control
1246             & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1247                 ret = samdb_msg_add_string(ldb, ac->msg, ac->msg,
1248                                            "isCriticalSystemObject", "TRUE");
1249                 if (ret != LDB_SUCCESS) {
1250                         return ret;
1251                 }
1252                 el = ldb_msg_find_element(ac->msg,
1253                                            "isCriticalSystemObject");
1254                 el->flags = LDB_FLAG_MOD_REPLACE;
1255         }
1256
1257         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
1258                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
1259                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1260                                          "primaryGroupID", rid);
1261                 if (ret != LDB_SUCCESS) {
1262                         return ret;
1263                 }
1264                 el = ldb_msg_find_element(ac->msg,
1265                                            "primaryGroupID");
1266                 el->flags = LDB_FLAG_MOD_REPLACE;
1267         }
1268
1269         return LDB_SUCCESS;
1270 }
1271
1272 static int samldb_group_type_change(struct samldb_ctx *ac)
1273 {
1274         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1275         uint32_t group_type, old_group_type, account_type;
1276         struct ldb_message_element *el;
1277         struct ldb_message *tmp_msg;
1278         int ret;
1279
1280         ret = samldb_get_single_valued_attr(ac, "groupType", &el);
1281         if (ret != LDB_SUCCESS) {
1282                 return ret;
1283         }
1284         if (el == NULL) {
1285                 /* we are not affected */
1286                 return LDB_SUCCESS;
1287         }
1288
1289         /* Create a temporary message for fetching the "groupType" */
1290         tmp_msg = ldb_msg_new(ac->msg);
1291         if (tmp_msg == NULL) {
1292                 return ldb_module_oom(ac->module);
1293         }
1294         ret = ldb_msg_add(tmp_msg, el, 0);
1295         if (ret != LDB_SUCCESS) {
1296                 return ret;
1297         }
1298         group_type = ldb_msg_find_attr_as_uint(tmp_msg, "groupType", 0);
1299         talloc_free(tmp_msg);
1300
1301         old_group_type = samdb_search_uint(ldb, ac, 0, ac->msg->dn,
1302                                            "groupType", NULL);
1303         if (old_group_type == 0) {
1304                 return ldb_operr(ldb);
1305         }
1306
1307         /* Group type switching isn't so easy as it seems: We can only
1308          * change in this directions: global <-> universal <-> local
1309          * On each step also the group type itself
1310          * (security/distribution) is variable. */
1311
1312         switch (group_type) {
1313         case GTYPE_SECURITY_GLOBAL_GROUP:
1314         case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
1315                 /* change to "universal" allowed */
1316                 if ((old_group_type == GTYPE_SECURITY_DOMAIN_LOCAL_GROUP) ||
1317                     (old_group_type == GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP)) {
1318                         return LDB_ERR_UNWILLING_TO_PERFORM;
1319                 }
1320         break;
1321
1322         case GTYPE_SECURITY_UNIVERSAL_GROUP:
1323         case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
1324                 /* each change allowed */
1325         break;
1326
1327         case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
1328         case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
1329                 /* change to "universal" allowed */
1330                 if ((old_group_type == GTYPE_SECURITY_GLOBAL_GROUP) ||
1331                     (old_group_type == GTYPE_DISTRIBUTION_GLOBAL_GROUP)) {
1332                         return LDB_ERR_UNWILLING_TO_PERFORM;
1333                 }
1334         break;
1335
1336         case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
1337         default:
1338                 /* we don't allow this "groupType" values */
1339                 return LDB_ERR_UNWILLING_TO_PERFORM;
1340         break;
1341         }
1342
1343         account_type =  ds_gtype2atype(group_type);
1344         if (account_type == 0) {
1345                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1346                 return LDB_ERR_UNWILLING_TO_PERFORM;
1347         }
1348         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1349                                  account_type);
1350         if (ret != LDB_SUCCESS) {
1351                 return ret;
1352         }
1353         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1354         el->flags = LDB_FLAG_MOD_REPLACE;
1355
1356         return LDB_SUCCESS;
1357 }
1358
1359 static int samldb_sam_accountname_check(struct samldb_ctx *ac)
1360 {
1361         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1362         const char *no_attrs[] = { NULL };
1363         struct ldb_result *res;
1364         const char *sam_accountname, *enc_str;
1365         struct ldb_message_element *el;
1366         struct ldb_message *tmp_msg;
1367         int ret;
1368
1369         ret = samldb_get_single_valued_attr(ac, "sAMAccountName", &el);
1370         if (ret != LDB_SUCCESS) {
1371                 return ret;
1372         }
1373         if (el == NULL) {
1374                 /* we are not affected */
1375                 return LDB_SUCCESS;
1376         }
1377
1378         /* Create a temporary message for fetching the "sAMAccountName" */
1379         tmp_msg = ldb_msg_new(ac->msg);
1380         if (tmp_msg == NULL) {
1381                 return ldb_module_oom(ac->module);
1382         }
1383         ret = ldb_msg_add(tmp_msg, el, 0);
1384         if (ret != LDB_SUCCESS) {
1385                 return ret;
1386         }
1387         sam_accountname = talloc_steal(ac,
1388                                        ldb_msg_find_attr_as_string(tmp_msg, "sAMAccountName", NULL));
1389         talloc_free(tmp_msg);
1390
1391         if (sam_accountname == NULL) {
1392                 return ldb_operr(ldb);
1393         }
1394
1395         enc_str = ldb_binary_encode_string(ac, sam_accountname);
1396         if (enc_str == NULL) {
1397                 return ldb_module_oom(ac->module);
1398         }
1399
1400         /* Make sure that a "sAMAccountName" is only used once */
1401
1402         ret = ldb_search(ldb, ac, &res, NULL, LDB_SCOPE_SUBTREE, no_attrs,
1403                          "(sAMAccountName=%s)", enc_str);
1404         if (ret != LDB_SUCCESS) {
1405                 return ret;
1406         }
1407         if (res->count > 1) {
1408                 return ldb_operr(ldb);
1409         } else if (res->count == 1) {
1410                 if (ldb_dn_compare(res->msgs[0]->dn, ac->msg->dn) != 0) {
1411                         ldb_asprintf_errstring(ldb,
1412                                                "samldb: Account name (sAMAccountName) '%s' already in use!",
1413                                                sam_accountname);
1414                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
1415                 }
1416         }
1417         talloc_free(res);
1418
1419         return LDB_SUCCESS;
1420 }
1421
1422 static int samldb_member_check(struct samldb_ctx *ac)
1423 {
1424         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1425         struct ldb_message_element *el;
1426         struct ldb_dn *member_dn, *group_dn;
1427         uint32_t prim_group_rid;
1428         struct dom_sid *sid;
1429         unsigned int i, j;
1430         int cnt;
1431
1432         /* We've to walk over all modification entries and consider the "member"
1433          * ones. */
1434         for (i = 0; i < ac->msg->num_elements; i++) {
1435                 if (ldb_attr_cmp(ac->msg->elements[i].name, "member") != 0) {
1436                         continue;
1437                 }
1438
1439                 el = &ac->msg->elements[i];
1440                 for (j = 0; j < el->num_values; j++) {
1441                         member_dn = ldb_dn_from_ldb_val(ac, ldb,
1442                                                         &el->values[j]);
1443                         if (!ldb_dn_validate(member_dn)) {
1444                                 return ldb_operr(ldb);
1445                         }
1446
1447                         /* The "member" attribute can be modified with the
1448                          * following restrictions (beside a valid DN):
1449                          *
1450                          * - "add" operations can only be performed when the
1451                          *   member still doesn't exist - if not then return
1452                          *   ERR_ENTRY_ALREADY_EXISTS (not
1453                          *   ERR_ATTRIBUTE_OR_VALUE_EXISTS!)
1454                          * - "delete" operations can only be performed when the
1455                          *   member does exist - if not then return
1456                          *   ERR_UNWILLING_TO_PERFORM (not
1457                          *   ERR_NO_SUCH_ATTRIBUTE!)
1458                          * - primary group check
1459                          */
1460                         cnt = samdb_search_count(ldb, ac, ac->msg->dn,
1461                                                  "(member=%s)",
1462                                                  ldb_dn_get_linearized(member_dn));
1463                         if (cnt < 0) {
1464                                 return ldb_operr(ldb);
1465                         }
1466                         if ((cnt > 0) && (LDB_FLAG_MOD_TYPE(el->flags)
1467                             == LDB_FLAG_MOD_ADD)) {
1468                                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1469                         }
1470                         if ((cnt == 0) && LDB_FLAG_MOD_TYPE(el->flags)
1471                             == LDB_FLAG_MOD_DELETE) {
1472                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1473                         }
1474
1475                         /* Denies to add "member"s to groups which are primary
1476                          * ones for them - in this case return
1477                          * ERR_ENTRY_ALREADY_EXISTS. */
1478
1479                         prim_group_rid = samdb_search_uint(ldb, ac,
1480                                                            (uint32_t) -1,
1481                                                            member_dn,
1482                                                            "primaryGroupID",
1483                                                            NULL);
1484                         if (prim_group_rid == (uint32_t) -1) {
1485                                 /* the member hasn't to be a user account ->
1486                                  * therefore no check needed in this case. */
1487                                 continue;
1488                         }
1489
1490                         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
1491                                               prim_group_rid);
1492                         if (sid == NULL) {
1493                                 return ldb_operr(ldb);
1494                         }
1495
1496                         group_dn = samdb_search_dn(ldb, ac, NULL,
1497                                                    "(objectSid=%s)",
1498                                                    ldap_encode_ndr_dom_sid(ac, sid));
1499                         if (group_dn == NULL) {
1500                                 return ldb_operr(ldb);
1501                         }
1502
1503                         if (ldb_dn_compare(group_dn, ac->msg->dn) == 0) {
1504                                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1505                         }
1506                 }
1507         }
1508
1509         return LDB_SUCCESS;
1510 }
1511
1512 /* This trigger adapts the "servicePrincipalName" attributes if the
1513  * "dNSHostName" attribute changes */
1514 static int samldb_service_principal_names_change(struct samldb_ctx *ac)
1515 {
1516         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1517         struct ldb_message_element *el = NULL;
1518         struct ldb_message *msg;
1519         const char *attrs[] = { "servicePrincipalName", NULL };
1520         struct ldb_result *res;
1521         const char *dns_hostname, *old_dns_hostname;
1522         unsigned int i;
1523         int ret;
1524
1525         /* Here it's not the same logic as with "samldb_get_single_valued_attr".
1526          * We need to:
1527          *
1528          * - consider "add" and "replace" operations - the last value we take
1529          * - ignore "delete" operations - obviously this attribute isn't
1530          *   write protected
1531          */
1532         for (i = 0; i < ac->msg->num_elements; i++) {
1533                 if (ldb_attr_cmp(ac->msg->elements[i].name,
1534                                  "dNSHostName") != 0) {
1535                         continue;
1536                 }
1537
1538                 if (LDB_FLAG_MOD_TYPE(ac->msg->elements[i].flags)
1539                     != LDB_FLAG_MOD_DELETE) {
1540                         el = &ac->msg->elements[i];
1541                 }
1542         }
1543         if (el == NULL) {
1544                 /* we are not affected */
1545                 return LDB_SUCCESS;
1546         }
1547
1548         /* Create a temporary message for fetching the "dNSHostName" */
1549         msg = ldb_msg_new(ac->msg);
1550         if (msg == NULL) {
1551                 return ldb_module_oom(ac->module);
1552         }
1553         ret = ldb_msg_add(msg, el, 0);
1554         if (ret != LDB_SUCCESS) {
1555                 return ret;
1556         }
1557         dns_hostname = ldb_msg_find_attr_as_string(msg, "dNSHostName", "");
1558         talloc_free(msg);
1559
1560         old_dns_hostname = samdb_search_string(ldb, ac, ac->msg->dn,
1561                                                "dNSHostName", NULL);
1562         if ((old_dns_hostname == NULL) || (strcasecmp(old_dns_hostname,
1563                                                       dns_hostname) == 0)) {
1564                 /* Well, if there's no old DNS hostname then we cannot do this.
1565                  * And if old and new DNS name do match we are also finished
1566                  * here. */
1567                 return LDB_SUCCESS;
1568         }
1569
1570         /* Potential "servicePrincipalName" changes in the same request have to
1571          * be handled before the update (Windows behaviour). */
1572         el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
1573         if (el != NULL) {
1574                 msg = ldb_msg_new(ac->msg);
1575                 if (msg == NULL) {
1576                         return ldb_module_oom(ac->module);
1577                 }
1578                 msg->dn = ac->msg->dn;
1579
1580                 do {
1581                         ret = ldb_msg_add(msg, el, el->flags);
1582                         if (ret != LDB_SUCCESS) {
1583                                 return ret;
1584                         }
1585
1586                         ldb_msg_remove_element(ac->msg, el);
1587
1588                         el = ldb_msg_find_element(ac->msg,
1589                                                   "servicePrincipalName");
1590                 } while (el != NULL);
1591
1592                 ret = dsdb_module_modify(ac->module, msg,
1593                                          DSDB_FLAG_NEXT_MODULE);
1594                 if (ret != LDB_SUCCESS) {
1595                         return ret;
1596                 }
1597                 talloc_free(msg);
1598         }
1599
1600         /* Fetch the "servicePrincipalName"s if any */
1601         ret = ldb_search(ldb, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1602                          NULL);
1603         if (ret != LDB_SUCCESS) {
1604                 return ret;
1605         }
1606         if ((res->count != 1) || (res->msgs[0]->num_elements > 1)) {
1607                 return ldb_operr(ldb);
1608         }
1609
1610         if (res->msgs[0]->num_elements == 1) {
1611                 /* Yes, we do have "servicePrincipalName"s. First we update them
1612                  * locally, that means we do always substitute the current
1613                  * "dNSHostName" with the new one and then we append this to the
1614                  * modification request (Windows behaviour). */
1615
1616                 for (i = 0; i < res->msgs[0]->elements[0].num_values; i++) {
1617                         char *old_str, *new_str, *pos;
1618                         const char *tok;
1619
1620                         old_str = (char *)
1621                                 res->msgs[0]->elements[0].values[i].data;
1622
1623                         new_str = talloc_strdup(ac->msg,
1624                                                 strtok_r(old_str, "/", &pos));
1625                         if (new_str == NULL) {
1626                                 return ldb_module_oom(ac->module);
1627                         }
1628
1629                         while ((tok = strtok_r(NULL, "/", &pos)) != NULL) {
1630                                 if (strcasecmp(tok, old_dns_hostname) == 0) {
1631                                         tok = dns_hostname;
1632                                 }
1633
1634                                 new_str = talloc_asprintf(ac->msg, "%s/%s",
1635                                                           new_str, tok);
1636                                 if (new_str == NULL) {
1637                                         return ldb_module_oom(ac->module);
1638                                 }
1639                         }
1640
1641                         ret = ldb_msg_add_string(ac->msg,
1642                                                  "servicePrincipalName",
1643                                                  new_str);
1644                         if (ret != LDB_SUCCESS) {
1645                                 return ret;
1646                         }
1647                 }
1648
1649                 el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
1650                 el->flags = LDB_FLAG_MOD_REPLACE;
1651         }
1652
1653         talloc_free(res);
1654
1655         return LDB_SUCCESS;
1656 }
1657
1658
1659 /* add */
1660 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
1661 {
1662         struct ldb_context *ldb;
1663         struct samldb_ctx *ac;
1664         int ret;
1665
1666         ldb = ldb_module_get_ctx(module);
1667         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
1668
1669         /* do not manipulate our control entries */
1670         if (ldb_dn_is_special(req->op.add.message->dn)) {
1671                 return ldb_next_request(module, req);
1672         }
1673
1674         ac = samldb_ctx_init(module, req);
1675         if (ac == NULL) {
1676                 return ldb_operr(ldb);
1677         }
1678
1679         /* build the new msg */
1680         ac->msg = ldb_msg_copy_shallow(ac, req->op.add.message);
1681         if (ac->msg == NULL) {
1682                 talloc_free(ac);
1683                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1684                           "samldb_add: ldb_msg_copy_shallow failed!\n");
1685                 return ldb_operr(ldb);
1686         }
1687
1688         if (samdb_find_attribute(ldb, ac->msg,
1689                                  "objectclass", "user") != NULL) {
1690                 ac->type = "user";
1691
1692                 ret = samldb_prim_group_trigger(ac);
1693                 if (ret != LDB_SUCCESS) {
1694                         return ret;
1695                 }
1696
1697                 ret = samldb_objectclass_trigger(ac);
1698                 if (ret != LDB_SUCCESS) {
1699                         return ret;
1700                 }
1701
1702                 return samldb_fill_object(ac);
1703         }
1704
1705         if (samdb_find_attribute(ldb, ac->msg,
1706                                  "objectclass", "group") != NULL) {
1707                 ac->type = "group";
1708
1709                 ret = samldb_objectclass_trigger(ac);
1710                 if (ret != LDB_SUCCESS) {
1711                         return ret;
1712                 }
1713
1714                 return samldb_fill_object(ac);
1715         }
1716
1717         /* perhaps a foreignSecurityPrincipal? */
1718         if (samdb_find_attribute(ldb, ac->msg,
1719                                  "objectclass",
1720                                  "foreignSecurityPrincipal") != NULL) {
1721                 return samldb_fill_foreignSecurityPrincipal_object(ac);
1722         }
1723
1724         if (samdb_find_attribute(ldb, ac->msg,
1725                                  "objectclass", "classSchema") != NULL) {
1726                 ret = samldb_schema_info_update(ac);
1727                 if (ret != LDB_SUCCESS) {
1728                         talloc_free(ac);
1729                         return ret;
1730                 }
1731
1732                 ac->type = "classSchema";
1733                 return samldb_fill_object(ac);
1734         }
1735
1736         if (samdb_find_attribute(ldb, ac->msg,
1737                                  "objectclass", "attributeSchema") != NULL) {
1738                 ret = samldb_schema_info_update(ac);
1739                 if (ret != LDB_SUCCESS) {
1740                         talloc_free(ac);
1741                         return ret;
1742                 }
1743
1744                 ac->type = "attributeSchema";
1745                 return samldb_fill_object(ac);
1746         }
1747
1748         talloc_free(ac);
1749
1750         /* nothing matched, go on */
1751         return ldb_next_request(module, req);
1752 }
1753
1754 /* modify */
1755 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
1756 {
1757         struct ldb_context *ldb;
1758         struct samldb_ctx *ac;
1759         struct ldb_message_element *el;
1760         bool modified = false;
1761         int ret;
1762
1763         if (ldb_dn_is_special(req->op.mod.message->dn)) {
1764                 /* do not manipulate our control entries */
1765                 return ldb_next_request(module, req);
1766         }
1767
1768         ldb = ldb_module_get_ctx(module);
1769
1770         /* make sure that "objectSid" is not specified */
1771         el = ldb_msg_find_element(req->op.mod.message, "objectSid");
1772         if (el != NULL) {
1773                 ldb_set_errstring(ldb,
1774                                   "samldb: objectSid must not be specified!");
1775                 return LDB_ERR_UNWILLING_TO_PERFORM;
1776         }
1777         /* make sure that "sAMAccountType" is not specified */
1778         el = ldb_msg_find_element(req->op.mod.message, "sAMAccountType");
1779         if (el != NULL) {
1780                 ldb_set_errstring(ldb,
1781                                   "samldb: sAMAccountType must not be specified!");
1782                 return LDB_ERR_UNWILLING_TO_PERFORM;
1783         }
1784         /* make sure that "isCriticalSystemObject" is not specified */
1785         el = ldb_msg_find_element(req->op.mod.message, "isCriticalSystemObject");
1786         if (el != NULL) {
1787                 if (ldb_request_get_control(req, LDB_CONTROL_RELAX_OID) == NULL) {
1788                         ldb_set_errstring(ldb,
1789                                           "samldb: isCriticalSystemObject must not be specified!");
1790                         return LDB_ERR_UNWILLING_TO_PERFORM;
1791                 }
1792         }
1793
1794         /* msDS-IntId is not allowed to be modified
1795          * except when modification comes from replication */
1796         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
1797                 if (!ldb_request_get_control(req,
1798                                              DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
1799                         return LDB_ERR_CONSTRAINT_VIOLATION;
1800                 }
1801         }
1802
1803         ac = samldb_ctx_init(module, req);
1804         if (ac == NULL) {
1805                 return ldb_operr(ldb);
1806         }
1807
1808         /* build the new msg */
1809         ac->msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
1810         if (ac->msg == NULL) {
1811                 talloc_free(ac);
1812                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1813                           "samldb_modify: ldb_msg_copy_shallow failed!\n");
1814                 return ldb_operr(ldb);
1815         }
1816
1817         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
1818         if (el != NULL) {
1819                 ret = samldb_prim_group_change(ac);
1820                 if (ret != LDB_SUCCESS) {
1821                         return ret;
1822                 }
1823         }
1824
1825         el = ldb_msg_find_element(ac->msg, "userAccountControl");
1826         if (el != NULL) {
1827                 modified = true;
1828                 ret = samldb_user_account_control_change(ac);
1829                 if (ret != LDB_SUCCESS) {
1830                         return ret;
1831                 }
1832         }
1833
1834         el = ldb_msg_find_element(ac->msg, "groupType");
1835         if (el != NULL) {
1836                 modified = true;
1837                 ret = samldb_group_type_change(ac);
1838                 if (ret != LDB_SUCCESS) {
1839                         return ret;
1840                 }
1841         }
1842
1843         el = ldb_msg_find_element(ac->msg, "sAMAccountName");
1844         if (el != NULL) {
1845                 ret = samldb_sam_accountname_check(ac);
1846                 if (ret != LDB_SUCCESS) {
1847                         return ret;
1848                 }
1849         }
1850
1851         el = ldb_msg_find_element(ac->msg, "member");
1852         if (el != NULL) {
1853                 ret = samldb_member_check(ac);
1854                 if (ret != LDB_SUCCESS) {
1855                         return ret;
1856                 }
1857         }
1858
1859         el = ldb_msg_find_element(ac->msg, "dNSHostName");
1860         if (el != NULL) {
1861                 modified = true;
1862                 ret = samldb_service_principal_names_change(ac);
1863                 if (ret != LDB_SUCCESS) {
1864                         return ret;
1865                 }
1866         }
1867
1868         if (modified) {
1869                 struct ldb_request *child_req;
1870
1871                 /* Now perform the real modifications as a child request */
1872                 ret = ldb_build_mod_req(&child_req, ldb, ac,
1873                                         ac->msg,
1874                                         req->controls,
1875                                         req, dsdb_next_callback,
1876                                         req);
1877                 LDB_REQ_SET_LOCATION(child_req);
1878                 if (ret != LDB_SUCCESS) {
1879                         return ret;
1880                 }
1881
1882                 return ldb_next_request(module, child_req);
1883         }
1884
1885         talloc_free(ac);
1886
1887         /* no change which interests us, go on */
1888         return ldb_next_request(module, req);
1889 }
1890
1891 /* delete */
1892
1893 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
1894 {
1895         struct ldb_context *ldb;
1896         struct dom_sid *sid;
1897         uint32_t rid;
1898         NTSTATUS status;
1899         int count;
1900
1901         ldb = ldb_module_get_ctx(ac->module);
1902
1903         /* Finds out the SID/RID of the SAM object */
1904         sid = samdb_search_dom_sid(ldb, ac, ac->req->op.del.dn, "objectSid",
1905                                    NULL);
1906         if (sid == NULL) {
1907                 /* No SID - it might not be a SAM object - therefore ok */
1908                 return LDB_SUCCESS;
1909         }
1910         status = dom_sid_split_rid(ac, sid, NULL, &rid);
1911         if (!NT_STATUS_IS_OK(status)) {
1912                 return ldb_operr(ldb);
1913         }
1914         if (rid == 0) {
1915                 /* Special object (security principal?) */
1916                 return LDB_SUCCESS;
1917         }
1918
1919         /* Deny delete requests from groups which are primary ones */
1920         count = samdb_search_count(ldb, ac, NULL,
1921                                    "(&(primaryGroupID=%u)(objectClass=user))",
1922                                    rid);
1923         if (count < 0) {
1924                 return ldb_operr(ldb);
1925         }
1926         if (count > 0) {
1927                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1928         }
1929
1930         return LDB_SUCCESS;
1931 }
1932
1933 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
1934 {
1935         struct samldb_ctx *ac;
1936         int ret;
1937
1938         if (ldb_dn_is_special(req->op.del.dn)) {
1939                 /* do not manipulate our control entries */
1940                 return ldb_next_request(module, req);
1941         }
1942
1943         ac = samldb_ctx_init(module, req);
1944         if (ac == NULL) {
1945                 return ldb_operr(ldb_module_get_ctx(module));
1946         }
1947
1948         ret = samldb_prim_group_users_check(ac);
1949         if (ret != LDB_SUCCESS) {
1950                 return ret;
1951         }
1952
1953         talloc_free(ac);
1954
1955         return ldb_next_request(module, req);
1956 }
1957
1958 /* extended */
1959
1960 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
1961 {
1962         struct ldb_context *ldb = ldb_module_get_ctx(module);
1963         struct dsdb_fsmo_extended_op *exop;
1964         int ret;
1965
1966         exop = talloc_get_type(req->op.extended.data,
1967                                struct dsdb_fsmo_extended_op);
1968         if (!exop) {
1969                 ldb_set_errstring(ldb,
1970                                   "samldb_extended_allocate_rid_pool: invalid extended data");
1971                 return LDB_ERR_PROTOCOL_ERROR;
1972         }
1973
1974         ret = ridalloc_allocate_rid_pool_fsmo(module, exop);
1975         if (ret != LDB_SUCCESS) {
1976                 return ret;
1977         }
1978
1979         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1980 }
1981
1982 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
1983 {
1984         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
1985                 return samldb_extended_allocate_rid_pool(module, req);
1986         }
1987
1988         return ldb_next_request(module, req);
1989 }
1990
1991
1992 static const struct ldb_module_ops ldb_samldb_module_ops = {
1993         .name          = "samldb",
1994         .add           = samldb_add,
1995         .modify        = samldb_modify,
1996         .del           = samldb_delete,
1997         .extended      = samldb_extended
1998 };
1999
2000
2001 int ldb_samldb_module_init(const char *version)
2002 {
2003         LDB_MODULE_CHECK_VERSION(version);
2004         return ldb_register_module(&ldb_samldb_module_ops);
2005 }