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