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