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