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