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