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