s4: use enums instead of strings it's cheaper
[mat/samba.git] / source4 / dsdb / samdb / ldb_modules / samldb.c
1 /*
2    SAM ldb module
3
4    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
5    Copyright (C) Simo Sorce  2004-2008
6    Copyright (C) Matthias Dieter Wallnöfer 2009-2011
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /*
23  *  Name: ldb
24  *
25  *  Component: ldb samldb module
26  *
27  *  Description: various internal DSDB triggers - most for SAM specific objects
28  *
29  *  Author: Simo Sorce
30  */
31
32 #include "includes.h"
33 #include "libcli/ldap/ldap_ndr.h"
34 #include "ldb_module.h"
35 #include "dsdb/samdb/samdb.h"
36 #include "dsdb/samdb/ldb_modules/util.h"
37 #include "dsdb/samdb/ldb_modules/ridalloc.h"
38 #include "libcli/security/security.h"
39 #include "librpc/gen_ndr/ndr_security.h"
40 #include "ldb_wrap.h"
41 #include "param/param.h"
42 #include "libds/common/flag_mapping.h"
43
44 struct samldb_ctx;
45 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
623                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
624                                         "rdnAttId", "cn");
625                         if (ret != LDB_SUCCESS) return ret;
626
627                         /* do not allow to mark an attributeSchema as RODC filtered if it
628                         * is system-critical */
629                         if (check_rodc_critical_attribute(ac->msg)) {
630                                 ldb_asprintf_errstring(ldb, "Refusing schema add of %s - cannot combine critical class with RODC filtering",
631                                                 ldb_dn_get_linearized(ac->msg->dn));
632                                 return LDB_ERR_UNWILLING_TO_PERFORM;
633                         }
634
635                         rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
636                         if (rdn_value == NULL) {
637                                 return ldb_operr(ldb);
638                         }
639                         if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
640                                 /* the RDN has prefix "CN" */
641                                 ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
642                                                 samdb_cn_to_lDAPDisplayName(ac->msg,
643                                                         (const char *) rdn_value->data));
644                                 if (ret != LDB_SUCCESS) {
645                                         ldb_oom(ldb);
646                                         return ret;
647                                 }
648                         }
649
650                         if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
651                                 struct GUID guid;
652                                 /* a new GUID */
653                                 guid = GUID_random();
654                                 ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
655                                 if (ret != LDB_SUCCESS) {
656                                         ldb_oom(ldb);
657                                         return ret;
658                                 }
659                         }
660
661                         def_obj_cat_val = ldb_msg_find_ldb_val(ac->msg,
662                                         "defaultObjectCategory");
663                         if (def_obj_cat_val != NULL) {
664                                 /* "defaultObjectCategory" has been set by the caller.
665                                 * Do some checks for consistency.
666                                 * NOTE: The real constraint check (that
667                                 * 'defaultObjectCategory' is the DN of the new
668                                 * objectclass or any parent of it) is still incomplete.
669                                 * For now we say that 'defaultObjectCategory' is valid
670                                 * if it exists and it is of objectclass "classSchema".
671                                 */
672                                 ac->dn = ldb_dn_from_ldb_val(ac, ldb, def_obj_cat_val);
673                                 if (ac->dn == NULL) {
674                                         ldb_set_errstring(ldb,
675                                                         "Invalid DN for 'defaultObjectCategory'!");
676                                         return LDB_ERR_CONSTRAINT_VIOLATION;
677                                 }
678                         } else {
679                                 /* "defaultObjectCategory" has not been set by the
680                                 * caller. Use the entry DN for it. */
681                                 ac->dn = ac->msg->dn;
682
683                                 ret = ldb_msg_add_string(ac->msg, "defaultObjectCategory",
684                                                 ldb_dn_alloc_linearized(ac->msg, ac->dn));
685                                 if (ret != LDB_SUCCESS) {
686                                         ldb_oom(ldb);
687                                         return ret;
688                                 }
689                         }
690
691                         ret = samldb_add_step(ac, samldb_add_entry);
692                         if (ret != LDB_SUCCESS) return ret;
693
694                         /* Now perform the checks for the 'defaultObjectCategory'. The
695                         * lookup DN was already saved in "ac->dn" */
696                         ret = samldb_add_step(ac, samldb_find_for_defaultObjectCategory);
697                         if (ret != LDB_SUCCESS) return ret;
698                         break;
699                         }
700
701                 case SAMLDB_TYPE_ATTRIBUTE: {
702                         const struct ldb_val *rdn_value;
703                         rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
704                         if (rdn_value == NULL) {
705                                 return ldb_operr(ldb);
706                         }
707                         if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
708                                 /* the RDN has prefix "CN" */
709                                 ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
710                                                 samdb_cn_to_lDAPDisplayName(ac->msg,
711                                                         (const char *) rdn_value->data));
712                                 if (ret != LDB_SUCCESS) {
713                                         ldb_oom(ldb);
714                                         return ret;
715                                 }
716                         }
717
718                         /* do not allow to mark an attributeSchema as RODC filtered if it
719                         * is system-critical */
720                         if (check_rodc_critical_attribute(ac->msg)) {
721                                 ldb_asprintf_errstring(ldb,
722                                                 "samldb: refusing schema add of %s - cannot combine critical attribute with RODC filtering",
723                                                 ldb_dn_get_linearized(ac->msg->dn));
724                                 return LDB_ERR_UNWILLING_TO_PERFORM;
725                         }
726
727                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
728                                         "isSingleValued", "FALSE");
729                         if (ret != LDB_SUCCESS) return ret;
730
731                         if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
732                                 struct GUID guid;
733                                 /* a new GUID */
734                                 guid = GUID_random();
735                                 ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
736                                 if (ret != LDB_SUCCESS) {
737                                         ldb_oom(ldb);
738                                         return ret;
739                                 }
740                         }
741
742                         /* handle msDS-IntID attribute */
743                         ret = samldb_add_handle_msDS_IntId(ac);
744                         if (ret != LDB_SUCCESS) return ret;
745
746                         ret = samldb_add_step(ac, samldb_add_entry);
747                         if (ret != LDB_SUCCESS) return ret;
748                         break;
749                         }
750
751                 default:
752                         ldb_asprintf_errstring(ldb,
753                                         "Invalid entry type!");
754                         return LDB_ERR_OPERATIONS_ERROR;
755                         break;
756         }
757
758         return samldb_first_step(ac);
759 }
760
761 static int samldb_fill_foreignSecurityPrincipal_object(struct samldb_ctx *ac)
762 {
763         struct ldb_context *ldb;
764         const struct ldb_val *rdn_value;
765         struct dom_sid *sid;
766         int ret;
767
768         ldb = ldb_module_get_ctx(ac->module);
769
770         sid = samdb_result_dom_sid(ac->msg, ac->msg, "objectSid");
771         if (sid == NULL) {
772                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
773                 if (rdn_value == NULL) {
774                         return ldb_operr(ldb);
775                 }
776                 sid = dom_sid_parse_talloc(ac->msg,
777                                            (const char *)rdn_value->data);
778                 if (sid == NULL) {
779                         ldb_set_errstring(ldb,
780                                           "samldb: No valid SID found in ForeignSecurityPrincipal CN!");
781                         return LDB_ERR_CONSTRAINT_VIOLATION;
782                 }
783                 if (! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
784                         return ldb_operr(ldb);
785                 }
786         }
787
788         /* finally proceed with adding the entry */
789         ret = samldb_add_step(ac, samldb_add_entry);
790         if (ret != LDB_SUCCESS) return ret;
791
792         return samldb_first_step(ac);
793 }
794
795 static int samldb_schema_info_update(struct samldb_ctx *ac)
796 {
797         int ret;
798         struct ldb_context *ldb;
799         struct dsdb_schema *schema;
800
801         /* replicated update should always go through */
802         if (ldb_request_get_control(ac->req,
803                                     DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
804                 return LDB_SUCCESS;
805         }
806
807         /* do not update schemaInfo during provisioning */
808         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
809                 return LDB_SUCCESS;
810         }
811
812         ldb = ldb_module_get_ctx(ac->module);
813         schema = dsdb_get_schema(ldb, NULL);
814         if (!schema) {
815                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
816                               "samldb_schema_info_update: no dsdb_schema loaded");
817                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
818                 return ldb_operr(ldb);
819         }
820
821         ret = dsdb_module_schema_info_update(ac->module, schema,
822                                              DSDB_FLAG_NEXT_MODULE|
823                                              DSDB_FLAG_AS_SYSTEM,
824                                              ac->req);
825         if (ret != LDB_SUCCESS) {
826                 ldb_asprintf_errstring(ldb,
827                                        "samldb_schema_info_update: dsdb_module_schema_info_update failed with %s",
828                                        ldb_errstring(ldb));
829                 return ret;
830         }
831
832         return LDB_SUCCESS;
833 }
834
835 static int samldb_prim_group_tester(struct samldb_ctx *ac, uint32_t rid);
836
837 /*
838  * "Objectclass" trigger (MS-SAMR 3.1.1.8.1)
839  *
840  * Has to be invoked on "add" and "modify" operations on "user", "computer" and
841  * "group" objects.
842  * ac->msg contains the "add"/"modify" message
843  * ac->type contains the object type (main objectclass)
844  */
845 static int samldb_objectclass_trigger(struct samldb_ctx *ac)
846 {
847         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
848         void *skip_allocate_sids = ldb_get_opaque(ldb,
849                                                   "skip_allocate_sids");
850         struct ldb_message_element *el, *el2;
851         struct dom_sid *sid;
852         int ret;
853
854         /* make sure that "sAMAccountType" is not specified */
855         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
856         if (el != NULL) {
857                 ldb_set_errstring(ldb,
858                                   "samldb: sAMAccountType must not be specified!");
859                 return LDB_ERR_UNWILLING_TO_PERFORM;
860         }
861
862         /* Step 1: objectSid assignment */
863
864         /* Don't allow the objectSid to be changed. But beside the RELAX
865          * control we have also to guarantee that it can always be set with
866          * SYSTEM permissions. This is needed for the "samba3sam" backend. */
867         sid = samdb_result_dom_sid(ac, ac->msg, "objectSid");
868         if ((sid != NULL) && (!dsdb_module_am_system(ac->module)) &&
869             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
870                 ldb_set_errstring(ldb,
871                                   "samldb: objectSid must not be specified!");
872                 return LDB_ERR_UNWILLING_TO_PERFORM;
873         }
874
875         /* but generate a new SID when we do have an add operations */
876         if ((sid == NULL) && (ac->req->operation == LDB_ADD) && !skip_allocate_sids) {
877                 ret = samldb_add_step(ac, samldb_allocate_sid);
878                 if (ret != LDB_SUCCESS) return ret;
879         }
880
881         switch(ac->type) {
882                 case SAMLDB_TYPE_USER: {
883                         bool uac_generated = false;
884
885                         /* Step 1.2: Default values */
886                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
887                                 "accountExpires", "9223372036854775807");
888                         if (ret != LDB_SUCCESS) return ret;
889                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
890                                 "badPasswordTime", "0");
891                         if (ret != LDB_SUCCESS) return ret;
892                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
893                                 "badPwdCount", "0");
894                         if (ret != LDB_SUCCESS) return ret;
895                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
896                                 "codePage", "0");
897                         if (ret != LDB_SUCCESS) return ret;
898                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
899                                 "countryCode", "0");
900                         if (ret != LDB_SUCCESS) return ret;
901                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
902                                 "lastLogoff", "0");
903                         if (ret != LDB_SUCCESS) return ret;
904                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
905                                 "lastLogon", "0");
906                         if (ret != LDB_SUCCESS) return ret;
907                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
908                                 "logonCount", "0");
909                         if (ret != LDB_SUCCESS) return ret;
910                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
911                                 "pwdLastSet", "0");
912                         if (ret != LDB_SUCCESS) return ret;
913
914                         /* On add operations we might need to generate a
915                         * "userAccountControl" (if it isn't specified). */
916                         el = ldb_msg_find_element(ac->msg, "userAccountControl");
917                         if ((el == NULL) && (ac->req->operation == LDB_ADD)) {
918                                 ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
919                                                         "userAccountControl",
920                                                         UF_NORMAL_ACCOUNT);
921                                 if (ret != LDB_SUCCESS) {
922                                         return ret;
923                                 }
924                                 uac_generated = true;
925                         }
926
927                         el = ldb_msg_find_element(ac->msg, "userAccountControl");
928                         if (el != NULL) {
929                                 uint32_t user_account_control, account_type;
930
931                                 /* Step 1.3: "userAccountControl" -> "sAMAccountType" mapping */
932                                 user_account_control = ldb_msg_find_attr_as_uint(ac->msg,
933                                                                                 "userAccountControl",
934                                                                                 0);
935
936                                 /* Temporary duplicate accounts aren't allowed */
937                                 if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
938                                         return LDB_ERR_OTHER;
939                                 }
940
941                                 /* Workstation and (read-only) DC objects do need objectclass "computer" */
942                                 if ((samdb_find_attribute(ldb, ac->msg,
943                                                         "objectclass", "computer") == NULL) &&
944                                 (user_account_control &
945                                 (UF_SERVER_TRUST_ACCOUNT | UF_WORKSTATION_TRUST_ACCOUNT))) {
946                                         ldb_set_errstring(ldb,
947                                                         "samldb: Requested account type does need objectclass 'computer'!");
948                                         return LDB_ERR_OBJECT_CLASS_VIOLATION;
949                                 }
950
951                                 account_type = ds_uf2atype(user_account_control);
952                                 if (account_type == 0) {
953                                         ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
954                                         return LDB_ERR_UNWILLING_TO_PERFORM;
955                                 }
956                                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
957                                                         "sAMAccountType",
958                                                         account_type);
959                                 if (ret != LDB_SUCCESS) {
960                                         return ret;
961                                 }
962                                 el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
963                                 el2->flags = LDB_FLAG_MOD_REPLACE;
964
965                                 /* "isCriticalSystemObject" might be set */
966                                 if (user_account_control &
967                                 (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
968                                         ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
969                                                                 "TRUE");
970                                         if (ret != LDB_SUCCESS) {
971                                                 return ret;
972                                         }
973                                         el2 = ldb_msg_find_element(ac->msg,
974                                                                 "isCriticalSystemObject");
975                                         el2->flags = LDB_FLAG_MOD_REPLACE;
976                                 } else if (user_account_control & UF_WORKSTATION_TRUST_ACCOUNT) {
977                                         ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
978                                                                 "FALSE");
979                                         if (ret != LDB_SUCCESS) {
980                                                 return ret;
981                                         }
982                                         el2 = ldb_msg_find_element(ac->msg,
983                                                                 "isCriticalSystemObject");
984                                         el2->flags = LDB_FLAG_MOD_REPLACE;
985                                 }
986
987                                 /* Step 1.4: "userAccountControl" -> "primaryGroupID" mapping */
988                                 if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
989                                         uint32_t rid = ds_uf2prim_group_rid(user_account_control);
990
991                                         /*
992                                         * Older AD deployments don't know about the
993                                         * RODC group
994                                         */
995                                         if (rid == DOMAIN_RID_READONLY_DCS) {
996                                                 ret = samldb_prim_group_tester(ac, rid);
997                                                 if (ret != LDB_SUCCESS) {
998                                                         return ret;
999                                                 }
1000                                         }
1001
1002                                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1003                                                                 "primaryGroupID", rid);
1004                                         if (ret != LDB_SUCCESS) {
1005                                                 return ret;
1006                                         }
1007                                         el2 = ldb_msg_find_element(ac->msg,
1008                                                                 "primaryGroupID");
1009                                         el2->flags = LDB_FLAG_MOD_REPLACE;
1010                                 }
1011
1012                                 /* Step 1.5: Add additional flags when needed */
1013                                 /* Obviously this is done when the "userAccountControl"
1014                                 * has been generated here (tested against Windows
1015                                 * Server) */
1016                                 if (uac_generated) {
1017                                         user_account_control |= UF_ACCOUNTDISABLE;
1018                                         user_account_control |= UF_PASSWD_NOTREQD;
1019
1020                                         ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
1021                                                                 "userAccountControl",
1022                                                                 user_account_control);
1023                                         if (ret != LDB_SUCCESS) {
1024                                                 return ret;
1025                                         }
1026                                 }
1027                         }
1028                         break;
1029                         }
1030                 case SAMLDB_TYPE_GROUP: {
1031                         const char *tempstr;
1032
1033                         /* Step 2.2: Default values */
1034                         tempstr = talloc_asprintf(ac->msg, "%d",
1035                                                 GTYPE_SECURITY_GLOBAL_GROUP);
1036                         if (tempstr == NULL) return ldb_operr(ldb);
1037                         ret = samdb_find_or_add_attribute(ldb, ac->msg,
1038                                 "groupType", tempstr);
1039                         if (ret != LDB_SUCCESS) return ret;
1040
1041                         /* Step 2.3: "groupType" -> "sAMAccountType" */
1042                         el = ldb_msg_find_element(ac->msg, "groupType");
1043                         if (el != NULL) {
1044                                 uint32_t group_type, account_type;
1045
1046                                 group_type = ldb_msg_find_attr_as_uint(ac->msg,
1047                                                                 "groupType", 0);
1048
1049                                 /* The creation of builtin groups requires the
1050                                 * RELAX control */
1051                                 if (group_type == GTYPE_SECURITY_BUILTIN_LOCAL_GROUP) {
1052                                         if (ldb_request_get_control(ac->req,
1053                                                                 LDB_CONTROL_RELAX_OID) == NULL) {
1054                                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1055                                         }
1056                                 }
1057
1058                                 account_type = ds_gtype2atype(group_type);
1059                                 if (account_type == 0) {
1060                                         ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1061                                         return LDB_ERR_UNWILLING_TO_PERFORM;
1062                                 }
1063                                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1064                                                         "sAMAccountType",
1065                                                         account_type);
1066                                 if (ret != LDB_SUCCESS) {
1067                                         return ret;
1068                                 }
1069                                 el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
1070                                 el2->flags = LDB_FLAG_MOD_REPLACE;
1071                         }
1072                         break;
1073                         }
1074
1075                 default:
1076                         ldb_asprintf_errstring(ldb,
1077                                         "Invalid entry type!");
1078                         return LDB_ERR_OPERATIONS_ERROR;
1079                         break;
1080         }
1081
1082         return LDB_SUCCESS;
1083 }
1084
1085 /*
1086  * "Primary group ID" trigger (MS-SAMR 3.1.1.8.2)
1087  *
1088  * Has to be invoked on "add" and "modify" operations on "user" and "computer"
1089  * objects.
1090  * ac->msg contains the "add"/"modify" message
1091  */
1092
1093 static int samldb_prim_group_tester(struct samldb_ctx *ac, uint32_t rid)
1094 {
1095         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1096         struct dom_sid *sid;
1097         struct ldb_result *res;
1098         int ret;
1099         const char *noattrs[] = { NULL };
1100
1101         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1102         if (sid == NULL) {
1103                 return ldb_operr(ldb);
1104         }
1105
1106         ret = dsdb_module_search(ac->module, ac, &res,
1107                                  ldb_get_default_basedn(ldb),
1108                                  LDB_SCOPE_SUBTREE,
1109                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1110                                  ac->req,
1111                                  "(objectSid=%s)",
1112                                  ldap_encode_ndr_dom_sid(ac, sid));
1113         if (ret != LDB_SUCCESS) {
1114                 return ret;
1115         }
1116         if (res->count != 1) {
1117                 talloc_free(res);
1118                 ldb_asprintf_errstring(ldb,
1119                                        "Failed to find primary group with RID %u!",
1120                                        rid);
1121                 return LDB_ERR_UNWILLING_TO_PERFORM;
1122         }
1123         talloc_free(res);
1124
1125         return LDB_SUCCESS;
1126 }
1127
1128 static int samldb_prim_group_set(struct samldb_ctx *ac)
1129 {
1130         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1131         uint32_t rid;
1132
1133         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1134         if (rid == (uint32_t) -1) {
1135                 /* we aren't affected of any primary group set */
1136                 return LDB_SUCCESS;
1137
1138         } else if (!ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
1139                 ldb_set_errstring(ldb,
1140                                   "The primary group isn't settable on add operations!");
1141                 return LDB_ERR_UNWILLING_TO_PERFORM;
1142         }
1143
1144         return samldb_prim_group_tester(ac, rid);
1145 }
1146
1147 static int samldb_prim_group_change(struct samldb_ctx *ac)
1148 {
1149         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1150         const char * attrs[] = { "primaryGroupID", "memberOf", NULL };
1151         struct ldb_result *res, *group_res;
1152         struct ldb_message_element *el;
1153         struct ldb_message *msg;
1154         uint32_t prev_rid, new_rid;
1155         struct dom_sid *prev_sid, *new_sid;
1156         struct ldb_dn *prev_prim_group_dn, *new_prim_group_dn;
1157         int ret;
1158         const char *noattrs[] = { NULL };
1159
1160         el = dsdb_get_single_valued_attr(ac->msg, "primaryGroupID",
1161                                          ac->req->operation);
1162         if (el == NULL) {
1163                 /* we are not affected */
1164                 return LDB_SUCCESS;
1165         }
1166
1167         /* Fetch information from the existing object */
1168
1169         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
1170                                     DSDB_FLAG_NEXT_MODULE, ac->req);
1171         if (ret != LDB_SUCCESS) {
1172                 return ret;
1173         }
1174
1175         /* Finds out the DN of the old primary group */
1176
1177         prev_rid = ldb_msg_find_attr_as_uint(res->msgs[0], "primaryGroupID",
1178                                              (uint32_t) -1);
1179         if (prev_rid == (uint32_t) -1) {
1180                 /* User objects do always have a mandatory "primaryGroupID"
1181                  * attribute. If this doesn't exist then the object is of the
1182                  * wrong type. This is the exact Windows error code */
1183                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1184         }
1185
1186         prev_sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), prev_rid);
1187         if (prev_sid == NULL) {
1188                 return ldb_operr(ldb);
1189         }
1190
1191         /* Finds out the DN of the new primary group
1192          * Notice: in order to parse the primary group ID correctly we create
1193          * a temporary message here. */
1194
1195         msg = ldb_msg_new(ac->msg);
1196         if (msg == NULL) {
1197                 return ldb_module_oom(ac->module);
1198         }
1199         ret = ldb_msg_add(msg, el, 0);
1200         if (ret != LDB_SUCCESS) {
1201                 return ret;
1202         }
1203         new_rid = ldb_msg_find_attr_as_uint(msg, "primaryGroupID", (uint32_t) -1);
1204         talloc_free(msg);
1205         if (new_rid == (uint32_t) -1) {
1206                 /* we aren't affected of any primary group change */
1207                 return LDB_SUCCESS;
1208         }
1209
1210         if (prev_rid == new_rid) {
1211                 return LDB_SUCCESS;
1212         }
1213
1214         ret = dsdb_module_search(ac->module, ac, &group_res,
1215                                  ldb_get_default_basedn(ldb),
1216                                  LDB_SCOPE_SUBTREE,
1217                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1218                                  ac->req,
1219                                  "(objectSid=%s)",
1220                                  ldap_encode_ndr_dom_sid(ac, prev_sid));
1221         if (ret != LDB_SUCCESS) {
1222                 return ret;
1223         }
1224         if (group_res->count != 1) {
1225                 return ldb_operr(ldb);
1226         }
1227         prev_prim_group_dn = group_res->msgs[0]->dn;
1228
1229         new_sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), new_rid);
1230         if (new_sid == NULL) {
1231                 return ldb_operr(ldb);
1232         }
1233
1234         ret = dsdb_module_search(ac->module, ac, &group_res,
1235                                  ldb_get_default_basedn(ldb),
1236                                  LDB_SCOPE_SUBTREE,
1237                                  noattrs, DSDB_FLAG_NEXT_MODULE,
1238                                  ac->req,
1239                                  "(objectSid=%s)",
1240                                  ldap_encode_ndr_dom_sid(ac, new_sid));
1241         if (ret != LDB_SUCCESS) {
1242                 return ret;
1243         }
1244         if (group_res->count != 1) {
1245                 /* Here we know if the specified new primary group candidate is
1246                  * valid or not. */
1247                 return LDB_ERR_UNWILLING_TO_PERFORM;
1248         }
1249         new_prim_group_dn = group_res->msgs[0]->dn;
1250
1251         /* We need to be already a normal member of the new primary
1252          * group in order to be successful. */
1253         el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1254                                   ldb_dn_get_linearized(new_prim_group_dn));
1255         if (el == NULL) {
1256                 return LDB_ERR_UNWILLING_TO_PERFORM;
1257         }
1258
1259         /* Remove the "member" attribute on the new primary group */
1260         msg = ldb_msg_new(ac->msg);
1261         if (msg == NULL) {
1262                 return ldb_module_oom(ac->module);
1263         }
1264         msg->dn = new_prim_group_dn;
1265
1266         ret = samdb_msg_add_delval(ldb, msg, msg, "member",
1267                                    ldb_dn_get_linearized(ac->msg->dn));
1268         if (ret != LDB_SUCCESS) {
1269                 return ret;
1270         }
1271
1272         ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE, ac->req);
1273         if (ret != LDB_SUCCESS) {
1274                 return ret;
1275         }
1276         talloc_free(msg);
1277
1278         /* Add a "member" attribute for the previous primary group */
1279         msg = ldb_msg_new(ac->msg);
1280         if (msg == NULL) {
1281                 return ldb_module_oom(ac->module);
1282         }
1283         msg->dn = prev_prim_group_dn;
1284
1285         ret = samdb_msg_add_addval(ldb, msg, msg, "member",
1286                                    ldb_dn_get_linearized(ac->msg->dn));
1287         if (ret != LDB_SUCCESS) {
1288                 return ret;
1289         }
1290
1291         ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE, ac->req);
1292         if (ret != LDB_SUCCESS) {
1293                 return ret;
1294         }
1295         talloc_free(msg);
1296
1297         return LDB_SUCCESS;
1298 }
1299
1300 static int samldb_prim_group_trigger(struct samldb_ctx *ac)
1301 {
1302         int ret;
1303
1304         if (ac->req->operation == LDB_ADD) {
1305                 ret = samldb_prim_group_set(ac);
1306         } else {
1307                 ret = samldb_prim_group_change(ac);
1308         }
1309
1310         return ret;
1311 }
1312
1313
1314 /**
1315  * This function is called on LDB modify operations. It performs some additions/
1316  * replaces on the current LDB message when "userAccountControl" changes.
1317  */
1318 static int samldb_user_account_control_change(struct samldb_ctx *ac)
1319 {
1320         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1321         uint32_t user_account_control, old_user_account_control, account_type;
1322         struct ldb_message_element *el;
1323         struct ldb_message *tmp_msg;
1324         int ret;
1325         struct ldb_result *res;
1326         const char *attrs[] = { "userAccountControl", "objectClass", NULL };
1327         unsigned int i;
1328         bool is_computer = false;
1329
1330         el = dsdb_get_single_valued_attr(ac->msg, "userAccountControl",
1331                                          ac->req->operation);
1332         if (el == NULL) {
1333                 /* we are not affected */
1334                 return LDB_SUCCESS;
1335         }
1336
1337         /* Create a temporary message for fetching the "userAccountControl" */
1338         tmp_msg = ldb_msg_new(ac->msg);
1339         if (tmp_msg == NULL) {
1340                 return ldb_module_oom(ac->module);
1341         }
1342         ret = ldb_msg_add(tmp_msg, el, 0);
1343         if (ret != LDB_SUCCESS) {
1344                 return ret;
1345         }
1346         user_account_control = ldb_msg_find_attr_as_uint(tmp_msg,
1347                                                          "userAccountControl",
1348                                                          0);
1349         talloc_free(tmp_msg);
1350
1351         /* Temporary duplicate accounts aren't allowed */
1352         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
1353                 return LDB_ERR_OTHER;
1354         }
1355
1356         /* Fetch the old "userAccountControl" and "objectClass" */
1357         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
1358                                     DSDB_FLAG_NEXT_MODULE, ac->req);
1359         if (ret != LDB_SUCCESS) {
1360                 return ret;
1361         }
1362         old_user_account_control = ldb_msg_find_attr_as_uint(res->msgs[0], "userAccountControl", 0);
1363         if (old_user_account_control == 0) {
1364                 return ldb_operr(ldb);
1365         }
1366         el = ldb_msg_find_element(res->msgs[0], "objectClass");
1367         if (el == NULL) {
1368                 return ldb_operr(ldb);
1369         }
1370
1371         /* When we do not have objectclass "computer" we cannot switch to a (read-only) DC */
1372         for (i = 0; i < el->num_values; i++) {
1373                 if (ldb_attr_cmp((char *)el->values[i].data, "computer") == 0) {
1374                         is_computer = true;
1375                         break;
1376                 }
1377         }
1378         if (!is_computer &&
1379             (user_account_control & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT))) {
1380                 ldb_set_errstring(ldb,
1381                                   "samldb: Requested account type does need objectclass 'computer'!");
1382                 return LDB_ERR_UNWILLING_TO_PERFORM;
1383         }
1384
1385         /*
1386          * The functions "ds_uf2atype" and "ds_uf2prim_group_rid" are used as
1387          * detectors for account type changes.
1388          * So if the account type does change then we need to adjust the
1389          * "sAMAccountType", the "isCriticalSystemObject" and the
1390          * "primaryGroupID" attribute.
1391          */
1392         if ((ds_uf2atype(user_account_control)
1393              == ds_uf2atype(old_user_account_control)) &&
1394             (ds_uf2prim_group_rid(user_account_control)
1395              == ds_uf2prim_group_rid(old_user_account_control))) {
1396                 return LDB_SUCCESS;
1397         }
1398
1399         account_type = ds_uf2atype(user_account_control);
1400         if (account_type == 0) {
1401                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1402                 return LDB_ERR_UNWILLING_TO_PERFORM;
1403         }
1404         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1405                                  account_type);
1406         if (ret != LDB_SUCCESS) {
1407                 return ret;
1408         }
1409         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1410         el->flags = LDB_FLAG_MOD_REPLACE;
1411
1412         /* "isCriticalSystemObject" might be set/changed */
1413         if (user_account_control
1414             & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1415                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1416                                          "TRUE");
1417                 if (ret != LDB_SUCCESS) {
1418                         return ret;
1419                 }
1420                 el = ldb_msg_find_element(ac->msg,
1421                                            "isCriticalSystemObject");
1422                 el->flags = LDB_FLAG_MOD_REPLACE;
1423         } else if (user_account_control & UF_WORKSTATION_TRUST_ACCOUNT) {
1424                 ret = ldb_msg_add_string(ac->msg, "isCriticalSystemObject",
1425                                          "FALSE");
1426                 if (ret != LDB_SUCCESS) {
1427                         return ret;
1428                 }
1429                 el = ldb_msg_find_element(ac->msg,
1430                                            "isCriticalSystemObject");
1431                 el->flags = LDB_FLAG_MOD_REPLACE;
1432         }
1433
1434         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
1435                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
1436
1437                 /* Older AD deployments don't know about the RODC group */
1438                 if (rid == DOMAIN_RID_READONLY_DCS) {
1439                         ret = samldb_prim_group_tester(ac, rid);
1440                         if (ret != LDB_SUCCESS) {
1441                                 return ret;
1442                         }
1443                 }
1444
1445                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1446                                          "primaryGroupID", rid);
1447                 if (ret != LDB_SUCCESS) {
1448                         return ret;
1449                 }
1450                 el = ldb_msg_find_element(ac->msg,
1451                                            "primaryGroupID");
1452                 el->flags = LDB_FLAG_MOD_REPLACE;
1453         }
1454
1455         return LDB_SUCCESS;
1456 }
1457
1458 static int samldb_group_type_change(struct samldb_ctx *ac)
1459 {
1460         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1461         uint32_t group_type, old_group_type, account_type;
1462         struct ldb_message_element *el;
1463         struct ldb_message *tmp_msg;
1464         int ret;
1465         struct ldb_result *res;
1466         const char *attrs[] = { "groupType", NULL };
1467
1468         el = dsdb_get_single_valued_attr(ac->msg, "groupType",
1469                                          ac->req->operation);
1470         if (el == NULL) {
1471                 /* we are not affected */
1472                 return LDB_SUCCESS;
1473         }
1474
1475         /* Create a temporary message for fetching the "groupType" */
1476         tmp_msg = ldb_msg_new(ac->msg);
1477         if (tmp_msg == NULL) {
1478                 return ldb_module_oom(ac->module);
1479         }
1480         ret = ldb_msg_add(tmp_msg, el, 0);
1481         if (ret != LDB_SUCCESS) {
1482                 return ret;
1483         }
1484         group_type = ldb_msg_find_attr_as_uint(tmp_msg, "groupType", 0);
1485         talloc_free(tmp_msg);
1486
1487         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,
1488                                     DSDB_FLAG_NEXT_MODULE |
1489                                     DSDB_SEARCH_SHOW_DELETED, ac->req);
1490         if (ret != LDB_SUCCESS) {
1491                 return ret;
1492         }
1493         old_group_type = ldb_msg_find_attr_as_uint(res->msgs[0], "groupType", 0);
1494         if (old_group_type == 0) {
1495                 return ldb_operr(ldb);
1496         }
1497
1498         /* Group type switching isn't so easy as it seems: We can only
1499          * change in this directions: global <-> universal <-> local
1500          * On each step also the group type itself
1501          * (security/distribution) is variable. */
1502
1503         if (ldb_request_get_control(ac->req, LDB_CONTROL_PROVISION_OID) == NULL) {
1504                 switch (group_type) {
1505                 case GTYPE_SECURITY_GLOBAL_GROUP:
1506                 case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
1507                         /* change to "universal" allowed */
1508                         if ((old_group_type == GTYPE_SECURITY_DOMAIN_LOCAL_GROUP) ||
1509                         (old_group_type == GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP)) {
1510                                 ldb_set_errstring(ldb,
1511                                         "samldb: Change from security/distribution local group forbidden!");
1512                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1513                         }
1514                 break;
1515
1516                 case GTYPE_SECURITY_UNIVERSAL_GROUP:
1517                 case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
1518                         /* each change allowed */
1519                 break;
1520                 case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
1521                 case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
1522                         /* change to "universal" allowed */
1523                         if ((old_group_type == GTYPE_SECURITY_GLOBAL_GROUP) ||
1524                         (old_group_type == GTYPE_DISTRIBUTION_GLOBAL_GROUP)) {
1525                                 ldb_set_errstring(ldb,
1526                                         "samldb: Change from security/distribution global group forbidden!");
1527                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1528                         }
1529                 break;
1530
1531                 case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
1532                 default:
1533                         /* we don't allow this "groupType" values */
1534                         return LDB_ERR_UNWILLING_TO_PERFORM;
1535                 break;
1536                 }
1537         }
1538
1539         account_type =  ds_gtype2atype(group_type);
1540         if (account_type == 0) {
1541                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1542                 return LDB_ERR_UNWILLING_TO_PERFORM;
1543         }
1544         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg, "sAMAccountType",
1545                                  account_type);
1546         if (ret != LDB_SUCCESS) {
1547                 return ret;
1548         }
1549         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
1550         el->flags = LDB_FLAG_MOD_REPLACE;
1551
1552         return LDB_SUCCESS;
1553 }
1554
1555 static int samldb_sam_accountname_check(struct samldb_ctx *ac)
1556 {
1557         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1558         const char *no_attrs[] = { NULL };
1559         struct ldb_result *res;
1560         const char *sam_accountname, *enc_str;
1561         struct ldb_message_element *el;
1562         struct ldb_message *tmp_msg;
1563         int ret;
1564
1565         el = dsdb_get_single_valued_attr(ac->msg, "sAMAccountName",
1566                                          ac->req->operation);
1567         if (el == NULL) {
1568                 /* we are not affected */
1569                 return LDB_SUCCESS;
1570         }
1571
1572         /* Create a temporary message for fetching the "sAMAccountName" */
1573         tmp_msg = ldb_msg_new(ac->msg);
1574         if (tmp_msg == NULL) {
1575                 return ldb_module_oom(ac->module);
1576         }
1577         ret = ldb_msg_add(tmp_msg, el, 0);
1578         if (ret != LDB_SUCCESS) {
1579                 return ret;
1580         }
1581         sam_accountname = talloc_steal(ac,
1582                                        ldb_msg_find_attr_as_string(tmp_msg, "sAMAccountName", NULL));
1583         talloc_free(tmp_msg);
1584
1585         if (sam_accountname == NULL) {
1586                 /* The "sAMAccountName" cannot be nothing */
1587                 ldb_set_errstring(ldb,
1588                                   "samldb: Empty account names aren't allowed!");
1589                 return LDB_ERR_UNWILLING_TO_PERFORM;
1590         }
1591
1592         enc_str = ldb_binary_encode_string(ac, sam_accountname);
1593         if (enc_str == NULL) {
1594                 return ldb_module_oom(ac->module);
1595         }
1596
1597         /* Make sure that a "sAMAccountName" is only used once */
1598
1599         ret = dsdb_module_search(ac->module, ac, &res,
1600                                  ldb_get_default_basedn(ldb),
1601                                  LDB_SCOPE_SUBTREE, no_attrs,
1602                                  DSDB_FLAG_NEXT_MODULE, ac->req,
1603                                  "(sAMAccountName=%s)", enc_str);
1604         if (ret != LDB_SUCCESS) {
1605                 return ret;
1606         }
1607         if (res->count > 1) {
1608                 return ldb_operr(ldb);
1609         } else if (res->count == 1) {
1610                 if (ldb_dn_compare(res->msgs[0]->dn, ac->msg->dn) != 0) {
1611                         ldb_asprintf_errstring(ldb,
1612                                                "samldb: Account name (sAMAccountName) '%s' already in use!",
1613                                                sam_accountname);
1614                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
1615                 }
1616         }
1617         talloc_free(res);
1618
1619         return LDB_SUCCESS;
1620 }
1621
1622 static int samldb_member_check(struct samldb_ctx *ac)
1623 {
1624         static const char * const attrs[] = { "objectSid", "member", NULL };
1625         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1626         struct ldb_message_element *el;
1627         struct ldb_dn *member_dn;
1628         struct dom_sid *sid;
1629         struct ldb_result *res;
1630         struct dom_sid *group_sid;
1631         unsigned int i, j;
1632         int ret;
1633
1634         /* Fetch information from the existing object */
1635
1636         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1637                                  DSDB_FLAG_NEXT_MODULE, ac->req, NULL);
1638         if (ret != LDB_SUCCESS) {
1639                 return ret;
1640         }
1641         if (res->count != 1) {
1642                 return ldb_operr(ldb);
1643         }
1644
1645         group_sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
1646         if (group_sid == NULL) {
1647                 return ldb_operr(ldb);
1648         }
1649
1650         /* We've to walk over all modification entries and consider the "member"
1651          * ones. */
1652         for (i = 0; i < ac->msg->num_elements; i++) {
1653                 if (ldb_attr_cmp(ac->msg->elements[i].name, "member") != 0) {
1654                         continue;
1655                 }
1656
1657                 el = &ac->msg->elements[i];
1658                 for (j = 0; j < el->num_values; j++) {
1659                         struct ldb_result *group_res;
1660                         const char *group_attrs[] = { "primaryGroupID" , NULL };
1661                         uint32_t prim_group_rid;
1662
1663                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE) {
1664                                 /* Deletes will be handled in
1665                                  * repl_meta_data, and deletes not
1666                                  * matching a member will return
1667                                  * LDB_ERR_UNWILLING_TO_PERFORM
1668                                  * there */
1669                                 continue;
1670                         }
1671
1672                         member_dn = ldb_dn_from_ldb_val(ac, ldb,
1673                                                         &el->values[j]);
1674                         if (!ldb_dn_validate(member_dn)) {
1675                                 return ldb_operr(ldb);
1676                         }
1677
1678                         /* Denies to add "member"s to groups which are primary
1679                          * ones for them - in this case return
1680                          * ERR_ENTRY_ALREADY_EXISTS. */
1681
1682                         ret = dsdb_module_search_dn(ac->module, ac, &group_res,
1683                                                     member_dn, group_attrs,
1684                                                     DSDB_FLAG_NEXT_MODULE, ac->req);
1685                         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1686                                 /* member DN doesn't exist yet */
1687                                 continue;
1688                         }
1689                         if (ret != LDB_SUCCESS) {
1690                                 return ret;
1691                         }
1692                         prim_group_rid = ldb_msg_find_attr_as_uint(group_res->msgs[0], "primaryGroupID", (uint32_t)-1);
1693                         if (prim_group_rid == (uint32_t) -1) {
1694                                 /* the member hasn't to be a user account ->
1695                                  * therefore no check needed in this case. */
1696                                 continue;
1697                         }
1698
1699                         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
1700                                               prim_group_rid);
1701                         if (sid == NULL) {
1702                                 return ldb_operr(ldb);
1703                         }
1704
1705                         if (dom_sid_equal(group_sid, sid)) {
1706                                 ldb_asprintf_errstring(ldb,
1707                                                        "samldb: member %s already set via primaryGroupID %u",
1708                                                        ldb_dn_get_linearized(member_dn), prim_group_rid);
1709                                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1710                         }
1711                 }
1712         }
1713
1714         talloc_free(res);
1715
1716         return LDB_SUCCESS;
1717 }
1718
1719 /* SAM objects have special rules regarding the "description" attribute on
1720  * modify operations. */
1721 static int samldb_description_check(struct samldb_ctx *ac, bool *modified)
1722 {
1723         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1724         const char * const attrs[] = { "objectClass", "description", NULL };
1725         struct ldb_result *res;
1726         unsigned int i;
1727         int ret;
1728
1729         /* Fetch information from the existing object */
1730         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1731                                  DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED, ac->req,
1732                                  "(|(objectclass=user)(objectclass=group)(objectclass=samDomain)(objectclass=samServer))");
1733         if (ret != LDB_SUCCESS) {
1734                 /* don't treat it specially ... let normal error codes
1735                    happen from other places */
1736                 ldb_reset_err_string(ldb);
1737                 return LDB_SUCCESS;
1738         }
1739         if (res->count == 0) {
1740                 /* we didn't match the filter */
1741                 talloc_free(res);
1742                 return LDB_SUCCESS;
1743         }
1744
1745         /* We've to walk over all modification entries and consider the
1746          * "description" ones. */
1747         for (i = 0; i < ac->msg->num_elements; i++) {
1748                 if (ldb_attr_cmp(ac->msg->elements[i].name, "description") == 0) {
1749                         ac->msg->elements[i].flags |= LDB_FLAG_INTERNAL_FORCE_SINGLE_VALUE_CHECK;
1750                         *modified = true;
1751                 }
1752         }
1753
1754         talloc_free(res);
1755
1756         return LDB_SUCCESS;
1757 }
1758
1759 /* This trigger adapts the "servicePrincipalName" attributes if the
1760  * "dNSHostName" and/or "sAMAccountName" attribute change(s) */
1761 static int samldb_service_principal_names_change(struct samldb_ctx *ac)
1762 {
1763         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
1764         struct ldb_message_element *el = NULL, *el2 = NULL;
1765         struct ldb_message *msg;
1766         const char *attrs[] = { "servicePrincipalName", NULL };
1767         struct ldb_result *res;
1768         const char *dns_hostname = NULL, *old_dns_hostname = NULL,
1769                    *sam_accountname = NULL, *old_sam_accountname = NULL;
1770         unsigned int i;
1771         int ret;
1772
1773         el = dsdb_get_single_valued_attr(ac->msg, "dNSHostName",
1774                                          ac->req->operation);
1775         el2 = dsdb_get_single_valued_attr(ac->msg, "sAMAccountName",
1776                                           ac->req->operation);
1777         if ((el == NULL) && (el2 == NULL)) {
1778                 /* we are not affected */
1779                 return LDB_SUCCESS;
1780         }
1781
1782         /* Create a temporary message for fetching the "dNSHostName" */
1783         if (el != NULL) {
1784                 const char *dns_attrs[] = { "dNSHostName", NULL };
1785                 msg = ldb_msg_new(ac->msg);
1786                 if (msg == NULL) {
1787                         return ldb_module_oom(ac->module);
1788                 }
1789                 ret = ldb_msg_add(msg, el, 0);
1790                 if (ret != LDB_SUCCESS) {
1791                         return ret;
1792                 }
1793                 dns_hostname = talloc_steal(ac,
1794                                             ldb_msg_find_attr_as_string(msg, "dNSHostName", NULL));
1795                 talloc_free(msg);
1796
1797                 ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn,
1798                                             dns_attrs, DSDB_FLAG_NEXT_MODULE, ac->req);
1799                 if (ret == LDB_SUCCESS) {
1800                         old_dns_hostname = ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
1801                 }
1802         }
1803
1804         /* Create a temporary message for fetching the "sAMAccountName" */
1805         if (el2 != NULL) {
1806                 char *tempstr, *tempstr2;
1807                 const char *acct_attrs[] = { "sAMAccountName", NULL };
1808
1809                 msg = ldb_msg_new(ac->msg);
1810                 if (msg == NULL) {
1811                         return ldb_module_oom(ac->module);
1812                 }
1813                 ret = ldb_msg_add(msg, el2, 0);
1814                 if (ret != LDB_SUCCESS) {
1815                         return ret;
1816                 }
1817                 tempstr = talloc_strdup(ac,
1818                                         ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL));
1819                 talloc_free(msg);
1820
1821                 ret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, acct_attrs,
1822                                             DSDB_FLAG_NEXT_MODULE, ac->req);
1823                 if (ret == LDB_SUCCESS) {
1824                         tempstr2 = talloc_strdup(ac,
1825                                                  ldb_msg_find_attr_as_string(res->msgs[0],
1826                                                                              "sAMAccountName", NULL));
1827                 }
1828
1829
1830                 /* The "sAMAccountName" needs some additional trimming: we need
1831                  * to remove the trailing "$"s if they exist. */
1832                 if ((tempstr != NULL) && (tempstr[0] != '\0') &&
1833                     (tempstr[strlen(tempstr) - 1] == '$')) {
1834                         tempstr[strlen(tempstr) - 1] = '\0';
1835                 }
1836                 if ((tempstr2 != NULL) && (tempstr2[0] != '\0') &&
1837                     (tempstr2[strlen(tempstr2) - 1] == '$')) {
1838                         tempstr2[strlen(tempstr2) - 1] = '\0';
1839                 }
1840                 sam_accountname = tempstr;
1841                 old_sam_accountname = tempstr2;
1842         }
1843
1844         if (old_dns_hostname == NULL) {
1845                 /* we cannot change when the old name is unknown */
1846                 dns_hostname = NULL;
1847         }
1848         if ((old_dns_hostname != NULL) && (dns_hostname != NULL) &&
1849             (strcasecmp(old_dns_hostname, dns_hostname) == 0)) {
1850                 /* The "dNSHostName" didn't change */
1851                 dns_hostname = NULL;
1852         }
1853
1854         if (old_sam_accountname == NULL) {
1855                 /* we cannot change when the old name is unknown */
1856                 sam_accountname = NULL;
1857         }
1858         if ((old_sam_accountname != NULL) && (sam_accountname != NULL) &&
1859             (strcasecmp(old_sam_accountname, sam_accountname) == 0)) {
1860                 /* The "sAMAccountName" didn't change */
1861                 sam_accountname = NULL;
1862         }
1863
1864         if ((dns_hostname == NULL) && (sam_accountname == NULL)) {
1865                 /* Well, there are information missing (old name(s)) or the
1866                  * names didn't change. We've nothing to do and can exit here */
1867                 return LDB_SUCCESS;
1868         }
1869
1870         /* Potential "servicePrincipalName" changes in the same request have to
1871          * be handled before the update (Windows behaviour). */
1872         el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
1873         if (el != NULL) {
1874                 msg = ldb_msg_new(ac->msg);
1875                 if (msg == NULL) {
1876                         return ldb_module_oom(ac->module);
1877                 }
1878                 msg->dn = ac->msg->dn;
1879
1880                 do {
1881                         ret = ldb_msg_add(msg, el, el->flags);
1882                         if (ret != LDB_SUCCESS) {
1883                                 return ret;
1884                         }
1885
1886                         ldb_msg_remove_element(ac->msg, el);
1887
1888                         el = ldb_msg_find_element(ac->msg,
1889                                                   "servicePrincipalName");
1890                 } while (el != NULL);
1891
1892                 ret = dsdb_module_modify(ac->module, msg,
1893                                          DSDB_FLAG_NEXT_MODULE, ac->req);
1894                 if (ret != LDB_SUCCESS) {
1895                         return ret;
1896                 }
1897                 talloc_free(msg);
1898         }
1899
1900         /* Fetch the "servicePrincipalName"s if any */
1901         ret = dsdb_module_search(ac->module, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1902                                  DSDB_FLAG_NEXT_MODULE, ac->req, NULL);
1903         if (ret != LDB_SUCCESS) {
1904                 return ret;
1905         }
1906         if ((res->count != 1) || (res->msgs[0]->num_elements > 1)) {
1907                 return ldb_operr(ldb);
1908         }
1909
1910         if (res->msgs[0]->num_elements == 1) {
1911                 /* Yes, we do have "servicePrincipalName"s. First we update them
1912                  * locally, that means we do always substitute the current
1913                  * "dNSHostName" with the new one and/or "sAMAccountName"
1914                  * without "$" with the new one and then we append this to the
1915                  * modification request (Windows behaviour). */
1916
1917                 for (i = 0; i < res->msgs[0]->elements[0].num_values; i++) {
1918                         char *old_str, *new_str, *pos;
1919                         const char *tok;
1920
1921                         old_str = (char *)
1922                                 res->msgs[0]->elements[0].values[i].data;
1923
1924                         new_str = talloc_strdup(ac->msg,
1925                                                 strtok_r(old_str, "/", &pos));
1926                         if (new_str == NULL) {
1927                                 return ldb_module_oom(ac->module);
1928                         }
1929
1930                         while ((tok = strtok_r(NULL, "/", &pos)) != NULL) {
1931                                 if ((dns_hostname != NULL) &&
1932                                     (strcasecmp(tok, old_dns_hostname) == 0)) {
1933                                         tok = dns_hostname;
1934                                 }
1935                                 if ((sam_accountname != NULL) &&
1936                                     (strcasecmp(tok, old_sam_accountname) == 0)) {
1937                                         tok = sam_accountname;
1938                                 }
1939
1940                                 new_str = talloc_asprintf(ac->msg, "%s/%s",
1941                                                           new_str, tok);
1942                                 if (new_str == NULL) {
1943                                         return ldb_module_oom(ac->module);
1944                                 }
1945                         }
1946
1947                         ret = ldb_msg_add_string(ac->msg,
1948                                                  "servicePrincipalName",
1949                                                  new_str);
1950                         if (ret != LDB_SUCCESS) {
1951                                 return ret;
1952                         }
1953                 }
1954
1955                 el = ldb_msg_find_element(ac->msg, "servicePrincipalName");
1956                 el->flags = LDB_FLAG_MOD_REPLACE;
1957         }
1958
1959         talloc_free(res);
1960
1961         return LDB_SUCCESS;
1962 }
1963
1964
1965 /* add */
1966 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
1967 {
1968         struct ldb_context *ldb;
1969         struct samldb_ctx *ac;
1970         int ret;
1971
1972         ldb = ldb_module_get_ctx(module);
1973         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
1974
1975         /* do not manipulate our control entries */
1976         if (ldb_dn_is_special(req->op.add.message->dn)) {
1977                 return ldb_next_request(module, req);
1978         }
1979
1980         ac = samldb_ctx_init(module, req);
1981         if (ac == NULL) {
1982                 return ldb_operr(ldb);
1983         }
1984
1985         /* build the new msg */
1986         ac->msg = ldb_msg_copy_shallow(ac, req->op.add.message);
1987         if (ac->msg == NULL) {
1988                 talloc_free(ac);
1989                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1990                           "samldb_add: ldb_msg_copy_shallow failed!\n");
1991                 return ldb_operr(ldb);
1992         }
1993
1994         if (samdb_find_attribute(ldb, ac->msg,
1995                                  "objectclass", "user") != NULL) {
1996                 ac->type = SAMLDB_TYPE_USER;
1997
1998                 ret = samldb_prim_group_trigger(ac);
1999                 if (ret != LDB_SUCCESS) {
2000                         return ret;
2001                 }
2002
2003                 ret = samldb_objectclass_trigger(ac);
2004                 if (ret != LDB_SUCCESS) {
2005                         return ret;
2006                 }
2007
2008                 return samldb_fill_object(ac);
2009         }
2010
2011         if (samdb_find_attribute(ldb, ac->msg,
2012                                  "objectclass", "group") != NULL) {
2013                 ac->type = SAMLDB_TYPE_GROUP;
2014
2015                 ret = samldb_objectclass_trigger(ac);
2016                 if (ret != LDB_SUCCESS) {
2017                         return ret;
2018                 }
2019
2020                 return samldb_fill_object(ac);
2021         }
2022
2023         /* perhaps a foreignSecurityPrincipal? */
2024         if (samdb_find_attribute(ldb, ac->msg,
2025                                  "objectclass",
2026                                  "foreignSecurityPrincipal") != NULL) {
2027                 return samldb_fill_foreignSecurityPrincipal_object(ac);
2028         }
2029
2030         if (samdb_find_attribute(ldb, ac->msg,
2031                                  "objectclass", "classSchema") != NULL) {
2032                 ret = samldb_schema_info_update(ac);
2033                 if (ret != LDB_SUCCESS) {
2034                         talloc_free(ac);
2035                         return ret;
2036                 }
2037
2038                 ac->type = SAMLDB_TYPE_CLASS;
2039                 return samldb_fill_object(ac);
2040         }
2041
2042         if (samdb_find_attribute(ldb, ac->msg,
2043                                  "objectclass", "attributeSchema") != NULL) {
2044                 ret = samldb_schema_info_update(ac);
2045                 if (ret != LDB_SUCCESS) {
2046                         talloc_free(ac);
2047                         return ret;
2048                 }
2049
2050                 ac->type = SAMLDB_TYPE_ATTRIBUTE;
2051                 return samldb_fill_object(ac);
2052         }
2053
2054         talloc_free(ac);
2055
2056         /* nothing matched, go on */
2057         return ldb_next_request(module, req);
2058 }
2059
2060 /* modify */
2061 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
2062 {
2063         struct ldb_context *ldb;
2064         struct samldb_ctx *ac;
2065         struct ldb_message_element *el, *el2;
2066         bool modified = false;
2067         int ret;
2068
2069         if (ldb_dn_is_special(req->op.mod.message->dn)) {
2070                 /* do not manipulate our control entries */
2071                 return ldb_next_request(module, req);
2072         }
2073
2074         ldb = ldb_module_get_ctx(module);
2075
2076         /* make sure that "objectSid" is not specified */
2077         el = ldb_msg_find_element(req->op.mod.message, "objectSid");
2078         if (el != NULL) {
2079                 if (ldb_request_get_control(req, LDB_CONTROL_PROVISION_OID) == NULL) {
2080                         ldb_set_errstring(ldb,
2081                                           "samldb: objectSid must not be specified!");
2082                         return LDB_ERR_UNWILLING_TO_PERFORM;
2083                 }
2084         }
2085         /* make sure that "sAMAccountType" is not specified */
2086         el = ldb_msg_find_element(req->op.mod.message, "sAMAccountType");
2087         if (el != NULL) {
2088                 ldb_set_errstring(ldb,
2089                                   "samldb: sAMAccountType must not be specified!");
2090                 return LDB_ERR_UNWILLING_TO_PERFORM;
2091         }
2092         /* make sure that "isCriticalSystemObject" is not specified */
2093         el = ldb_msg_find_element(req->op.mod.message, "isCriticalSystemObject");
2094         if (el != NULL) {
2095                 if (ldb_request_get_control(req, LDB_CONTROL_RELAX_OID) == NULL) {
2096                         ldb_set_errstring(ldb,
2097                                           "samldb: isCriticalSystemObject must not be specified!");
2098                         return LDB_ERR_UNWILLING_TO_PERFORM;
2099                 }
2100         }
2101
2102         /* msDS-IntId is not allowed to be modified
2103          * except when modification comes from replication */
2104         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
2105                 if (!ldb_request_get_control(req,
2106                                              DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
2107                         return LDB_ERR_CONSTRAINT_VIOLATION;
2108                 }
2109         }
2110
2111         ac = samldb_ctx_init(module, req);
2112         if (ac == NULL) {
2113                 return ldb_operr(ldb);
2114         }
2115
2116         /* build the new msg */
2117         ac->msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
2118         if (ac->msg == NULL) {
2119                 talloc_free(ac);
2120                 ldb_debug(ldb, LDB_DEBUG_FATAL,
2121                           "samldb_modify: ldb_msg_copy_shallow failed!\n");
2122                 return ldb_operr(ldb);
2123         }
2124
2125         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
2126         if (el != NULL) {
2127                 ret = samldb_prim_group_trigger(ac);
2128                 if (ret != LDB_SUCCESS) {
2129                         return ret;
2130                 }
2131         }
2132
2133         el = ldb_msg_find_element(ac->msg, "userAccountControl");
2134         if (el != NULL) {
2135                 modified = true;
2136                 ret = samldb_user_account_control_change(ac);
2137                 if (ret != LDB_SUCCESS) {
2138                         return ret;
2139                 }
2140         }
2141
2142         el = ldb_msg_find_element(ac->msg, "groupType");
2143         if (el != NULL) {
2144                 modified = true;
2145                 ret = samldb_group_type_change(ac);
2146                 if (ret != LDB_SUCCESS) {
2147                         return ret;
2148                 }
2149         }
2150
2151         el = ldb_msg_find_element(ac->msg, "sAMAccountName");
2152         if (el != NULL) {
2153                 ret = samldb_sam_accountname_check(ac);
2154                 if (ret != LDB_SUCCESS) {
2155                         return ret;
2156                 }
2157         }
2158
2159         el = ldb_msg_find_element(ac->msg, "member");
2160         if (el != NULL) {
2161                 ret = samldb_member_check(ac);
2162                 if (ret != LDB_SUCCESS) {
2163                         return ret;
2164                 }
2165         }
2166
2167         el = ldb_msg_find_element(ac->msg, "description");
2168         if (el != NULL) {
2169                 ret = samldb_description_check(ac, &modified);
2170                 if (ret != LDB_SUCCESS) {
2171                         return ret;
2172                 }
2173         }
2174
2175         el = ldb_msg_find_element(ac->msg, "dNSHostName");
2176         el2 = ldb_msg_find_element(ac->msg, "sAMAccountName");
2177         if ((el != NULL) || (el2 != NULL)) {
2178                 modified = true;
2179                 ret = samldb_service_principal_names_change(ac);
2180                 if (ret != LDB_SUCCESS) {
2181                         return ret;
2182                 }
2183         }
2184
2185         if (modified) {
2186                 struct ldb_request *child_req;
2187
2188                 /* Now perform the real modifications as a child request */
2189                 ret = ldb_build_mod_req(&child_req, ldb, ac,
2190                                         ac->msg,
2191                                         req->controls,
2192                                         req, dsdb_next_callback,
2193                                         req);
2194                 LDB_REQ_SET_LOCATION(child_req);
2195                 if (ret != LDB_SUCCESS) {
2196                         return ret;
2197                 }
2198
2199                 return ldb_next_request(module, child_req);
2200         }
2201
2202         talloc_free(ac);
2203
2204         /* no change which interests us, go on */
2205         return ldb_next_request(module, req);
2206 }
2207
2208 /* delete */
2209
2210 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
2211 {
2212         struct ldb_context *ldb;
2213         struct dom_sid *sid;
2214         uint32_t rid;
2215         NTSTATUS status;
2216         int ret;
2217         struct ldb_result *res;
2218         const char *attrs[] = { "objectSid", "isDeleted", NULL };
2219         const char *noattrs[] = { NULL };
2220
2221         ldb = ldb_module_get_ctx(ac->module);
2222
2223         /* Finds out the SID/RID of the SAM object */
2224         ret = dsdb_module_search_dn(ac->module, ac, &res, ac->req->op.del.dn,
2225                                         attrs,
2226                                         DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED,
2227                                         ac->req);
2228         if (ret != LDB_SUCCESS) {
2229                 return ret;
2230         }
2231
2232         if (ldb_msg_check_string_attribute(res->msgs[0], "isDeleted", "TRUE")) {
2233                 return LDB_SUCCESS;
2234         }
2235
2236         sid = samdb_result_dom_sid(ac, res->msgs[0], "objectSid");
2237         if (sid == NULL) {
2238                 /* No SID - it might not be a SAM object - therefore ok */
2239                 return LDB_SUCCESS;
2240         }
2241         status = dom_sid_split_rid(ac, sid, NULL, &rid);
2242         if (!NT_STATUS_IS_OK(status)) {
2243                 return ldb_operr(ldb);
2244         }
2245         if (rid == 0) {
2246                 /* Special object (security principal?) */
2247                 return LDB_SUCCESS;
2248         }
2249
2250         /* Deny delete requests from groups which are primary ones */
2251         ret = dsdb_module_search(ac->module, ac, &res,
2252                                  ldb_get_default_basedn(ldb),
2253                                  LDB_SCOPE_SUBTREE, noattrs,
2254                                  DSDB_FLAG_NEXT_MODULE,
2255                                  ac->req,
2256                                  "(&(primaryGroupID=%u)(objectClass=user))", rid);
2257         if (ret != LDB_SUCCESS) {
2258                 return ret;
2259         }
2260         if (res->count > 0) {
2261                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
2262         }
2263
2264         return LDB_SUCCESS;
2265 }
2266
2267 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
2268 {
2269         struct samldb_ctx *ac;
2270         int ret;
2271
2272         if (ldb_dn_is_special(req->op.del.dn)) {
2273                 /* do not manipulate our control entries */
2274                 return ldb_next_request(module, req);
2275         }
2276
2277         ac = samldb_ctx_init(module, req);
2278         if (ac == NULL) {
2279                 return ldb_operr(ldb_module_get_ctx(module));
2280         }
2281
2282         ret = samldb_prim_group_users_check(ac);
2283         if (ret != LDB_SUCCESS) {
2284                 return ret;
2285         }
2286
2287         talloc_free(ac);
2288
2289         return ldb_next_request(module, req);
2290 }
2291
2292 /* extended */
2293
2294 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
2295 {
2296         struct ldb_context *ldb = ldb_module_get_ctx(module);
2297         struct dsdb_fsmo_extended_op *exop;
2298         int ret;
2299
2300         exop = talloc_get_type(req->op.extended.data,
2301                                struct dsdb_fsmo_extended_op);
2302         if (!exop) {
2303                 ldb_set_errstring(ldb,
2304                                   "samldb_extended_allocate_rid_pool: invalid extended data");
2305                 return LDB_ERR_PROTOCOL_ERROR;
2306         }
2307
2308         ret = ridalloc_allocate_rid_pool_fsmo(module, exop, req);
2309         if (ret != LDB_SUCCESS) {
2310                 return ret;
2311         }
2312
2313         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
2314 }
2315
2316 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
2317 {
2318         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
2319                 return samldb_extended_allocate_rid_pool(module, req);
2320         }
2321
2322         return ldb_next_request(module, req);
2323 }
2324
2325
2326 static const struct ldb_module_ops ldb_samldb_module_ops = {
2327         .name          = "samldb",
2328         .add           = samldb_add,
2329         .modify        = samldb_modify,
2330         .del           = samldb_delete,
2331         .extended      = samldb_extended
2332 };
2333
2334
2335 int ldb_samldb_module_init(const char *version)
2336 {
2337         LDB_MODULE_CHECK_VERSION(version);
2338         return ldb_register_module(&ldb_samldb_module_ops);
2339 }