s4:samldb LDB module - fix the behaviour when changing the "userAccountControl"
[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                         if (user_account_control &
915                             (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
916                                 ret = samdb_msg_set_string(ldb, ac->msg, ac->msg,
917                                                            "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                         }
926
927                         /* Step 1.4: "userAccountControl" -> "primaryGroupID" mapping */
928                         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
929                                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
930                                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
931                                                          "primaryGroupID", rid);
932                                 if (ret != LDB_SUCCESS) {
933                                         return ret;
934                                 }
935                                 el2 = ldb_msg_find_element(ac->msg,
936                                                            "primaryGroupID");
937                                 el2->flags = LDB_FLAG_MOD_REPLACE;
938                         }
939
940                         /* Step 1.5: Add additional flags when needed */
941                         /* Obviously this is done when the "userAccountControl"
942                          * has been generated here (tested against Windows
943                          * Server) */
944                         if (uac_generated) {
945                                 user_account_control |= UF_ACCOUNTDISABLE;
946                                 user_account_control |= UF_PASSWD_NOTREQD;
947
948                                 ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
949                                                          "userAccountControl",
950                                                          user_account_control);
951                                 if (ret != LDB_SUCCESS) {
952                                         return ret;
953                                 }
954                         }
955                 }
956
957         } else if (strcmp(ac->type, "group") == 0) {
958                 const char *tempstr;
959
960                 /* Step 2.2: Default values */
961                 tempstr = talloc_asprintf(ac->msg, "%d",
962                                           GTYPE_SECURITY_GLOBAL_GROUP);
963                 if (tempstr == NULL) return ldb_operr(ldb);
964                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
965                         "groupType", tempstr);
966                 if (ret != LDB_SUCCESS) return ret;
967
968                 /* Step 2.3: "groupType" -> "sAMAccountType" */
969                 el = ldb_msg_find_element(ac->msg, "groupType");
970                 if (el != NULL) {
971                         uint32_t group_type, account_type;
972
973                         group_type = ldb_msg_find_attr_as_uint(ac->msg,
974                                                                "groupType", 0);
975
976                         /* The creation of builtin groups requires the
977                          * RELAX control */
978                         if (group_type == GTYPE_SECURITY_BUILTIN_LOCAL_GROUP) {
979                                 if (ldb_request_get_control(ac->req,
980                                                             LDB_CONTROL_RELAX_OID) == NULL) {
981                                         return LDB_ERR_UNWILLING_TO_PERFORM;
982                                 }
983                         }
984
985                         account_type = ds_gtype2atype(group_type);
986                         if (account_type == 0) {
987                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
988                                 return LDB_ERR_UNWILLING_TO_PERFORM;
989                         }
990                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
991                                                  "sAMAccountType",
992                                                  account_type);
993                         if (ret != LDB_SUCCESS) {
994                                 return ret;
995                         }
996                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
997                         el2->flags = LDB_FLAG_MOD_REPLACE;
998                 }
999         }
1000
1001         return LDB_SUCCESS;
1002 }
1003
1004 /*
1005  * "Primary group ID" trigger (MS-SAMR 3.1.1.8.2)
1006  *
1007  * Has to be invoked on "add" and "modify" operations on "user" and "computer"
1008  * objects.
1009  * ac->msg contains the "add"/"modify" message
1010  */
1011
1012 static int samldb_prim_group_set(struct samldb_ctx *ac)
1013 {
1014         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1015         uint32_t rid;
1016         struct dom_sid *sid;
1017         struct ldb_result *res;
1018         int ret;
1019         const char *noattrs[] = { NULL };
1020
1021         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1022         if (rid == (uint32_t) -1) {
1023                 /* we aren't affected of any primary group set */
1024                 return LDB_SUCCESS;
1025
1026         } else if (!ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
1027                 ldb_set_errstring(ldb,
1028                                   "The primary group isn't settable on add operations!");
1029                 return LDB_ERR_UNWILLING_TO_PERFORM;
1030         }
1031
1032         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1033         if (sid == NULL) {
1034                 return ldb_operr(ldb);
1035         }
1036
1037         ret = dsdb_module_search(ac->module, ac, &res, NULL, LDB_SCOPE_SUBTREE,
1038                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1039                                  ac->req,
1040                                  "(objectSid=%s)",
1041                                  ldap_encode_ndr_dom_sid(ac, sid));
1042         if (ret != LDB_SUCCESS) {
1043                 return ret;
1044         }
1045         if (res->count != 1) {
1046                 talloc_free(res);
1047                 ldb_asprintf_errstring(ldb,
1048                                        "Failed to find primary group with RID %u!",
1049                                        rid);
1050                 return LDB_ERR_UNWILLING_TO_PERFORM;
1051         }
1052         talloc_free(res);
1053
1054         return LDB_SUCCESS;
1055 }
1056
1057 static int samldb_prim_group_change(struct samldb_ctx *ac)
1058 {
1059         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1060         const char * attrs[] = { "primaryGroupID", "memberOf", NULL };
1061         struct ldb_result *res, *group_res;
1062         struct ldb_message_element *el;
1063         struct ldb_message *msg;
1064         uint32_t prev_rid, new_rid;
1065         struct dom_sid *prev_sid, *new_sid;
1066         struct ldb_dn *prev_prim_group_dn, *new_prim_group_dn;
1067         int ret;
1068         const char *noattrs[] = { NULL };
1069
1070         el = dsdb_get_single_valued_attr(ac->msg, "primaryGroupID",
1071                                          ac->req->operation);
1072         if (el == NULL) {
1073                 /* we are not affected */
1074                 return LDB_SUCCESS;
1075         }
1076
1077         /* Fetch information from the existing object */
1078
1079         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1080                                  DSDB_FLAG_NEXT_MODULE, ac->req, NULL);
1081         if (ret != LDB_SUCCESS) {
1082                 return ret;
1083         }
1084         if (res->count != 1) {
1085                 return ldb_operr(ldb);
1086         }
1087
1088         /* Finds out the DN of the old primary group */
1089
1090         prev_rid = ldb_msg_find_attr_as_uint(res->msgs[0], "primaryGroupID",
1091                                              (uint32_t) -1);
1092         if (prev_rid == (uint32_t) -1) {
1093                 /* User objects do always have a mandatory "primaryGroupID"
1094                  * attribute. If this doesn't exist then the object is of the
1095                  * wrong type. This is the exact Windows error code */
1096                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1097         }
1098
1099         prev_sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), prev_rid);
1100         if (prev_sid == NULL) {
1101                 return ldb_operr(ldb);
1102         }
1103
1104         /* Finds out the DN of the new primary group
1105          * Notice: in order to parse the primary group ID correctly we create
1106          * a temporary message here. */
1107
1108         msg = ldb_msg_new(ac->msg);
1109         if (msg == NULL) {
1110                 return ldb_module_oom(ac->module);
1111         }
1112         ret = ldb_msg_add(msg, el, 0);
1113         if (ret != LDB_SUCCESS) {
1114                 return ret;
1115         }
1116         new_rid = ldb_msg_find_attr_as_uint(msg, "primaryGroupID", (uint32_t) -1);
1117         talloc_free(msg);
1118         if (new_rid == (uint32_t) -1) {
1119                 /* we aren't affected of any primary group change */
1120                 return LDB_SUCCESS;
1121         }
1122
1123         if (prev_rid == new_rid) {
1124                 return LDB_SUCCESS;
1125         }
1126
1127         ret = dsdb_module_search(ac->module, ac, &group_res, NULL, LDB_SCOPE_SUBTREE,
1128                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1129                                  ac->req,
1130                                  "(objectSid=%s)",
1131                                  ldap_encode_ndr_dom_sid(ac, prev_sid));
1132         if (ret != LDB_SUCCESS) {
1133                 return ret;
1134         }
1135         if (group_res->count != 1) {
1136                 return ldb_operr(ldb);
1137         }
1138         prev_prim_group_dn = group_res->msgs[0]->dn;
1139
1140         new_sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), new_rid);
1141         if (new_sid == NULL) {
1142                 return ldb_operr(ldb);
1143         }
1144
1145         ret = dsdb_module_search(ac->module, ac, &group_res, NULL, LDB_SCOPE_SUBTREE,
1146                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1147                                  ac->req,
1148                                  "(objectSid=%s)",
1149                                  ldap_encode_ndr_dom_sid(ac, new_sid));
1150         if (ret != LDB_SUCCESS) {
1151                 return ret;
1152         }
1153         if (group_res->count != 1) {
1154                 /* Here we know if the specified new primary group candidate is
1155                  * valid or not. */
1156                 return LDB_ERR_UNWILLING_TO_PERFORM;
1157         }
1158         new_prim_group_dn = group_res->msgs[0]->dn;
1159
1160         /* We need to be already a normal member of the new primary
1161          * group in order to be successful. */
1162         el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1163                                   ldb_dn_get_linearized(new_prim_group_dn));
1164         if (el == NULL) {
1165                 return LDB_ERR_UNWILLING_TO_PERFORM;
1166         }
1167
1168         /* Remove the "member" attribute on the new primary group */
1169         msg = ldb_msg_new(ac->msg);
1170         if (msg == NULL) {
1171                 return ldb_module_oom(ac->module);
1172         }
1173         msg->dn = new_prim_group_dn;
1174
1175         ret = samdb_msg_add_delval(ldb, msg, msg, "member",
1176                                    ldb_dn_get_linearized(ac->msg->dn));
1177         if (ret != LDB_SUCCESS) {
1178                 return ret;
1179         }
1180
1181         ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE, ac->req);
1182         if (ret != LDB_SUCCESS) {
1183                 return ret;
1184         }
1185         talloc_free(msg);
1186
1187         /* Add a "member" attribute for the previous primary group */
1188         msg = ldb_msg_new(ac->msg);
1189         if (msg == NULL) {
1190                 return ldb_module_oom(ac->module);
1191         }
1192         msg->dn = prev_prim_group_dn;
1193
1194         ret = samdb_msg_add_addval(ldb, msg, msg, "member",
1195                                    ldb_dn_get_linearized(ac->msg->dn));
1196         if (ret != LDB_SUCCESS) {
1197                 return ret;
1198         }
1199
1200         ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE, ac->req);
1201         if (ret != LDB_SUCCESS) {
1202                 return ret;
1203         }
1204         talloc_free(msg);
1205
1206         return LDB_SUCCESS;
1207 }
1208
1209 static int samldb_prim_group_trigger(struct samldb_ctx *ac)
1210 {
1211         int ret;
1212
1213         if (ac->req->operation == LDB_ADD) {
1214                 ret = samldb_prim_group_set(ac);
1215         } else {
1216                 ret = samldb_prim_group_change(ac);
1217         }
1218
1219         return ret;
1220 }
1221
1222
1223 /**
1224  * This function is called on LDB modify operations. It performs some additions/
1225  * replaces on the current LDB message when "userAccountControl" changes.
1226  */
1227 static int samldb_user_account_control_change(struct samldb_ctx *ac)
1228 {
1229         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1230         uint32_t user_account_control, old_user_account_control, account_type;
1231         struct ldb_message_element *el;
1232         struct ldb_message *tmp_msg;
1233         int ret;
1234         struct ldb_result *res;
1235         const char *attrs[] = { "userAccountControl", NULL };
1236
1237         el = dsdb_get_single_valued_attr(ac->msg, "userAccountControl",
1238                                          ac->req->operation);
1239         if (el == NULL) {
1240                 /* we are not affected */
1241                 return LDB_SUCCESS;
1242         }
1243
1244         /* Create a temporary message for fetching the "userAccountControl" */
1245         tmp_msg = ldb_msg_new(ac->msg);
1246         if (tmp_msg == NULL) {
1247                 return ldb_module_oom(ac->module);
1248         }
1249         ret = ldb_msg_add(tmp_msg, el, 0);
1250         if (ret != LDB_SUCCESS) {
1251                 return ret;
1252         }
1253         user_account_control = ldb_msg_find_attr_as_uint(tmp_msg,
1254                                                          "userAccountControl",
1255                                                          0);
1256         talloc_free(tmp_msg);
1257
1258         /* Temporary duplicate accounts aren't allowed */
1259         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
1260                 return LDB_ERR_OTHER;
1261         }
1262
1263         /* Fetch the old "userAccountControl" */
1264         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
1265                                     DSDB_FLAG_NEXT_MODULE, ac->req);
1266         if (ret != LDB_SUCCESS) {
1267                 return ret;
1268         }
1269         old_user_account_control = ldb_msg_find_attr_as_uint(res->msgs[0], "userAccountControl", 0);
1270         if (old_user_account_control == 0) {
1271                 return ldb_operr(ldb);
1272         }
1273
1274         /*
1275          * The functions "ds_uf2atype" and "ds_uf2prim_group_rid" are used as
1276          * detectors for account type changes.
1277          * So if the account type does change then we need to adjust the
1278          * "sAMAccountType", the "isCriticalSystemObject" and the
1279          * "primaryGroupID" attribute.
1280          */
1281         if ((ds_uf2atype(user_account_control)
1282              == ds_uf2atype(old_user_account_control)) &&
1283             (ds_uf2prim_group_rid(user_account_control)
1284              == ds_uf2prim_group_rid(old_user_account_control))) {
1285                 return LDB_SUCCESS;
1286         }
1287
1288         account_type = ds_uf2atype(user_account_control);
1289         if (account_type == 0) {
1290                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1291                 return LDB_ERR_UNWILLING_TO_PERFORM;
1292         }
1293         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1294                                  account_type);
1295         if (ret != LDB_SUCCESS) {
1296                 return ret;
1297         }
1298         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1299         el->flags = LDB_FLAG_MOD_REPLACE;
1300
1301         if (user_account_control
1302             & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1303                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1304                                          "TRUE");
1305                 if (ret != LDB_SUCCESS) {
1306                         return ret;
1307                 }
1308                 el = ldb_msg_find_element(ac->msg,
1309                                            "isCriticalSystemObject");
1310                 el->flags = LDB_FLAG_MOD_REPLACE;
1311         }
1312
1313         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
1314                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
1315                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1316                                          "primaryGroupID", rid);
1317                 if (ret != LDB_SUCCESS) {
1318                         return ret;
1319                 }
1320                 el = ldb_msg_find_element(ac->msg,
1321                                            "primaryGroupID");
1322                 el->flags = LDB_FLAG_MOD_REPLACE;
1323         }
1324
1325         return LDB_SUCCESS;
1326 }
1327
1328 static int samldb_group_type_change(struct samldb_ctx *ac)
1329 {
1330         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1331         uint32_t group_type, old_group_type, account_type;
1332         struct ldb_message_element *el;
1333         struct ldb_message *tmp_msg;
1334         int ret;
1335         struct ldb_result *res;
1336         const char *attrs[] = { "groupType", NULL };
1337
1338         el = dsdb_get_single_valued_attr(ac->msg, "groupType",
1339                                          ac->req->operation);
1340         if (el == NULL) {
1341                 /* we are not affected */
1342                 return LDB_SUCCESS;
1343         }
1344
1345         /* Create a temporary message for fetching the "groupType" */
1346         tmp_msg = ldb_msg_new(ac->msg);
1347         if (tmp_msg == NULL) {
1348                 return ldb_module_oom(ac->module);
1349         }
1350         ret = ldb_msg_add(tmp_msg, el, 0);
1351         if (ret != LDB_SUCCESS) {
1352                 return ret;
1353         }
1354         group_type = ldb_msg_find_attr_as_uint(tmp_msg, "groupType", 0);
1355         talloc_free(tmp_msg);
1356
1357         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
1358                                     DSDB_FLAG_NEXT_MODULE, ac->req);
1359         if (ret != LDB_SUCCESS) {
1360                 return ret;
1361         }
1362         old_group_type = ldb_msg_find_attr_as_uint(res->msgs[0], "groupType", 0);
1363         if (old_group_type == 0) {
1364                 return ldb_operr(ldb);
1365         }
1366
1367         /* Group type switching isn't so easy as it seems: We can only
1368          * change in this directions: global <-> universal <-> local
1369          * On each step also the group type itself
1370          * (security/distribution) is variable. */
1371
1372         if (ldb_request_get_control(ac->req, LDB_CONTROL_PROVISION_OID) == NULL) {
1373                 switch (group_type) {
1374                 case GTYPE_SECURITY_GLOBAL_GROUP:
1375                 case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
1376                         /* change to "universal" allowed */
1377                         if ((old_group_type == GTYPE_SECURITY_DOMAIN_LOCAL_GROUP) ||
1378                         (old_group_type == GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP)) {
1379                                 ldb_set_errstring(ldb,
1380                                         "samldb: Change from security/distribution local group forbidden!");
1381                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1382                         }
1383                 break;
1384
1385                 case GTYPE_SECURITY_UNIVERSAL_GROUP:
1386                 case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
1387                         /* each change allowed */
1388                 break;
1389                 case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
1390                 case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
1391                         /* change to "universal" allowed */
1392                         if ((old_group_type == GTYPE_SECURITY_GLOBAL_GROUP) ||
1393                         (old_group_type == GTYPE_DISTRIBUTION_GLOBAL_GROUP)) {
1394                                 ldb_set_errstring(ldb,
1395                                         "samldb: Change from security/distribution global group forbidden!");
1396                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1397                         }
1398                 break;
1399
1400                 case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
1401                 default:
1402                         /* we don't allow this "groupType" values */
1403                         return LDB_ERR_UNWILLING_TO_PERFORM;
1404                 break;
1405                 }
1406         }
1407
1408         account_type =  ds_gtype2atype(group_type);
1409         if (account_type == 0) {
1410                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1411                 return LDB_ERR_UNWILLING_TO_PERFORM;
1412         }
1413         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1414                                  account_type);
1415         if (ret != LDB_SUCCESS) {
1416                 return ret;
1417         }
1418         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1419         el->flags = LDB_FLAG_MOD_REPLACE;
1420
1421         return LDB_SUCCESS;
1422 }
1423
1424 static int samldb_sam_accountname_check(struct samldb_ctx *ac)
1425 {
1426         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1427         const char *no_attrs[] = { NULL };
1428         struct ldb_result *res;
1429         const char *sam_accountname, *enc_str;
1430         struct ldb_message_element *el;
1431         struct ldb_message *tmp_msg;
1432         int ret;
1433
1434         el = dsdb_get_single_valued_attr(ac->msg, "sAMAccountName",
1435                                          ac->req->operation);
1436         if (el == NULL) {
1437                 /* we are not affected */
1438                 return LDB_SUCCESS;
1439         }
1440
1441         /* Create a temporary message for fetching the "sAMAccountName" */
1442         tmp_msg = ldb_msg_new(ac->msg);
1443         if (tmp_msg == NULL) {
1444                 return ldb_module_oom(ac->module);
1445         }
1446         ret = ldb_msg_add(tmp_msg, el, 0);
1447         if (ret != LDB_SUCCESS) {
1448                 return ret;
1449         }
1450         sam_accountname = talloc_steal(ac,
1451                                        ldb_msg_find_attr_as_string(tmp_msg, "sAMAccountName", NULL));
1452         talloc_free(tmp_msg);
1453
1454         if (sam_accountname == NULL) {
1455                 /* The "sAMAccountName" cannot be nothing */
1456                 ldb_set_errstring(ldb,
1457                                   "samldb: Empty account names aren't allowed!");
1458                 return LDB_ERR_UNWILLING_TO_PERFORM;
1459         }
1460
1461         enc_str = ldb_binary_encode_string(ac, sam_accountname);
1462         if (enc_str == NULL) {
1463                 return ldb_module_oom(ac->module);
1464         }
1465
1466         /* Make sure that a "sAMAccountName" is only used once */
1467
1468         ret = dsdb_module_search(ac->module, ac, &res, NULL, LDB_SCOPE_SUBTREE, no_attrs,
1469                                  DSDB_FLAG_NEXT_MODULE, ac->req,
1470                                  "(sAMAccountName=%s)", enc_str);
1471         if (ret != LDB_SUCCESS) {
1472                 return ret;
1473         }
1474         if (res->count > 1) {
1475                 return ldb_operr(ldb);
1476         } else if (res->count == 1) {
1477                 if (ldb_dn_compare(res->msgs[0]->dn, ac->msg->dn) != 0) {
1478                         ldb_asprintf_errstring(ldb,
1479                                                "samldb: Account name (sAMAccountName) '%s' already in use!",
1480                                                sam_accountname);
1481                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
1482                 }
1483         }
1484         talloc_free(res);
1485
1486         return LDB_SUCCESS;
1487 }
1488
1489 static int samldb_member_check(struct samldb_ctx *ac)
1490 {
1491         static const char * const attrs[] = { "objectSid", "member", NULL };
1492         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1493         struct ldb_message_element *el;
1494         struct ldb_dn *member_dn;
1495         struct dom_sid *sid;
1496         struct ldb_result *res;
1497         struct dom_sid *group_sid;
1498         unsigned int i, j;
1499         int cnt;
1500         int ret;
1501
1502         /* Fetch information from the existing object */
1503
1504         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1505                                  DSDB_FLAG_NEXT_MODULE, ac->req, NULL);
1506         if (ret != LDB_SUCCESS) {
1507                 return ret;
1508         }
1509         if (res->count != 1) {
1510                 return ldb_operr(ldb);
1511         }
1512
1513         group_sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
1514         if (group_sid == NULL) {
1515                 return ldb_operr(ldb);
1516         }
1517
1518         /* We've to walk over all modification entries and consider the "member"
1519          * ones. */
1520         for (i = 0; i < ac->msg->num_elements; i++) {
1521                 if (ldb_attr_cmp(ac->msg->elements[i].name, "member") != 0) {
1522                         continue;
1523                 }
1524
1525                 el = &ac->msg->elements[i];
1526                 for (j = 0; j < el->num_values; j++) {
1527                         struct ldb_message_element *mo;
1528                         struct ldb_result *group_res;
1529                         const char *group_attrs[] = { "primaryGroupID" , NULL };
1530                         uint32_t prim_group_rid;
1531
1532                         member_dn = ldb_dn_from_ldb_val(ac, ldb,
1533                                                         &el->values[j]);
1534                         if (!ldb_dn_validate(member_dn)) {
1535                                 return ldb_operr(ldb);
1536                         }
1537
1538                         /* The "member" attribute can be modified with the
1539                          * following restrictions (beside a valid DN):
1540                          *
1541                          * - "add" operations can only be performed when the
1542                          *   member still doesn't exist - if not then return
1543                          *   ERR_ENTRY_ALREADY_EXISTS (not
1544                          *   ERR_ATTRIBUTE_OR_VALUE_EXISTS!)
1545                          * - "delete" operations can only be performed when the
1546                          *   member does exist - if not then return
1547                          *   ERR_UNWILLING_TO_PERFORM (not
1548                          *   ERR_NO_SUCH_ATTRIBUTE!)
1549                          * - primary group check
1550                          */
1551                         mo = samdb_find_attribute(ldb, res->msgs[0], "member",
1552                                                   ldb_dn_get_linearized(member_dn));
1553                         if (mo == NULL) {
1554                                 cnt = 0;
1555                         } else {
1556                                 cnt = 1;
1557                         }
1558
1559                         if ((cnt > 0) && (LDB_FLAG_MOD_TYPE(el->flags)
1560                             == LDB_FLAG_MOD_ADD)) {
1561                                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1562                         }
1563                         if ((cnt == 0) && LDB_FLAG_MOD_TYPE(el->flags)
1564                             == LDB_FLAG_MOD_DELETE) {
1565                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1566                         }
1567
1568                         /* Denies to add "member"s to groups which are primary
1569                          * ones for them - in this case return
1570                          * ERR_ENTRY_ALREADY_EXISTS. */
1571
1572                         ret = dsdb_module_search_dn(ac->module, ac, &group_res,
1573                                                     member_dn, group_attrs,
1574                                                     DSDB_FLAG_NEXT_MODULE, ac->req);
1575                         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1576                                 /* member DN doesn't exist yet */
1577                                 continue;
1578                         }
1579                         if (ret != LDB_SUCCESS) {
1580                                 return ret;
1581                         }
1582                         prim_group_rid = ldb_msg_find_attr_as_uint(group_res->msgs[0], "primaryGroupID", (uint32_t)-1);
1583                         if (prim_group_rid == (uint32_t) -1) {
1584                                 /* the member hasn't to be a user account ->
1585                                  * therefore no check needed in this case. */
1586                                 continue;
1587                         }
1588
1589                         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
1590                                               prim_group_rid);
1591                         if (sid == NULL) {
1592                                 return ldb_operr(ldb);
1593                         }
1594
1595                         if (dom_sid_equal(group_sid, sid)) {
1596                                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1597                         }
1598                 }
1599         }
1600
1601         talloc_free(res);
1602
1603         return LDB_SUCCESS;
1604 }
1605
1606 /* SAM objects have special rules regarding the "description" attribute on
1607  * modify operations. */
1608 static int samldb_description_check(struct samldb_ctx *ac, bool *modified)
1609 {
1610         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1611         const char * const attrs[] = { "objectClass", "description", NULL };
1612         struct ldb_result *res;
1613         unsigned int i;
1614         int ret;
1615
1616         /* Fetch information from the existing object */
1617         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1618                                  DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED, ac->req,
1619                                  "(|(objectclass=user)(objectclass=group)(objectclass=samDomain)(objectclass=samServer))");
1620         if (ret != LDB_SUCCESS) {
1621                 /* don't treat it specially ... let normal error codes
1622                    happen from other places */
1623                 ldb_reset_err_string(ldb);
1624                 return LDB_SUCCESS;
1625         }
1626         if (res->count == 0) {
1627                 /* we didn't match the filter */
1628                 talloc_free(res);
1629                 return LDB_SUCCESS;
1630         }
1631
1632         /* We've to walk over all modification entries and consider the
1633          * "description" ones. */
1634         for (i = 0; i < ac->msg->num_elements; i++) {
1635                 if (ldb_attr_cmp(ac->msg->elements[i].name, "description") == 0) {
1636                         ac->msg->elements[i].flags |= LDB_FLAG_INTERNAL_FORCE_SINGLE_VALUE_CHECK;
1637                         *modified = true;
1638                 }
1639         }
1640
1641         talloc_free(res);
1642
1643         return LDB_SUCCESS;
1644 }
1645
1646 /* This trigger adapts the "servicePrincipalName" attributes if the
1647  * "dNSHostName" and/or "sAMAccountName" attribute change(s) */
1648 static int samldb_service_principal_names_change(struct samldb_ctx *ac)
1649 {
1650         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1651         struct ldb_message_element *el = NULL, *el2 = NULL;
1652         struct ldb_message *msg;
1653         const char *attrs[] = { "servicePrincipalName", NULL };
1654         struct ldb_result *res;
1655         const char *dns_hostname = NULL, *old_dns_hostname = NULL,
1656                    *sam_accountname = NULL, *old_sam_accountname = NULL;
1657         unsigned int i;
1658         int ret;
1659
1660         el = dsdb_get_single_valued_attr(ac->msg, "dNSHostName",
1661                                          ac->req->operation);
1662         el2 = dsdb_get_single_valued_attr(ac->msg, "sAMAccountName",
1663                                           ac->req->operation);
1664         if ((el == NULL) && (el2 == NULL)) {
1665                 /* we are not affected */
1666                 return LDB_SUCCESS;
1667         }
1668
1669         /* Create a temporary message for fetching the "dNSHostName" */
1670         if (el != NULL) {
1671                 const char *dns_attrs[] = { "dNSHostName", NULL };
1672                 msg = ldb_msg_new(ac->msg);
1673                 if (msg == NULL) {
1674                         return ldb_module_oom(ac->module);
1675                 }
1676                 ret = ldb_msg_add(msg, el, 0);
1677                 if (ret != LDB_SUCCESS) {
1678                         return ret;
1679                 }
1680                 dns_hostname = talloc_steal(ac,
1681                                             ldb_msg_find_attr_as_string(msg, "dNSHostName", NULL));
1682                 talloc_free(msg);
1683
1684                 ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn,
1685                                             dns_attrs, DSDB_FLAG_NEXT_MODULE, ac->req);
1686                 if (ret == LDB_SUCCESS) {
1687                         old_dns_hostname = ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
1688                 }
1689         }
1690
1691         /* Create a temporary message for fetching the "sAMAccountName" */
1692         if (el2 != NULL) {
1693                 char *tempstr, *tempstr2;
1694                 const char *acct_attrs[] = { "sAMAccountName", NULL };
1695
1696                 msg = ldb_msg_new(ac->msg);
1697                 if (msg == NULL) {
1698                         return ldb_module_oom(ac->module);
1699                 }
1700                 ret = ldb_msg_add(msg, el2, 0);
1701                 if (ret != LDB_SUCCESS) {
1702                         return ret;
1703                 }
1704                 tempstr = talloc_strdup(ac,
1705                                         ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL));
1706                 talloc_free(msg);
1707
1708                 ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, acct_attrs,
1709                                             DSDB_FLAG_NEXT_MODULE, ac->req);
1710                 if (ret == LDB_SUCCESS) {
1711                         tempstr2 = talloc_strdup(ac,
1712                                                  ldb_msg_find_attr_as_string(res->msgs[0],
1713                                                                              "sAMAccountName", NULL));
1714                 }
1715
1716
1717                 /* The "sAMAccountName" needs some additional trimming: we need
1718                  * to remove the trailing "$"s if they exist. */
1719                 if ((tempstr != NULL) && (tempstr[0] != '\0') &&
1720                     (tempstr[strlen(tempstr) - 1] == '$')) {
1721                         tempstr[strlen(tempstr) - 1] = '\0';
1722                 }
1723                 if ((tempstr2 != NULL) && (tempstr2[0] != '\0') &&
1724                     (tempstr2[strlen(tempstr2) - 1] == '$')) {
1725                         tempstr2[strlen(tempstr2) - 1] = '\0';
1726                 }
1727                 sam_accountname = tempstr;
1728                 old_sam_accountname = tempstr2;
1729         }
1730
1731         if (old_dns_hostname == NULL) {
1732                 /* we cannot change when the old name is unknown */
1733                 dns_hostname = NULL;
1734         }
1735         if ((old_dns_hostname != NULL) && (dns_hostname != NULL) &&
1736             (strcasecmp(old_dns_hostname, dns_hostname) == 0)) {
1737                 /* The "dNSHostName" didn't change */
1738                 dns_hostname = NULL;
1739         }
1740
1741         if (old_sam_accountname == NULL) {
1742                 /* we cannot change when the old name is unknown */
1743                 sam_accountname = NULL;
1744         }
1745         if ((old_sam_accountname != NULL) && (sam_accountname != NULL) &&
1746             (strcasecmp(old_sam_accountname, sam_accountname) == 0)) {
1747                 /* The "sAMAccountName" didn't change */
1748                 sam_accountname = NULL;
1749         }
1750
1751         if ((dns_hostname == NULL) && (sam_accountname == NULL)) {
1752                 /* Well, there are information missing (old name(s)) or the
1753                  * names didn't change. We've nothing to do and can exit here */
1754                 return LDB_SUCCESS;
1755         }
1756
1757         /* Potential "servicePrincipalName" changes in the same request have to
1758          * be handled before the update (Windows behaviour). */
1759         el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
1760         if (el != NULL) {
1761                 msg = ldb_msg_new(ac->msg);
1762                 if (msg == NULL) {
1763                         return ldb_module_oom(ac->module);
1764                 }
1765                 msg->dn = ac->msg->dn;
1766
1767                 do {
1768                         ret = ldb_msg_add(msg, el, el->flags);
1769                         if (ret != LDB_SUCCESS) {
1770                                 return ret;
1771                         }
1772
1773                         ldb_msg_remove_element(ac->msg, el);
1774
1775                         el = ldb_msg_find_element(ac->msg,
1776                                                   "servicePrincipalName");
1777                 } while (el != NULL);
1778
1779                 ret = dsdb_module_modify(ac->module, msg,
1780                                          DSDB_FLAG_NEXT_MODULE, ac->req);
1781                 if (ret != LDB_SUCCESS) {
1782                         return ret;
1783                 }
1784                 talloc_free(msg);
1785         }
1786
1787         /* Fetch the "servicePrincipalName"s if any */
1788         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1789                                  DSDB_FLAG_NEXT_MODULE, ac->req, NULL);
1790         if (ret != LDB_SUCCESS) {
1791                 return ret;
1792         }
1793         if ((res->count != 1) || (res->msgs[0]->num_elements > 1)) {
1794                 return ldb_operr(ldb);
1795         }
1796
1797         if (res->msgs[0]->num_elements == 1) {
1798                 /* Yes, we do have "servicePrincipalName"s. First we update them
1799                  * locally, that means we do always substitute the current
1800                  * "dNSHostName" with the new one and/or "sAMAccountName"
1801                  * without "$" with the new one and then we append this to the
1802                  * modification request (Windows behaviour). */
1803
1804                 for (i = 0; i < res->msgs[0]->elements[0].num_values; i++) {
1805                         char *old_str, *new_str, *pos;
1806                         const char *tok;
1807
1808                         old_str = (char *)
1809                                 res->msgs[0]->elements[0].values[i].data;
1810
1811                         new_str = talloc_strdup(ac->msg,
1812                                                 strtok_r(old_str, "/", &pos));
1813                         if (new_str == NULL) {
1814                                 return ldb_module_oom(ac->module);
1815                         }
1816
1817                         while ((tok = strtok_r(NULL, "/", &pos)) != NULL) {
1818                                 if ((dns_hostname != NULL) &&
1819                                     (strcasecmp(tok, old_dns_hostname) == 0)) {
1820                                         tok = dns_hostname;
1821                                 }
1822                                 if ((sam_accountname != NULL) &&
1823                                     (strcasecmp(tok, old_sam_accountname) == 0)) {
1824                                         tok = sam_accountname;
1825                                 }
1826
1827                                 new_str = talloc_asprintf(ac->msg, "%s/%s",
1828                                                           new_str, tok);
1829                                 if (new_str == NULL) {
1830                                         return ldb_module_oom(ac->module);
1831                                 }
1832                         }
1833
1834                         ret = ldb_msg_add_string(ac->msg,
1835                                                  "servicePrincipalName",
1836                                                  new_str);
1837                         if (ret != LDB_SUCCESS) {
1838                                 return ret;
1839                         }
1840                 }
1841
1842                 el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
1843                 el->flags = LDB_FLAG_MOD_REPLACE;
1844         }
1845
1846         talloc_free(res);
1847
1848         return LDB_SUCCESS;
1849 }
1850
1851
1852 /* add */
1853 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
1854 {
1855         struct ldb_context *ldb;
1856         struct samldb_ctx *ac;
1857         int ret;
1858
1859         ldb = ldb_module_get_ctx(module);
1860         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
1861
1862         /* do not manipulate our control entries */
1863         if (ldb_dn_is_special(req->op.add.message->dn)) {
1864                 return ldb_next_request(module, req);
1865         }
1866
1867         ac = samldb_ctx_init(module, req);
1868         if (ac == NULL) {
1869                 return ldb_operr(ldb);
1870         }
1871
1872         /* build the new msg */
1873         ac->msg = ldb_msg_copy_shallow(ac, req->op.add.message);
1874         if (ac->msg == NULL) {
1875                 talloc_free(ac);
1876                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1877                           "samldb_add: ldb_msg_copy_shallow failed!\n");
1878                 return ldb_operr(ldb);
1879         }
1880
1881         if (samdb_find_attribute(ldb, ac->msg,
1882                                  "objectclass", "user") != NULL) {
1883                 ac->type = "user";
1884
1885                 ret = samldb_prim_group_trigger(ac);
1886                 if (ret != LDB_SUCCESS) {
1887                         return ret;
1888                 }
1889
1890                 ret = samldb_objectclass_trigger(ac);
1891                 if (ret != LDB_SUCCESS) {
1892                         return ret;
1893                 }
1894
1895                 return samldb_fill_object(ac);
1896         }
1897
1898         if (samdb_find_attribute(ldb, ac->msg,
1899                                  "objectclass", "group") != NULL) {
1900                 ac->type = "group";
1901
1902                 ret = samldb_objectclass_trigger(ac);
1903                 if (ret != LDB_SUCCESS) {
1904                         return ret;
1905                 }
1906
1907                 return samldb_fill_object(ac);
1908         }
1909
1910         /* perhaps a foreignSecurityPrincipal? */
1911         if (samdb_find_attribute(ldb, ac->msg,
1912                                  "objectclass",
1913                                  "foreignSecurityPrincipal") != NULL) {
1914                 return samldb_fill_foreignSecurityPrincipal_object(ac);
1915         }
1916
1917         if (samdb_find_attribute(ldb, ac->msg,
1918                                  "objectclass", "classSchema") != NULL) {
1919                 ret = samldb_schema_info_update(ac);
1920                 if (ret != LDB_SUCCESS) {
1921                         talloc_free(ac);
1922                         return ret;
1923                 }
1924
1925                 ac->type = "classSchema";
1926                 return samldb_fill_object(ac);
1927         }
1928
1929         if (samdb_find_attribute(ldb, ac->msg,
1930                                  "objectclass", "attributeSchema") != NULL) {
1931                 ret = samldb_schema_info_update(ac);
1932                 if (ret != LDB_SUCCESS) {
1933                         talloc_free(ac);
1934                         return ret;
1935                 }
1936
1937                 ac->type = "attributeSchema";
1938                 return samldb_fill_object(ac);
1939         }
1940
1941         talloc_free(ac);
1942
1943         /* nothing matched, go on */
1944         return ldb_next_request(module, req);
1945 }
1946
1947 /* modify */
1948 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
1949 {
1950         struct ldb_context *ldb;
1951         struct samldb_ctx *ac;
1952         struct ldb_message_element *el, *el2;
1953         bool modified = false;
1954         int ret;
1955
1956         if (ldb_dn_is_special(req->op.mod.message->dn)) {
1957                 /* do not manipulate our control entries */
1958                 return ldb_next_request(module, req);
1959         }
1960
1961         ldb = ldb_module_get_ctx(module);
1962
1963         /* make sure that "objectSid" is not specified */
1964         el = ldb_msg_find_element(req->op.mod.message, "objectSid");
1965         if (el != NULL) {
1966                 ldb_set_errstring(ldb,
1967                                   "samldb: objectSid must not be specified!");
1968                 return LDB_ERR_UNWILLING_TO_PERFORM;
1969         }
1970         /* make sure that "sAMAccountType" is not specified */
1971         el = ldb_msg_find_element(req->op.mod.message, "sAMAccountType");
1972         if (el != NULL) {
1973                 ldb_set_errstring(ldb,
1974                                   "samldb: sAMAccountType must not be specified!");
1975                 return LDB_ERR_UNWILLING_TO_PERFORM;
1976         }
1977         /* make sure that "isCriticalSystemObject" is not specified */
1978         el = ldb_msg_find_element(req->op.mod.message, "isCriticalSystemObject");
1979         if (el != NULL) {
1980                 if (ldb_request_get_control(req, LDB_CONTROL_RELAX_OID) == NULL) {
1981                         ldb_set_errstring(ldb,
1982                                           "samldb: isCriticalSystemObject must not be specified!");
1983                         return LDB_ERR_UNWILLING_TO_PERFORM;
1984                 }
1985         }
1986
1987         /* msDS-IntId is not allowed to be modified
1988          * except when modification comes from replication */
1989         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
1990                 if (!ldb_request_get_control(req,
1991                                              DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
1992                         return LDB_ERR_CONSTRAINT_VIOLATION;
1993                 }
1994         }
1995
1996         ac = samldb_ctx_init(module, req);
1997         if (ac == NULL) {
1998                 return ldb_operr(ldb);
1999         }
2000
2001         /* build the new msg */
2002         ac->msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
2003         if (ac->msg == NULL) {
2004                 talloc_free(ac);
2005                 ldb_debug(ldb, LDB_DEBUG_FATAL,
2006                           "samldb_modify: ldb_msg_copy_shallow failed!\n");
2007                 return ldb_operr(ldb);
2008         }
2009
2010         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
2011         if (el != NULL) {
2012                 ret = samldb_prim_group_change(ac);
2013                 if (ret != LDB_SUCCESS) {
2014                         return ret;
2015                 }
2016         }
2017
2018         el = ldb_msg_find_element(ac->msg, "userAccountControl");
2019         if (el != NULL) {
2020                 modified = true;
2021                 ret = samldb_user_account_control_change(ac);
2022                 if (ret != LDB_SUCCESS) {
2023                         return ret;
2024                 }
2025         }
2026
2027         el = ldb_msg_find_element(ac->msg, "groupType");
2028         if (el != NULL) {
2029                 modified = true;
2030                 ret = samldb_group_type_change(ac);
2031                 if (ret != LDB_SUCCESS) {
2032                         return ret;
2033                 }
2034         }
2035
2036         el = ldb_msg_find_element(ac->msg, "sAMAccountName");
2037         if (el != NULL) {
2038                 ret = samldb_sam_accountname_check(ac);
2039                 if (ret != LDB_SUCCESS) {
2040                         return ret;
2041                 }
2042         }
2043
2044         el = ldb_msg_find_element(ac->msg, "member");
2045         if (el != NULL) {
2046                 ret = samldb_member_check(ac);
2047                 if (ret != LDB_SUCCESS) {
2048                         return ret;
2049                 }
2050         }
2051
2052         el = ldb_msg_find_element(ac->msg, "description");
2053         if (el != NULL) {
2054                 ret = samldb_description_check(ac, &modified);
2055                 if (ret != LDB_SUCCESS) {
2056                         return ret;
2057                 }
2058         }
2059
2060         el = ldb_msg_find_element(ac->msg, "dNSHostName");
2061         el2 = ldb_msg_find_element(ac->msg, "sAMAccountName");
2062         if ((el != NULL) || (el2 != NULL)) {
2063                 modified = true;
2064                 ret = samldb_service_principal_names_change(ac);
2065                 if (ret != LDB_SUCCESS) {
2066                         return ret;
2067                 }
2068         }
2069
2070         if (modified) {
2071                 struct ldb_request *child_req;
2072
2073                 /* Now perform the real modifications as a child request */
2074                 ret = ldb_build_mod_req(&child_req, ldb, ac,
2075                                         ac->msg,
2076                                         req->controls,
2077                                         req, dsdb_next_callback,
2078                                         req);
2079                 LDB_REQ_SET_LOCATION(child_req);
2080                 if (ret != LDB_SUCCESS) {
2081                         return ret;
2082                 }
2083
2084                 return ldb_next_request(module, child_req);
2085         }
2086
2087         talloc_free(ac);
2088
2089         /* no change which interests us, go on */
2090         return ldb_next_request(module, req);
2091 }
2092
2093 /* delete */
2094
2095 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
2096 {
2097         struct ldb_context *ldb;
2098         struct dom_sid *sid;
2099         uint32_t rid;
2100         NTSTATUS status;
2101         int ret;
2102         struct ldb_result *res;
2103         const char *attrs[] = { "objectSid", NULL };
2104         const char *noattrs[] = { NULL };
2105
2106         ldb = ldb_module_get_ctx(ac->module);
2107
2108         /* Finds out the SID/RID of the SAM object */
2109         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->req->op.del.dn, attrs, DSDB_FLAG_NEXT_MODULE, ac->req);
2110         if (ret != LDB_SUCCESS) {
2111                 return ret;
2112         }
2113
2114         sid = samdb_result_dom_sid(ac, res->msgs[0], "objectSid");
2115         if (sid == NULL) {
2116                 /* No SID - it might not be a SAM object - therefore ok */
2117                 return LDB_SUCCESS;
2118         }
2119         status = dom_sid_split_rid(ac, sid, NULL, &rid);
2120         if (!NT_STATUS_IS_OK(status)) {
2121                 return ldb_operr(ldb);
2122         }
2123         if (rid == 0) {
2124                 /* Special object (security principal?) */
2125                 return LDB_SUCCESS;
2126         }
2127
2128         /* Deny delete requests from groups which are primary ones */
2129         ret = dsdb_module_search(ac->module, ac, &res, NULL, LDB_SCOPE_SUBTREE, noattrs,
2130                                  DSDB_FLAG_NEXT_MODULE,
2131                                  ac->req,
2132                                  "(&(primaryGroupID=%u)(objectClass=user))", rid);
2133         if (ret != LDB_SUCCESS) {
2134                 return ret;
2135         }
2136         if (res->count > 0) {
2137                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
2138         }
2139
2140         return LDB_SUCCESS;
2141 }
2142
2143 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
2144 {
2145         struct samldb_ctx *ac;
2146         int ret;
2147
2148         if (ldb_dn_is_special(req->op.del.dn)) {
2149                 /* do not manipulate our control entries */
2150                 return ldb_next_request(module, req);
2151         }
2152
2153         ac = samldb_ctx_init(module, req);
2154         if (ac == NULL) {
2155                 return ldb_operr(ldb_module_get_ctx(module));
2156         }
2157
2158         ret = samldb_prim_group_users_check(ac);
2159         if (ret != LDB_SUCCESS) {
2160                 return ret;
2161         }
2162
2163         talloc_free(ac);
2164
2165         return ldb_next_request(module, req);
2166 }
2167
2168 /* extended */
2169
2170 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
2171 {
2172         struct ldb_context *ldb = ldb_module_get_ctx(module);
2173         struct dsdb_fsmo_extended_op *exop;
2174         int ret;
2175
2176         exop = talloc_get_type(req->op.extended.data,
2177                                struct dsdb_fsmo_extended_op);
2178         if (!exop) {
2179                 ldb_set_errstring(ldb,
2180                                   "samldb_extended_allocate_rid_pool: invalid extended data");
2181                 return LDB_ERR_PROTOCOL_ERROR;
2182         }
2183
2184         ret = ridalloc_allocate_rid_pool_fsmo(module, exop, req);
2185         if (ret != LDB_SUCCESS) {
2186                 return ret;
2187         }
2188
2189         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
2190 }
2191
2192 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
2193 {
2194         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
2195                 return samldb_extended_allocate_rid_pool(module, req);
2196         }
2197
2198         return ldb_next_request(module, req);
2199 }
2200
2201
2202 static const struct ldb_module_ops ldb_samldb_module_ops = {
2203         .name          = "samldb",
2204         .add           = samldb_add,
2205         .modify        = samldb_modify,
2206         .del           = samldb_delete,
2207         .extended      = samldb_extended
2208 };
2209
2210
2211 int ldb_samldb_module_init(const char *version)
2212 {
2213         LDB_MODULE_CHECK_VERSION(version);
2214         return ldb_register_module(&ldb_samldb_module_ops);
2215 }