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