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