s4:samldb LDB module - validate "sAMAccountName" modifications
[sfrench/samba-autobuild/.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_asprintf_errstring(ldb,
839                                        "samldb: no SID may be specified in user/group modifications for %s",
840                                        ldb_dn_get_linearized(ac->msg->dn));
841                 return LDB_ERR_UNWILLING_TO_PERFORM;
842         }
843
844         /* but generate a new SID when we do have an add operations */
845         if ((sid == NULL) && (ac->req->operation == LDB_ADD)) {
846                 sid_generator = lpcfg_sid_generator(lp_ctx);
847                 if (sid_generator == SID_GENERATOR_INTERNAL) {
848                         ret = samldb_add_step(ac, samldb_allocate_sid);
849                         if (ret != LDB_SUCCESS) return ret;
850                 }
851         }
852
853         if (strcmp(ac->type, "user") == 0) {
854                 /* Step 1.2: Default values */
855                 tempstr = talloc_asprintf(ac->msg, "%d", UF_NORMAL_ACCOUNT);
856                 if (tempstr == NULL) return ldb_operr(ldb);
857                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
858                         "userAccountControl", tempstr);
859                 if (ret != LDB_SUCCESS) return ret;
860                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
861                         "badPwdCount", "0");
862                 if (ret != LDB_SUCCESS) return ret;
863                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
864                         "codePage", "0");
865                 if (ret != LDB_SUCCESS) return ret;
866                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
867                         "countryCode", "0");
868                 if (ret != LDB_SUCCESS) return ret;
869                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
870                         "badPasswordTime", "0");
871                 if (ret != LDB_SUCCESS) return ret;
872                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
873                         "lastLogoff", "0");
874                 if (ret != LDB_SUCCESS) return ret;
875                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
876                         "lastLogon", "0");
877                 if (ret != LDB_SUCCESS) return ret;
878                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
879                         "pwdLastSet", "0");
880                 if (ret != LDB_SUCCESS) return ret;
881                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
882                         "accountExpires", "9223372036854775807");
883                 if (ret != LDB_SUCCESS) return ret;
884                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
885                         "logonCount", "0");
886                 if (ret != LDB_SUCCESS) return ret;
887
888                 el = ldb_msg_find_element(ac->msg, "userAccountControl");
889                 if (el != NULL) {
890                         uint32_t user_account_control, account_type;
891
892                         /* Step 1.3: "userAccountControl" -> "sAMAccountType" mapping */
893                         user_account_control = ldb_msg_find_attr_as_uint(ac->msg,
894                                                                          "userAccountControl",
895                                                                          0);
896
897                         /* Temporary duplicate accounts aren't allowed */
898                         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
899                                 return LDB_ERR_OTHER;
900                         }
901
902                         account_type = ds_uf2atype(user_account_control);
903                         if (account_type == 0) {
904                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
905                                 return LDB_ERR_UNWILLING_TO_PERFORM;
906                         }
907                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
908                                                  "sAMAccountType",
909                                                  account_type);
910                         if (ret != LDB_SUCCESS) {
911                                 return ret;
912                         }
913                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
914                         el2->flags = LDB_FLAG_MOD_REPLACE;
915
916                         if (user_account_control &
917                             (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
918                                 ret = samdb_msg_set_string(ldb, ac->msg, ac->msg,
919                                                            "isCriticalSystemObject",
920                                                            "TRUE");
921                                 if (ret != LDB_SUCCESS) {
922                                         return ret;
923                                 }
924                                 el2 = ldb_msg_find_element(ac->msg,
925                                                            "isCriticalSystemObject");
926                                 el2->flags = LDB_FLAG_MOD_REPLACE;
927                         }
928
929                         /* Step 1.4: "userAccountControl" -> "primaryGroupID" mapping */
930                         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
931                                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
932                                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
933                                                          "primaryGroupID", rid);
934                                 if (ret != LDB_SUCCESS) {
935                                         return ret;
936                                 }
937                                 el2 = ldb_msg_find_element(ac->msg,
938                                                            "primaryGroupID");
939                                 el2->flags = LDB_FLAG_MOD_REPLACE;
940                         }
941
942                         /* Step 1.5: Add additional flags when needed */
943                         if ((user_account_control & UF_NORMAL_ACCOUNT) &&
944                             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
945                                 user_account_control |= UF_ACCOUNTDISABLE;
946                                 user_account_control |= UF_PASSWD_NOTREQD;
947
948                                 ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
949                                                          "userAccountControl",
950                                                          user_account_control);
951                                 if (ret != LDB_SUCCESS) {
952                                         return ret;
953                                 }
954                         }
955                 }
956
957         } else if (strcmp(ac->type, "group") == 0) {
958                 /* Step 2.2: Default values */
959                 tempstr = talloc_asprintf(ac->msg, "%d",
960                                           GTYPE_SECURITY_GLOBAL_GROUP);
961                 if (tempstr == NULL) return ldb_operr(ldb);
962                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
963                         "groupType", tempstr);
964                 if (ret != LDB_SUCCESS) return ret;
965
966                 /* Step 2.3: "groupType" -> "sAMAccountType" */
967                 el = ldb_msg_find_element(ac->msg, "groupType");
968                 if (el != NULL) {
969                         uint32_t group_type, account_type;
970
971                         group_type = ldb_msg_find_attr_as_uint(ac->msg,
972                                                                "groupType", 0);
973
974                         /* The creation of builtin groups requires the
975                          * RELAX control */
976                         if (group_type == GTYPE_SECURITY_BUILTIN_LOCAL_GROUP) {
977                                 if (ldb_request_get_control(ac->req,
978                                                             LDB_CONTROL_RELAX_OID) == NULL) {
979                                         return LDB_ERR_UNWILLING_TO_PERFORM;
980                                 }
981                         }
982
983                         account_type = ds_gtype2atype(group_type);
984                         if (account_type == 0) {
985                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
986                                 return LDB_ERR_UNWILLING_TO_PERFORM;
987                         }
988                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
989                                                  "sAMAccountType",
990                                                  account_type);
991                         if (ret != LDB_SUCCESS) {
992                                 return ret;
993                         }
994                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
995                         el2->flags = LDB_FLAG_MOD_REPLACE;
996                 }
997         }
998
999         return LDB_SUCCESS;
1000 }
1001
1002 /*
1003  * "Primary group ID" trigger (MS-SAMR 3.1.1.8.2)
1004  *
1005  * Has to be invoked on "add" and "modify" operations on "user" and "computer"
1006  * objects.
1007  * ac->msg contains the "add"/"modify" message
1008  */
1009
1010 static int samldb_prim_group_set(struct samldb_ctx *ac)
1011 {
1012         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1013         struct ldb_dn *prim_group_dn;
1014         uint32_t rid;
1015         struct dom_sid *sid;
1016
1017         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1018         if (rid == (uint32_t) -1) {
1019                 /* we aren't affected of any primary group set */
1020                 return LDB_SUCCESS;
1021
1022         } else if (!ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
1023                 ldb_set_errstring(ldb,
1024                                   "The primary group isn't settable on add operations!");
1025                 return LDB_ERR_UNWILLING_TO_PERFORM;
1026         }
1027
1028         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1029         if (sid == NULL) {
1030                 return ldb_operr(ldb);
1031         }
1032
1033         prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1034                                         ldap_encode_ndr_dom_sid(ac, sid));
1035         if (prim_group_dn == NULL) {
1036                 ldb_asprintf_errstring(ldb,
1037                                        "Failed to find primary group with RID %u!",
1038                                        rid);
1039                 return LDB_ERR_UNWILLING_TO_PERFORM;
1040         }
1041
1042         return LDB_SUCCESS;
1043 }
1044
1045 static int samldb_prim_group_change(struct samldb_ctx *ac)
1046 {
1047         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1048         const char * attrs[] = { "primaryGroupID", "memberOf", NULL };
1049         struct ldb_result *res;
1050         struct ldb_message_element *el;
1051         struct ldb_message *msg;
1052         uint32_t rid;
1053         struct dom_sid *sid;
1054         struct ldb_dn *prev_prim_group_dn, *new_prim_group_dn;
1055         int ret;
1056
1057         ret = samldb_get_single_valued_attr(ac, "primaryGroupID", &el);
1058         if (ret != LDB_SUCCESS) {
1059                 return ret;
1060         }
1061         if (el == NULL) {
1062                 /* we are not affected */
1063                 return LDB_SUCCESS;
1064         }
1065
1066         /* Fetch informations from the existing object */
1067
1068         ret = ldb_search(ldb, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1069                          NULL);
1070         if (ret != LDB_SUCCESS) {
1071                 return ret;
1072         }
1073         if (res->count != 1) {
1074                 return ldb_operr(ldb);
1075         }
1076
1077         /* Finds out the DN of the old primary group */
1078
1079         rid = ldb_msg_find_attr_as_uint(res->msgs[0], "primaryGroupID", (uint32_t) -1);
1080         if (rid == (uint32_t) -1) {
1081                 /* User objects do always have a mandatory "primaryGroupID"
1082                  * attribute. If this doesn't exist then the object is of the
1083                  * wrong type. This is the exact Windows error code */
1084                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1085         }
1086
1087         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1088         if (sid == NULL) {
1089                 return ldb_operr(ldb);
1090         }
1091
1092         prev_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1093                                              ldap_encode_ndr_dom_sid(ac, sid));
1094         if (prev_prim_group_dn == NULL) {
1095                 return ldb_operr(ldb);
1096         }
1097
1098         /* Finds out the DN of the new primary group
1099          * Notice: in order to parse the primary group ID correctly we create
1100          * a temporary message here. */
1101
1102         msg = ldb_msg_new(ac->msg);
1103         if (msg == NULL) {
1104                 return ldb_module_oom(ac->module);
1105         }
1106         ret = ldb_msg_add(msg, el, 0);
1107         if (ret != LDB_SUCCESS) {
1108                 return ret;
1109         }
1110         rid = ldb_msg_find_attr_as_uint(msg, "primaryGroupID", (uint32_t) -1);
1111         talloc_free(msg);
1112         if (rid == (uint32_t) -1) {
1113                 /* we aren't affected of any primary group change */
1114                 return LDB_SUCCESS;
1115         }
1116
1117         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1118         if (sid == NULL) {
1119                 return ldb_operr(ldb);
1120         }
1121
1122         new_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1123                                             ldap_encode_ndr_dom_sid(ac, sid));
1124         if (new_prim_group_dn == NULL) {
1125                 /* Here we know if the specified new primary group candidate is
1126                  * valid or not. */
1127                 return LDB_ERR_UNWILLING_TO_PERFORM;
1128         }
1129
1130         /* Only update the "member" attributes when we really do have a change */
1131         if (ldb_dn_compare(new_prim_group_dn, prev_prim_group_dn) != 0) {
1132                 /* We need to be already a normal member of the new primary
1133                  * group in order to be successful. */
1134                 el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1135                                           ldb_dn_get_linearized(new_prim_group_dn));
1136                 if (el == NULL) {
1137                         return LDB_ERR_UNWILLING_TO_PERFORM;
1138                 }
1139
1140                 /* Remove the "member" attribute on the new primary group */
1141                 msg = ldb_msg_new(ac->msg);
1142                 if (msg == NULL) {
1143                         return ldb_module_oom(ac->module);
1144                 }
1145                 msg->dn = new_prim_group_dn;
1146
1147                 ret = samdb_msg_add_delval(ldb, msg, msg, "member",
1148                                            ldb_dn_get_linearized(ac->msg->dn));
1149                 if (ret != LDB_SUCCESS) {
1150                         return ret;
1151                 }
1152
1153                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1154                 if (ret != LDB_SUCCESS) {
1155                         return ret;
1156                 }
1157                 talloc_free(msg);
1158
1159                 /* Add a "member" attribute for the previous primary group */
1160                 msg = ldb_msg_new(ac->msg);
1161                 if (msg == NULL) {
1162                         return ldb_module_oom(ac->module);
1163                 }
1164                 msg->dn = prev_prim_group_dn;
1165
1166                 ret = samdb_msg_add_addval(ldb, msg, msg, "member",
1167                                            ldb_dn_get_linearized(ac->msg->dn));
1168                 if (ret != LDB_SUCCESS) {
1169                         return ret;
1170                 }
1171
1172                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1173                 if (ret != LDB_SUCCESS) {
1174                         return ret;
1175                 }
1176                 talloc_free(msg);
1177         }
1178
1179         talloc_free(res);
1180
1181         return LDB_SUCCESS;
1182 }
1183
1184 static int samldb_prim_group_trigger(struct samldb_ctx *ac)
1185 {
1186         int ret;
1187
1188         if (ac->req->operation == LDB_ADD) {
1189                 ret = samldb_prim_group_set(ac);
1190         } else {
1191                 ret = samldb_prim_group_change(ac);
1192         }
1193
1194         return ret;
1195 }
1196
1197 static int samldb_user_account_control_change(struct samldb_ctx *ac)
1198 {
1199         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1200         uint32_t user_account_control, account_type;
1201         struct ldb_message_element *el;
1202         struct ldb_message *tmp_msg;
1203         int ret;
1204
1205         ret = samldb_get_single_valued_attr(ac, "userAccountControl", &el);
1206         if (ret != LDB_SUCCESS) {
1207                 return ret;
1208         }
1209         if (el == NULL) {
1210                 /* we are not affected */
1211                 return LDB_SUCCESS;
1212         }
1213
1214         /* Create a temporary message for fetching the "userAccountControl" */
1215         tmp_msg = ldb_msg_new(ac->msg);
1216         if (tmp_msg == NULL) {
1217                 return ldb_module_oom(ac->module);
1218         }
1219         ret = ldb_msg_add(tmp_msg, el, 0);
1220         if (ret != LDB_SUCCESS) {
1221                 return ret;
1222         }
1223         user_account_control = ldb_msg_find_attr_as_uint(tmp_msg,
1224                                                          "userAccountControl",
1225                                                          0);
1226         talloc_free(tmp_msg);
1227
1228         /* Temporary duplicate accounts aren't allowed */
1229         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
1230                 return LDB_ERR_OTHER;
1231         }
1232
1233         account_type = ds_uf2atype(user_account_control);
1234         if (account_type == 0) {
1235                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1236                 return LDB_ERR_UNWILLING_TO_PERFORM;
1237         }
1238         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1239                                  account_type);
1240         if (ret != LDB_SUCCESS) {
1241                 return ret;
1242         }
1243         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1244         el->flags = LDB_FLAG_MOD_REPLACE;
1245
1246         if (user_account_control
1247             & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1248                 ret = samdb_msg_add_string(ldb, ac->msg, ac->msg,
1249                                            "isCriticalSystemObject", "TRUE");
1250                 if (ret != LDB_SUCCESS) {
1251                         return ret;
1252                 }
1253                 el = ldb_msg_find_element(ac->msg,
1254                                            "isCriticalSystemObject");
1255                 el->flags = LDB_FLAG_MOD_REPLACE;
1256         }
1257
1258         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
1259                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
1260                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1261                                          "primaryGroupID", rid);
1262                 if (ret != LDB_SUCCESS) {
1263                         return ret;
1264                 }
1265                 el = ldb_msg_find_element(ac->msg,
1266                                            "primaryGroupID");
1267                 el->flags = LDB_FLAG_MOD_REPLACE;
1268         }
1269
1270         return LDB_SUCCESS;
1271 }
1272
1273 static int samldb_group_type_change(struct samldb_ctx *ac)
1274 {
1275         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1276         uint32_t group_type, old_group_type, account_type;
1277         struct ldb_message_element *el;
1278         struct ldb_message *tmp_msg;
1279         int ret;
1280
1281         ret = samldb_get_single_valued_attr(ac, "groupType", &el);
1282         if (ret != LDB_SUCCESS) {
1283                 return ret;
1284         }
1285         if (el == NULL) {
1286                 /* we are not affected */
1287                 return LDB_SUCCESS;
1288         }
1289
1290         /* Create a temporary message for fetching the "groupType" */
1291         tmp_msg = ldb_msg_new(ac->msg);
1292         if (tmp_msg == NULL) {
1293                 return ldb_module_oom(ac->module);
1294         }
1295         ret = ldb_msg_add(tmp_msg, el, 0);
1296         if (ret != LDB_SUCCESS) {
1297                 return ret;
1298         }
1299         group_type = ldb_msg_find_attr_as_uint(tmp_msg, "groupType", 0);
1300         talloc_free(tmp_msg);
1301
1302         old_group_type = samdb_search_uint(ldb, ac, 0, ac->msg->dn,
1303                                            "groupType", NULL);
1304         if (old_group_type == 0) {
1305                 return ldb_operr(ldb);
1306         }
1307
1308         /* Group type switching isn't so easy as it seems: We can only
1309          * change in this directions: global <-> universal <-> local
1310          * On each step also the group type itself
1311          * (security/distribution) is variable. */
1312
1313         switch (group_type) {
1314         case GTYPE_SECURITY_GLOBAL_GROUP:
1315         case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
1316                 /* change to "universal" allowed */
1317                 if ((old_group_type == GTYPE_SECURITY_DOMAIN_LOCAL_GROUP) ||
1318                     (old_group_type == GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP)) {
1319                         return LDB_ERR_UNWILLING_TO_PERFORM;
1320                 }
1321         break;
1322
1323         case GTYPE_SECURITY_UNIVERSAL_GROUP:
1324         case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
1325                 /* each change allowed */
1326         break;
1327
1328         case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
1329         case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
1330                 /* change to "universal" allowed */
1331                 if ((old_group_type == GTYPE_SECURITY_GLOBAL_GROUP) ||
1332                     (old_group_type == GTYPE_DISTRIBUTION_GLOBAL_GROUP)) {
1333                         return LDB_ERR_UNWILLING_TO_PERFORM;
1334                 }
1335         break;
1336
1337         case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
1338         default:
1339                 /* we don't allow this "groupType" values */
1340                 return LDB_ERR_UNWILLING_TO_PERFORM;
1341         break;
1342         }
1343
1344         account_type =  ds_gtype2atype(group_type);
1345         if (account_type == 0) {
1346                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1347                 return LDB_ERR_UNWILLING_TO_PERFORM;
1348         }
1349         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1350                                  account_type);
1351         if (ret != LDB_SUCCESS) {
1352                 return ret;
1353         }
1354         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1355         el->flags = LDB_FLAG_MOD_REPLACE;
1356
1357         return LDB_SUCCESS;
1358 }
1359
1360 static int samldb_sam_accountname_check(struct samldb_ctx *ac)
1361 {
1362         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1363         const char *no_attrs[] = { NULL };
1364         struct ldb_result *res;
1365         const char *sam_accountname, *enc_str;
1366         struct ldb_message_element *el;
1367         struct ldb_message *tmp_msg;
1368         int ret;
1369
1370         ret = samldb_get_single_valued_attr(ac, "sAMAccountName", &el);
1371         if (ret != LDB_SUCCESS) {
1372                 return ret;
1373         }
1374         if (el == NULL) {
1375                 /* we are not affected */
1376                 return LDB_SUCCESS;
1377         }
1378
1379         /* Create a temporary message for fetching the "sAMAccountName" */
1380         tmp_msg = ldb_msg_new(ac->msg);
1381         if (tmp_msg == NULL) {
1382                 return ldb_module_oom(ac->module);
1383         }
1384         ret = ldb_msg_add(tmp_msg, el, 0);
1385         if (ret != LDB_SUCCESS) {
1386                 return ret;
1387         }
1388         sam_accountname = ldb_msg_find_attr_as_string(tmp_msg, "sAMAccountName",
1389                                                       NULL);
1390         talloc_free(tmp_msg);
1391
1392         if (sam_accountname == NULL) {
1393                 return ldb_operr(ldb);
1394         }
1395
1396         enc_str = ldb_binary_encode_string(ac, sam_accountname);
1397         if (enc_str == NULL) {
1398                 return ldb_module_oom(ac->module);
1399         }
1400
1401         /* Make sure that a "sAMAccountName" is only used once */
1402
1403         ret = ldb_search(ldb, ac, &res, NULL, LDB_SCOPE_SUBTREE, no_attrs,
1404                          "(sAMAccountName=%s)", enc_str);
1405         if (ret != LDB_SUCCESS) {
1406                 return ret;
1407         }
1408         if (res->count > 1) {
1409                 return ldb_operr(ldb);
1410         } else if (res->count == 1) {
1411                 if (ldb_dn_compare(res->msgs[0]->dn, ac->msg->dn) != 0) {
1412                         ldb_asprintf_errstring(ldb,
1413                                                "samldb: Account name (sAMAccountName) '%s' already in use!",
1414                                                sam_accountname);
1415                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
1416                 }
1417         }
1418         talloc_free(res);
1419
1420         return LDB_SUCCESS;
1421 }
1422
1423 static int samldb_member_check(struct samldb_ctx *ac)
1424 {
1425         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1426         struct ldb_message_element *el;
1427         struct ldb_dn *member_dn, *group_dn;
1428         uint32_t prim_group_rid;
1429         struct dom_sid *sid;
1430         unsigned int i, j;
1431         int cnt;
1432
1433         /* We've to walk over all modification entries and consider the "member"
1434          * ones. */
1435         for (i = 0; i < ac->msg->num_elements; i++) {
1436                 if (ldb_attr_cmp(ac->msg->elements[i].name, "member") != 0) {
1437                         continue;
1438                 }
1439
1440                 el = &ac->msg->elements[i];
1441                 for (j = 0; j < el->num_values; j++) {
1442                         member_dn = ldb_dn_from_ldb_val(ac, ldb,
1443                                                         &el->values[j]);
1444                         if (!ldb_dn_validate(member_dn)) {
1445                                 return ldb_operr(ldb);
1446                         }
1447
1448                         /* The "member" attribute can be modified with the
1449                          * following restrictions (beside a valid DN):
1450                          *
1451                          * - "add" operations can only be performed when the
1452                          *   member still doesn't exist - if not then return
1453                          *   ERR_ENTRY_ALREADY_EXISTS (not
1454                          *   ERR_ATTRIBUTE_OR_VALUE_EXISTS!)
1455                          * - "delete" operations can only be performed when the
1456                          *   member does exist - if not then return
1457                          *   ERR_UNWILLING_TO_PERFORM (not
1458                          *   ERR_NO_SUCH_ATTRIBUTE!)
1459                          * - primary group check
1460                          */
1461                         cnt = samdb_search_count(ldb, ac, ac->msg->dn,
1462                                                  "(member=%s)",
1463                                                  ldb_dn_get_linearized(member_dn));
1464                         if (cnt < 0) {
1465                                 return ldb_operr(ldb);
1466                         }
1467                         if ((cnt > 0) && (LDB_FLAG_MOD_TYPE(el->flags)
1468                             == LDB_FLAG_MOD_ADD)) {
1469                                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1470                         }
1471                         if ((cnt == 0) && LDB_FLAG_MOD_TYPE(el->flags)
1472                             == LDB_FLAG_MOD_DELETE) {
1473                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1474                         }
1475
1476                         /* Denies to add "member"s to groups which are primary
1477                          * ones for them - in this case return
1478                          * ERR_ENTRY_ALREADY_EXISTS. */
1479
1480                         prim_group_rid = samdb_search_uint(ldb, ac,
1481                                                            (uint32_t) -1,
1482                                                            member_dn,
1483                                                            "primaryGroupID",
1484                                                            NULL);
1485                         if (prim_group_rid == (uint32_t) -1) {
1486                                 /* the member hasn't to be a user account ->
1487                                  * therefore no check needed in this case. */
1488                                 continue;
1489                         }
1490
1491                         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
1492                                               prim_group_rid);
1493                         if (sid == NULL) {
1494                                 return ldb_operr(ldb);
1495                         }
1496
1497                         group_dn = samdb_search_dn(ldb, ac, NULL,
1498                                                    "(objectSid=%s)",
1499                                                    ldap_encode_ndr_dom_sid(ac, sid));
1500                         if (group_dn == NULL) {
1501                                 return ldb_operr(ldb);
1502                         }
1503
1504                         if (ldb_dn_compare(group_dn, ac->msg->dn) == 0) {
1505                                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1506                         }
1507                 }
1508         }
1509
1510         return LDB_SUCCESS;
1511 }
1512
1513 /* This trigger adapts the "servicePrincipalName" attributes if the
1514  * "dNSHostName" attribute changes */
1515 static int samldb_service_principal_names_change(struct samldb_ctx *ac)
1516 {
1517         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1518         struct ldb_message_element *el = NULL;
1519         struct ldb_message *msg;
1520         const char *attrs[] = { "servicePrincipalName", NULL };
1521         struct ldb_result *res;
1522         const char *dns_hostname, *old_dns_hostname;
1523         unsigned int i;
1524         int ret;
1525
1526         /* Here it's not the same logic as with "samldb_get_single_valued_attr".
1527          * We need to:
1528          *
1529          * - consider "add" and "replace" operations - the last value we take
1530          * - ignore "delete" operations - obviously this attribute isn't
1531          *   write protected
1532          */
1533         for (i = 0; i < ac->msg->num_elements; i++) {
1534                 if (ldb_attr_cmp(ac->msg->elements[i].name,
1535                                  "dNSHostName") != 0) {
1536                         continue;
1537                 }
1538
1539                 if (LDB_FLAG_MOD_TYPE(ac->msg->elements[i].flags)
1540                     != LDB_FLAG_MOD_DELETE) {
1541                         el = &ac->msg->elements[i];
1542                 }
1543         }
1544         if (el == NULL) {
1545                 /* we are not affected */
1546                 return LDB_SUCCESS;
1547         }
1548
1549         /* Create a temporary message for fetching the "dNSHostName" */
1550         msg = ldb_msg_new(ac->msg);
1551         if (msg == NULL) {
1552                 return ldb_module_oom(ac->module);
1553         }
1554         ret = ldb_msg_add(msg, el, 0);
1555         if (ret != LDB_SUCCESS) {
1556                 return ret;
1557         }
1558         dns_hostname = ldb_msg_find_attr_as_string(msg, "dNSHostName", "");
1559         talloc_free(msg);
1560
1561         old_dns_hostname = samdb_search_string(ldb, ac, ac->msg->dn,
1562                                                "dNSHostName", NULL);
1563         if ((old_dns_hostname == NULL) || (strcasecmp(old_dns_hostname,
1564                                                       dns_hostname) == 0)) {
1565                 /* Well, if there's no old DNS hostname then we cannot do this.
1566                  * And if old and new DNS name do match we are also finished
1567                  * here. */
1568                 return LDB_SUCCESS;
1569         }
1570
1571         /* Potential "servicePrincipalName" changes in the same request have to
1572          * be handled before the update (Windows behaviour). */
1573         el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
1574         if (el != NULL) {
1575                 msg = ldb_msg_new(ac->msg);
1576                 if (msg == NULL) {
1577                         return ldb_module_oom(ac->module);
1578                 }
1579                 msg->dn = ac->msg->dn;
1580
1581                 do {
1582                         ret = ldb_msg_add(msg, el, el->flags);
1583                         if (ret != LDB_SUCCESS) {
1584                                 return ret;
1585                         }
1586
1587                         ldb_msg_remove_element(ac->msg, el);
1588
1589                         el = ldb_msg_find_element(ac->msg,
1590                                                   "servicePrincipalName");
1591                 } while (el != NULL);
1592
1593                 ret = dsdb_module_modify(ac->module, msg,
1594                                          DSDB_FLAG_NEXT_MODULE);
1595                 if (ret != LDB_SUCCESS) {
1596                         return ret;
1597                 }
1598                 talloc_free(msg);
1599         }
1600
1601         /* Fetch the "servicePrincipalName"s if any */
1602         ret = ldb_search(ldb, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1603                          NULL);
1604         if (ret != LDB_SUCCESS) {
1605                 return ret;
1606         }
1607         if ((res->count != 1) || (res->msgs[0]->num_elements > 1)) {
1608                 return ldb_operr(ldb);
1609         }
1610
1611         if (res->msgs[0]->num_elements == 1) {
1612                 /* Yes, we do have "servicePrincipalName"s. First we update them
1613                  * locally, that means we do always substitute the current
1614                  * "dNSHostName" with the new one and then we append this to the
1615                  * modification request (Windows behaviour). */
1616
1617                 for (i = 0; i < res->msgs[0]->elements[0].num_values; i++) {
1618                         char *old_str, *new_str, *pos;
1619                         const char *tok;
1620
1621                         old_str = (char *)
1622                                 res->msgs[0]->elements[0].values[i].data;
1623
1624                         new_str = talloc_strdup(ac->msg,
1625                                                 strtok_r(old_str, "/", &pos));
1626                         if (new_str == NULL) {
1627                                 return ldb_module_oom(ac->module);
1628                         }
1629
1630                         while ((tok = strtok_r(NULL, "/", &pos)) != NULL) {
1631                                 if (strcasecmp(tok, old_dns_hostname) == 0) {
1632                                         tok = dns_hostname;
1633                                 }
1634
1635                                 new_str = talloc_asprintf(ac->msg, "%s/%s",
1636                                                           new_str, tok);
1637                                 if (new_str == NULL) {
1638                                         return ldb_module_oom(ac->module);
1639                                 }
1640                         }
1641
1642                         ret = ldb_msg_add_string(ac->msg,
1643                                                  "servicePrincipalName",
1644                                                  new_str);
1645                         if (ret != LDB_SUCCESS) {
1646                                 return ret;
1647                         }
1648                 }
1649
1650                 el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
1651                 el->flags = LDB_FLAG_MOD_REPLACE;
1652         }
1653
1654         talloc_free(res);
1655
1656         return LDB_SUCCESS;
1657 }
1658
1659
1660 /* add */
1661 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
1662 {
1663         struct ldb_context *ldb;
1664         struct samldb_ctx *ac;
1665         int ret;
1666
1667         ldb = ldb_module_get_ctx(module);
1668         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
1669
1670         /* do not manipulate our control entries */
1671         if (ldb_dn_is_special(req->op.add.message->dn)) {
1672                 return ldb_next_request(module, req);
1673         }
1674
1675         ac = samldb_ctx_init(module, req);
1676         if (ac == NULL) {
1677                 return ldb_operr(ldb);
1678         }
1679
1680         /* build the new msg */
1681         ac->msg = ldb_msg_copy_shallow(ac, req->op.add.message);
1682         if (ac->msg == NULL) {
1683                 talloc_free(ac);
1684                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1685                           "samldb_add: ldb_msg_copy_shallow failed!\n");
1686                 return ldb_operr(ldb);
1687         }
1688
1689         if (samdb_find_attribute(ldb, ac->msg,
1690                                  "objectclass", "user") != NULL) {
1691                 ac->type = "user";
1692
1693                 ret = samldb_prim_group_trigger(ac);
1694                 if (ret != LDB_SUCCESS) {
1695                         return ret;
1696                 }
1697
1698                 ret = samldb_objectclass_trigger(ac);
1699                 if (ret != LDB_SUCCESS) {
1700                         return ret;
1701                 }
1702
1703                 return samldb_fill_object(ac);
1704         }
1705
1706         if (samdb_find_attribute(ldb, ac->msg,
1707                                  "objectclass", "group") != NULL) {
1708                 ac->type = "group";
1709
1710                 ret = samldb_objectclass_trigger(ac);
1711                 if (ret != LDB_SUCCESS) {
1712                         return ret;
1713                 }
1714
1715                 return samldb_fill_object(ac);
1716         }
1717
1718         /* perhaps a foreignSecurityPrincipal? */
1719         if (samdb_find_attribute(ldb, ac->msg,
1720                                  "objectclass",
1721                                  "foreignSecurityPrincipal") != NULL) {
1722                 return samldb_fill_foreignSecurityPrincipal_object(ac);
1723         }
1724
1725         if (samdb_find_attribute(ldb, ac->msg,
1726                                  "objectclass", "classSchema") != NULL) {
1727                 ret = samldb_schema_info_update(ac);
1728                 if (ret != LDB_SUCCESS) {
1729                         talloc_free(ac);
1730                         return ret;
1731                 }
1732
1733                 ac->type = "classSchema";
1734                 return samldb_fill_object(ac);
1735         }
1736
1737         if (samdb_find_attribute(ldb, ac->msg,
1738                                  "objectclass", "attributeSchema") != NULL) {
1739                 ret = samldb_schema_info_update(ac);
1740                 if (ret != LDB_SUCCESS) {
1741                         talloc_free(ac);
1742                         return ret;
1743                 }
1744
1745                 ac->type = "attributeSchema";
1746                 return samldb_fill_object(ac);
1747         }
1748
1749         talloc_free(ac);
1750
1751         /* nothing matched, go on */
1752         return ldb_next_request(module, req);
1753 }
1754
1755 /* modify */
1756 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
1757 {
1758         struct ldb_context *ldb;
1759         struct samldb_ctx *ac;
1760         struct ldb_message_element *el;
1761         bool modified = false;
1762         int ret;
1763
1764         if (ldb_dn_is_special(req->op.mod.message->dn)) {
1765                 /* do not manipulate our control entries */
1766                 return ldb_next_request(module, req);
1767         }
1768
1769         ldb = ldb_module_get_ctx(module);
1770
1771         /* make sure that "sAMAccountType" is not specified */
1772         el = ldb_msg_find_element(req->op.mod.message, "sAMAccountType");
1773         if (el != NULL) {
1774                 ldb_set_errstring(ldb,
1775                                   "samldb: sAMAccountType must not be specified!");
1776                 return LDB_ERR_UNWILLING_TO_PERFORM;
1777         }
1778         /* make sure that "isCriticalSystemObject" is not specified */
1779         el = ldb_msg_find_element(req->op.mod.message, "isCriticalSystemObject");
1780         if (el != NULL) {
1781                 if (ldb_request_get_control(req, LDB_CONTROL_RELAX_OID) == NULL) {
1782                         ldb_set_errstring(ldb,
1783                                           "samldb: isCriticalSystemObject must not be specified!");
1784                         return LDB_ERR_UNWILLING_TO_PERFORM;
1785                 }
1786         }
1787
1788         /* msDS-IntId is not allowed to be modified
1789          * except when modification comes from replication */
1790         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
1791                 if (!ldb_request_get_control(req,
1792                                              DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
1793                         return LDB_ERR_CONSTRAINT_VIOLATION;
1794                 }
1795         }
1796
1797         ac = samldb_ctx_init(module, req);
1798         if (ac == NULL) {
1799                 return ldb_operr(ldb);
1800         }
1801
1802         /* build the new msg */
1803         ac->msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
1804         if (ac->msg == NULL) {
1805                 talloc_free(ac);
1806                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1807                           "samldb_modify: ldb_msg_copy_shallow failed!\n");
1808                 return ldb_operr(ldb);
1809         }
1810
1811         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
1812         if (el != NULL) {
1813                 ret = samldb_prim_group_change(ac);
1814                 if (ret != LDB_SUCCESS) {
1815                         return ret;
1816                 }
1817         }
1818
1819         el = ldb_msg_find_element(ac->msg, "userAccountControl");
1820         if (el != NULL) {
1821                 modified = true;
1822                 ret = samldb_user_account_control_change(ac);
1823                 if (ret != LDB_SUCCESS) {
1824                         return ret;
1825                 }
1826         }
1827
1828         el = ldb_msg_find_element(ac->msg, "groupType");
1829         if (el != NULL) {
1830                 modified = true;
1831                 ret = samldb_group_type_change(ac);
1832                 if (ret != LDB_SUCCESS) {
1833                         return ret;
1834                 }
1835         }
1836
1837         el = ldb_msg_find_element(ac->msg, "sAMAccountName");
1838         if (el != NULL) {
1839                 ret = samldb_sam_accountname_check(ac);
1840                 if (ret != LDB_SUCCESS) {
1841                         return ret;
1842                 }
1843         }
1844
1845         el = ldb_msg_find_element(ac->msg, "member");
1846         if (el != NULL) {
1847                 ret = samldb_member_check(ac);
1848                 if (ret != LDB_SUCCESS) {
1849                         return ret;
1850                 }
1851         }
1852
1853         el = ldb_msg_find_element(ac->msg, "dNSHostName");
1854         if (el != NULL) {
1855                 modified = true;
1856                 ret = samldb_service_principal_names_change(ac);
1857                 if (ret != LDB_SUCCESS) {
1858                         return ret;
1859                 }
1860         }
1861
1862         if (modified) {
1863                 struct ldb_request *child_req;
1864
1865                 /* Now perform the real modifications as a child request */
1866                 ret = ldb_build_mod_req(&child_req, ldb, ac,
1867                                         ac->msg,
1868                                         req->controls,
1869                                         req, dsdb_next_callback,
1870                                         req);
1871                 LDB_REQ_SET_LOCATION(child_req);
1872                 if (ret != LDB_SUCCESS) {
1873                         return ret;
1874                 }
1875
1876                 return ldb_next_request(module, child_req);
1877         }
1878
1879         talloc_free(ac);
1880
1881         /* no change which interests us, go on */
1882         return ldb_next_request(module, req);
1883 }
1884
1885 /* delete */
1886
1887 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
1888 {
1889         struct ldb_context *ldb;
1890         struct dom_sid *sid;
1891         uint32_t rid;
1892         NTSTATUS status;
1893         int count;
1894
1895         ldb = ldb_module_get_ctx(ac->module);
1896
1897         /* Finds out the SID/RID of the SAM object */
1898         sid = samdb_search_dom_sid(ldb, ac, ac->req->op.del.dn, "objectSid",
1899                                    NULL);
1900         if (sid == NULL) {
1901                 /* No SID - it might not be a SAM object - therefore ok */
1902                 return LDB_SUCCESS;
1903         }
1904         status = dom_sid_split_rid(ac, sid, NULL, &rid);
1905         if (!NT_STATUS_IS_OK(status)) {
1906                 return ldb_operr(ldb);
1907         }
1908         if (rid == 0) {
1909                 /* Special object (security principal?) */
1910                 return LDB_SUCCESS;
1911         }
1912
1913         /* Deny delete requests from groups which are primary ones */
1914         count = samdb_search_count(ldb, ac, NULL,
1915                                    "(&(primaryGroupID=%u)(objectClass=user))",
1916                                    rid);
1917         if (count < 0) {
1918                 return ldb_operr(ldb);
1919         }
1920         if (count > 0) {
1921                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1922         }
1923
1924         return LDB_SUCCESS;
1925 }
1926
1927 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
1928 {
1929         struct samldb_ctx *ac;
1930         int ret;
1931
1932         if (ldb_dn_is_special(req->op.del.dn)) {
1933                 /* do not manipulate our control entries */
1934                 return ldb_next_request(module, req);
1935         }
1936
1937         ac = samldb_ctx_init(module, req);
1938         if (ac == NULL) {
1939                 return ldb_operr(ldb_module_get_ctx(module));
1940         }
1941
1942         ret = samldb_prim_group_users_check(ac);
1943         if (ret != LDB_SUCCESS) {
1944                 return ret;
1945         }
1946
1947         talloc_free(ac);
1948
1949         return ldb_next_request(module, req);
1950 }
1951
1952 /* extended */
1953
1954 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
1955 {
1956         struct ldb_context *ldb = ldb_module_get_ctx(module);
1957         struct dsdb_fsmo_extended_op *exop;
1958         int ret;
1959
1960         exop = talloc_get_type(req->op.extended.data,
1961                                struct dsdb_fsmo_extended_op);
1962         if (!exop) {
1963                 ldb_set_errstring(ldb,
1964                                   "samldb_extended_allocate_rid_pool: invalid extended data");
1965                 return LDB_ERR_PROTOCOL_ERROR;
1966         }
1967
1968         ret = ridalloc_allocate_rid_pool_fsmo(module, exop);
1969         if (ret != LDB_SUCCESS) {
1970                 return ret;
1971         }
1972
1973         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1974 }
1975
1976 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
1977 {
1978         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
1979                 return samldb_extended_allocate_rid_pool(module, req);
1980         }
1981
1982         return ldb_next_request(module, req);
1983 }
1984
1985
1986 _PUBLIC_ const struct ldb_module_ops ldb_samldb_module_ops = {
1987         .name          = "samldb",
1988         .add           = samldb_add,
1989         .modify        = samldb_modify,
1990         .del           = samldb_delete,
1991         .extended      = samldb_extended
1992 };
1993