s4:samldb LDB module - fix indentations
[metze/samba/wip.git] / source4 / dsdb / samdb / ldb_modules / samldb.c
1 /*
2    SAM ldb module
3
4    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
5    Copyright (C) Simo Sorce  2004-2008
6    Copyright (C) Matthias Dieter Wallnöfer 2009-2010
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /*
23  *  Name: ldb
24  *
25  *  Component: ldb samldb module
26  *
27  *  Description: various internal DSDB triggers - most for SAM specific objects
28  *
29  *  Author: Simo Sorce
30  */
31
32 #include "includes.h"
33 #include "libcli/ldap/ldap_ndr.h"
34 #include "ldb_module.h"
35 #include "dsdb/samdb/samdb.h"
36 #include "dsdb/samdb/ldb_modules/util.h"
37 #include "dsdb/samdb/ldb_modules/ridalloc.h"
38 #include "libcli/security/security.h"
39 #include "librpc/gen_ndr/ndr_security.h"
40 #include "ldb_wrap.h"
41 #include "param/param.h"
42
43 struct samldb_ctx;
44
45 typedef int (*samldb_step_fn_t)(struct samldb_ctx *);
46
47 struct samldb_step {
48         struct samldb_step *next;
49         samldb_step_fn_t fn;
50 };
51
52 struct samldb_ctx {
53         struct ldb_module *module;
54         struct ldb_request *req;
55
56         /* used for add operations */
57         const char *type;
58
59         /* the resulting message */
60         struct ldb_message *msg;
61
62         /* used in "samldb_find_for_defaultObjectCategory" */
63         struct ldb_dn *dn, *res_dn;
64
65         /* all the async steps necessary to complete the operation */
66         struct samldb_step *steps;
67         struct samldb_step *curstep;
68
69         /* If someone set an ares to forward controls and response back to the caller */
70         struct ldb_reply *ares;
71 };
72
73 static struct samldb_ctx *samldb_ctx_init(struct ldb_module *module,
74                                           struct ldb_request *req)
75 {
76         struct ldb_context *ldb;
77         struct samldb_ctx *ac;
78
79         ldb = ldb_module_get_ctx(module);
80
81         ac = talloc_zero(req, struct samldb_ctx);
82         if (ac == NULL) {
83                 ldb_oom(ldb);
84                 return NULL;
85         }
86
87         ac->module = module;
88         ac->req = req;
89
90         return ac;
91 }
92
93 static int samldb_add_step(struct samldb_ctx *ac, samldb_step_fn_t fn)
94 {
95         struct samldb_step *step, *stepper;
96
97         step = talloc_zero(ac, struct samldb_step);
98         if (step == NULL) {
99                 return ldb_oom(ldb_module_get_ctx(ac->module));
100         }
101
102         step->fn = fn;
103
104         if (ac->steps == NULL) {
105                 ac->steps = step;
106                 ac->curstep = step;
107         } else {
108                 if (ac->curstep == NULL)
109                         return ldb_operr(ldb_module_get_ctx(ac->module));
110                 for (stepper = ac->curstep; stepper->next != NULL;
111                         stepper = stepper->next);
112                 stepper->next = step;
113         }
114
115         return LDB_SUCCESS;
116 }
117
118 static int samldb_first_step(struct samldb_ctx *ac)
119 {
120         if (ac->steps == NULL) {
121                 return ldb_operr(ldb_module_get_ctx(ac->module));
122         }
123
124         ac->curstep = ac->steps;
125         return ac->curstep->fn(ac);
126 }
127
128 static int samldb_next_step(struct samldb_ctx *ac)
129 {
130         if (ac->curstep->next) {
131                 ac->curstep = ac->curstep->next;
132                 return ac->curstep->fn(ac);
133         }
134
135         /* We exit the samldb module here. If someone set an "ares" to forward
136          * controls and response back to the caller, use them. */
137         if (ac->ares) {
138                 return ldb_module_done(ac->req, ac->ares->controls,
139                                        ac->ares->response, LDB_SUCCESS);
140         } else {
141                 return ldb_module_done(ac->req, NULL, NULL, LDB_SUCCESS);
142         }
143 }
144
145
146 /* sAMAccountName handling */
147
148 static int samldb_generate_sAMAccountName(struct ldb_context *ldb,
149                                           struct ldb_message *msg)
150 {
151         char *name;
152
153         /* Format: $000000-000000000000 */
154
155         name = talloc_asprintf(msg, "$%.6X-%.6X%.6X",
156                                 (unsigned int)generate_random(),
157                                 (unsigned int)generate_random(),
158                                 (unsigned int)generate_random());
159         if (name == NULL) {
160                 return ldb_oom(ldb);
161         }
162         return ldb_msg_add_steal_string(msg, "sAMAccountName", name);
163 }
164
165 static int samldb_check_sAMAccountName(struct samldb_ctx *ac)
166 {
167         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
168         const char *name;
169         int ret;
170
171         if (ldb_msg_find_element(ac->msg, "sAMAccountName") == NULL) {
172                 ret = samldb_generate_sAMAccountName(ldb, ac->msg);
173                 if (ret != LDB_SUCCESS) {
174                         return ret;
175                 }
176         }
177
178         name = ldb_msg_find_attr_as_string(ac->msg, "sAMAccountName", NULL);
179         if (name == NULL) {
180                 return ldb_operr(ldb);
181         }
182
183         ret = samdb_search_count(ldb, NULL, "(sAMAccountName=%s)",
184                                  ldb_binary_encode_string(ac, name));
185         if ((ret < 0) || (ret > 1)) {
186                 return ldb_operr(ldb);
187         }
188         if (ret == 1) {
189                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
190         }
191
192         return samldb_next_step(ac);
193 }
194
195
196 static bool samldb_msg_add_sid(struct ldb_message *msg,
197                                 const char *name,
198                                 const struct dom_sid *sid)
199 {
200         struct ldb_val v;
201         enum ndr_err_code ndr_err;
202
203         ndr_err = ndr_push_struct_blob(&v, msg, sid,
204                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
205         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
206                 return false;
207         }
208         return (ldb_msg_add_value(msg, name, &v, NULL) == 0);
209 }
210
211
212 /* allocate a SID using our RID Set */
213 static int samldb_allocate_sid(struct samldb_ctx *ac)
214 {
215         uint32_t rid;
216         struct dom_sid *sid;
217         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
218         int ret;
219
220         ret = ridalloc_allocate_rid(ac->module, &rid);
221         if (ret != LDB_SUCCESS) {
222                 return ret;
223         }
224
225         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
226         if (sid == NULL) {
227                 return ldb_module_oom(ac->module);
228         }
229
230         if ( ! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
231                 return ldb_operr(ldb);
232         }
233
234         return samldb_next_step(ac);
235 }
236
237 /*
238   see if a krbtgt_number is available
239  */
240 static bool samldb_krbtgtnumber_available(struct samldb_ctx *ac,
241                                           uint32_t krbtgt_number)
242 {
243         TALLOC_CTX *tmp_ctx = talloc_new(ac);
244         struct ldb_result *res;
245         const char *no_attrs[] = { NULL };
246         int ret;
247
248         ret = dsdb_module_search(ac->module, tmp_ctx, &res, NULL,
249                                  LDB_SCOPE_SUBTREE, no_attrs,
250                                  DSDB_FLAG_NEXT_MODULE,
251                                  "(msDC-SecondaryKrbTgtNumber=%u)",
252                                  krbtgt_number);
253         if (ret == LDB_SUCCESS && res->count == 0) {
254                 talloc_free(tmp_ctx);
255                 return true;
256         }
257         talloc_free(tmp_ctx);
258         return false;
259 }
260
261 /* special handling for add in RODC join */
262 static int samldb_rodc_add(struct samldb_ctx *ac)
263 {
264         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
265         uint32_t krbtgt_number, i_start, i;
266         int ret;
267         char *newpass;
268
269         /* find a unused msDC-SecondaryKrbTgtNumber */
270         i_start = generate_random() & 0xFFFF;
271         if (i_start == 0) {
272                 i_start = 1;
273         }
274
275         for (i=i_start; i<=0xFFFF; i++) {
276                 if (samldb_krbtgtnumber_available(ac, i)) {
277                         krbtgt_number = i;
278                         goto found;
279                 }
280         }
281         for (i=1; i<i_start; i++) {
282                 if (samldb_krbtgtnumber_available(ac, i)) {
283                         krbtgt_number = i;
284                         goto found;
285                 }
286         }
287
288         ldb_asprintf_errstring(ldb,
289                                "%08X: Unable to find available msDS-SecondaryKrbTgtNumber",
290                                W_ERROR_V(WERR_NO_SYSTEM_RESOURCES));
291         return LDB_ERR_OTHER;
292
293 found:
294         ret = ldb_msg_add_empty(ac->msg, "msDS-SecondaryKrbTgtNumber",
295                                 LDB_FLAG_INTERNAL_DISABLE_VALIDATION, NULL);
296         if (ret != LDB_SUCCESS) {
297                 return ldb_operr(ldb);
298         }
299
300         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
301                                  "msDS-SecondaryKrbTgtNumber", krbtgt_number);
302         if (ret != LDB_SUCCESS) {
303                 return ldb_operr(ldb);
304         }
305
306         ret = ldb_msg_add_fmt(ac->msg, "sAMAccountName", "krbtgt_%u",
307                               krbtgt_number);
308         if (ret != LDB_SUCCESS) {
309                 return ldb_operr(ldb);
310         }
311
312         newpass = generate_random_password(ac->msg, 128, 255);
313         if (newpass == NULL) {
314                 return ldb_operr(ldb);
315         }
316
317         ret = ldb_msg_add_steal_string(ac->msg, "clearTextPassword", newpass);
318         if (ret != LDB_SUCCESS) {
319                 return ldb_operr(ldb);
320         }
321
322         return samldb_next_step(ac);
323 }
324
325 static int samldb_find_for_defaultObjectCategory(struct samldb_ctx *ac)
326 {
327         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
328         struct ldb_result *res;
329         const char *no_attrs[] = { NULL };
330         int ret;
331
332         ac->res_dn = NULL;
333
334         ret = dsdb_module_search(ac->module, ac, &res,
335                                  ac->dn, LDB_SCOPE_BASE, no_attrs,
336                                  DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT
337                                  | DSDB_FLAG_NEXT_MODULE,
338                                  "(objectClass=classSchema)");
339         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
340                 /* Don't be pricky when the DN doesn't exist if we have the */
341                 /* RELAX control specified */
342                 if (ldb_request_get_control(ac->req,
343                                             LDB_CONTROL_RELAX_OID) == NULL) {
344                         ldb_set_errstring(ldb,
345                                           "samldb_find_defaultObjectCategory: "
346                                           "Invalid DN for 'defaultObjectCategory'!");
347                         return LDB_ERR_CONSTRAINT_VIOLATION;
348                 }
349         }
350         if ((ret != LDB_ERR_NO_SUCH_OBJECT) && (ret != LDB_SUCCESS)) {
351                 return ret;
352         }
353
354         ac->res_dn = ac->dn;
355
356         return samldb_next_step(ac);
357 }
358
359 /**
360  * msDS-IntId attributeSchema attribute handling
361  * during LDB_ADD request processing
362  */
363 static int samldb_add_handle_msDS_IntId(struct samldb_ctx *ac)
364 {
365         int ret;
366         bool id_exists;
367         uint32_t msds_intid;
368         int32_t system_flags;
369         struct ldb_context *ldb;
370         struct ldb_result *ldb_res;
371         struct ldb_dn *schema_dn;
372
373         ldb = ldb_module_get_ctx(ac->module);
374         schema_dn = ldb_get_schema_basedn(ldb);
375
376         /* replicated update should always go through */
377         if (ldb_request_get_control(ac->req,
378                                     DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
379                 return LDB_SUCCESS;
380         }
381
382         /* msDS-IntId is handled by system and should never be
383          * passed by clients */
384         if (ldb_msg_find_element(ac->msg, "msDS-IntId")) {
385                 return LDB_ERR_UNWILLING_TO_PERFORM;
386         }
387
388         /* do not generate msDS-IntId if Relax control is passed */
389         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
390                 return LDB_SUCCESS;
391         }
392
393         /* check Functional Level */
394         if (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003) {
395                 return LDB_SUCCESS;
396         }
397
398         /* check systemFlags for SCHEMA_BASE_OBJECT flag */
399         system_flags = ldb_msg_find_attr_as_int(ac->msg, "systemFlags", 0);
400         if (system_flags & SYSTEM_FLAG_SCHEMA_BASE_OBJECT) {
401                 return LDB_SUCCESS;
402         }
403
404         /* Generate new value for msDs-IntId
405          * Value should be in 0x80000000..0xBFFFFFFF range */
406         msds_intid = generate_random() % 0X3FFFFFFF;
407         msds_intid += 0x80000000;
408
409         /* probe id values until unique one is found */
410         do {
411                 msds_intid++;
412                 if (msds_intid > 0xBFFFFFFF) {
413                         msds_intid = 0x80000001;
414                 }
415
416                 ret = dsdb_module_search(ac->module, ac,
417                                          &ldb_res,
418                                          schema_dn, LDB_SCOPE_ONELEVEL, NULL,
419                                          DSDB_FLAG_NEXT_MODULE,
420                                          "(msDS-IntId=%d)", msds_intid);
421                 if (ret != LDB_SUCCESS) {
422                         ldb_debug_set(ldb, LDB_DEBUG_ERROR,
423                                       __location__": Searching for msDS-IntId=%d failed - %s\n",
424                                       msds_intid,
425                                       ldb_errstring(ldb));
426                         return ldb_operr(ldb);
427                 }
428                 id_exists = (ldb_res->count > 0);
429
430                 talloc_free(ldb_res);
431         } while(id_exists);
432
433         return samdb_msg_add_int(ldb, ac->msg, ac->msg, "msDS-IntId",
434                                  msds_intid);
435 }
436
437
438 /*
439  * samldb_add_entry (async)
440  */
441
442 static int samldb_add_entry_callback(struct ldb_request *req,
443                                         struct ldb_reply *ares)
444 {
445         struct ldb_context *ldb;
446         struct samldb_ctx *ac;
447         int ret;
448
449         ac = talloc_get_type(req->context, struct samldb_ctx);
450         ldb = ldb_module_get_ctx(ac->module);
451
452         if (!ares) {
453                 return ldb_module_done(ac->req, NULL, NULL,
454                                         LDB_ERR_OPERATIONS_ERROR);
455         }
456
457         if (ares->type == LDB_REPLY_REFERRAL) {
458                 return ldb_module_send_referral(ac->req, ares->referral);
459         }
460
461         if (ares->error != LDB_SUCCESS) {
462                 return ldb_module_done(ac->req, ares->controls,
463                                         ares->response, ares->error);
464         }
465         if (ares->type != LDB_REPLY_DONE) {
466                 ldb_set_errstring(ldb,
467                         "Invalid reply type!\n");
468                 return ldb_module_done(ac->req, NULL, NULL,
469                                         LDB_ERR_OPERATIONS_ERROR);
470         }
471
472         /* The caller may wish to get controls back from the add */
473         ac->ares = talloc_steal(ac, ares);
474
475         ret = samldb_next_step(ac);
476         if (ret != LDB_SUCCESS) {
477                 return ldb_module_done(ac->req, NULL, NULL, ret);
478         }
479         return ret;
480 }
481
482 static int samldb_add_entry(struct samldb_ctx *ac)
483 {
484         struct ldb_context *ldb;
485         struct ldb_request *req;
486         int ret;
487
488         ldb = ldb_module_get_ctx(ac->module);
489
490         ret = ldb_build_add_req(&req, ldb, ac,
491                                 ac->msg,
492                                 ac->req->controls,
493                                 ac, samldb_add_entry_callback,
494                                 ac->req);
495         LDB_REQ_SET_LOCATION(req);
496         if (ret != LDB_SUCCESS) {
497                 return ret;
498         }
499
500         return ldb_next_request(ac->module, req);
501 }
502
503 /*
504  * return true if msg carries an attributeSchema that is intended to be RODC
505  * filtered but is also a system-critical attribute.
506  */
507 static bool check_rodc_critical_attribute(struct ldb_message *msg)
508 {
509         uint32_t schemaFlagsEx, searchFlags, rodc_filtered_flags;
510
511         schemaFlagsEx = ldb_msg_find_attr_as_uint(msg, "schemaFlagsEx", 0);
512         searchFlags = ldb_msg_find_attr_as_uint(msg, "searchFlags", 0);
513         rodc_filtered_flags = (SEARCH_FLAG_RODC_ATTRIBUTE
514                               | SEARCH_FLAG_CONFIDENTIAL);
515
516         if ((schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) &&
517                 ((searchFlags & rodc_filtered_flags) == rodc_filtered_flags)) {
518                 return true;
519         } else {
520                 return false;
521         }
522 }
523
524
525 static int samldb_fill_object(struct samldb_ctx *ac)
526 {
527         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
528         int ret;
529
530         /* Add informations for the different account types */
531         if (strcmp(ac->type, "user") == 0) {
532                 struct ldb_control *rodc_control = ldb_request_get_control(ac->req,
533                                                                            LDB_CONTROL_RODC_DCPROMO_OID);
534                 if (rodc_control != NULL) {
535                         /* see [MS-ADTS] 3.1.1.3.4.1.23 LDAP_SERVER_RODC_DCPROMO_OID */
536                         rodc_control->critical = false;
537                         ret = samldb_add_step(ac, samldb_rodc_add);
538                         if (ret != LDB_SUCCESS) return ret;
539                 }
540
541                 /* check if we have a valid sAMAccountName */
542                 ret = samldb_add_step(ac, samldb_check_sAMAccountName);
543                 if (ret != LDB_SUCCESS) return ret;
544
545                 ret = samldb_add_step(ac, samldb_add_entry);
546                 if (ret != LDB_SUCCESS) return ret;
547
548         } else if (strcmp(ac->type, "group") == 0) {
549                 /* check if we have a valid sAMAccountName */
550                 ret = samldb_add_step(ac, samldb_check_sAMAccountName);
551                 if (ret != LDB_SUCCESS) return ret;
552
553                 ret = samldb_add_step(ac, samldb_add_entry);
554                 if (ret != LDB_SUCCESS) return ret;
555
556         } else if (strcmp(ac->type, "classSchema") == 0) {
557                 const struct ldb_val *rdn_value, *def_obj_cat_val;
558
559                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
560                                                   "rdnAttId", "cn");
561                 if (ret != LDB_SUCCESS) return ret;
562
563                 /* do not allow to mark an attributeSchema as RODC filtered if it
564                  * is system-critical */
565                 if (check_rodc_critical_attribute(ac->msg)) {
566                         ldb_asprintf_errstring(ldb, "Refusing schema add of %s - cannot combine critical class with RODC filtering",
567                                                ldb_dn_get_linearized(ac->msg->dn));
568                         return LDB_ERR_UNWILLING_TO_PERFORM;
569                 }
570
571                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
572                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
573                         /* the RDN has prefix "CN" */
574                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
575                                 samdb_cn_to_lDAPDisplayName(ac->msg,
576                                                             (const char *) rdn_value->data));
577                         if (ret != LDB_SUCCESS) {
578                                 ldb_oom(ldb);
579                                 return ret;
580                         }
581                 }
582
583                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
584                         struct GUID guid;
585                         /* a new GUID */
586                         guid = GUID_random();
587                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
588                         if (ret != LDB_SUCCESS) {
589                                 ldb_oom(ldb);
590                                 return ret;
591                         }
592                 }
593
594                 def_obj_cat_val = ldb_msg_find_ldb_val(ac->msg,
595                                                        "defaultObjectCategory");
596                 if (def_obj_cat_val != NULL) {
597                         /* "defaultObjectCategory" has been set by the caller.
598                          * Do some checks for consistency.
599                          * NOTE: The real constraint check (that
600                          * 'defaultObjectCategory' is the DN of the new
601                          * objectclass or any parent of it) is still incomplete.
602                          * For now we say that 'defaultObjectCategory' is valid
603                          * if it exists and it is of objectclass "classSchema".
604                          */
605                         ac->dn = ldb_dn_from_ldb_val(ac, ldb, def_obj_cat_val);
606                         if (ac->dn == NULL) {
607                                 ldb_set_errstring(ldb,
608                                                   "Invalid DN for 'defaultObjectCategory'!");
609                                 return LDB_ERR_CONSTRAINT_VIOLATION;
610                         }
611                 } else {
612                         /* "defaultObjectCategory" has not been set by the
613                          * caller. Use the entry DN for it. */
614                         ac->dn = ac->msg->dn;
615
616                         ret = ldb_msg_add_string(ac->msg, "defaultObjectCategory",
617                                                  ldb_dn_alloc_linearized(ac->msg, ac->dn));
618                         if (ret != LDB_SUCCESS) {
619                                 ldb_oom(ldb);
620                                 return ret;
621                         }
622                 }
623
624                 ret = samldb_add_step(ac, samldb_add_entry);
625                 if (ret != LDB_SUCCESS) return ret;
626
627                 /* Now perform the checks for the 'defaultObjectCategory'. The
628                  * lookup DN was already saved in "ac->dn" */
629                 ret = samldb_add_step(ac, samldb_find_for_defaultObjectCategory);
630                 if (ret != LDB_SUCCESS) return ret;
631
632         } else if (strcmp(ac->type, "attributeSchema") == 0) {
633                 const struct ldb_val *rdn_value;
634                 rdn_value = ldb_dn_get_rdn_val(ac->msg->dn);
635                 if (!ldb_msg_find_element(ac->msg, "lDAPDisplayName")) {
636                         /* the RDN has prefix "CN" */
637                         ret = ldb_msg_add_string(ac->msg, "lDAPDisplayName",
638                                 samdb_cn_to_lDAPDisplayName(ac->msg,
639                                                             (const char *) rdn_value->data));
640                         if (ret != LDB_SUCCESS) {
641                                 ldb_oom(ldb);
642                                 return ret;
643                         }
644                 }
645
646                 /* do not allow to mark an attributeSchema as RODC filtered if it
647                  * is system-critical */
648                 if (check_rodc_critical_attribute(ac->msg)) {
649                         ldb_asprintf_errstring(ldb, "Refusing schema add of %s - cannot combine critical attribute with RODC filtering",
650                                                ldb_dn_get_linearized(ac->msg->dn));
651                         return LDB_ERR_UNWILLING_TO_PERFORM;
652                 }
653
654                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
655                                                   "isSingleValued", "FALSE");
656                 if (ret != LDB_SUCCESS) return ret;
657
658                 if (!ldb_msg_find_element(ac->msg, "schemaIDGUID")) {
659                         struct GUID guid;
660                         /* a new GUID */
661                         guid = GUID_random();
662                         ret = dsdb_msg_add_guid(ac->msg, &guid, "schemaIDGUID");
663                         if (ret != LDB_SUCCESS) {
664                                 ldb_oom(ldb);
665                                 return ret;
666                         }
667                 }
668
669                 /* handle msDS-IntID attribute */
670                 ret = samldb_add_handle_msDS_IntId(ac);
671                 if (ret != LDB_SUCCESS) return ret;
672
673                 ret = samldb_add_step(ac, samldb_add_entry);
674                 if (ret != LDB_SUCCESS) return ret;
675
676         } else {
677                 ldb_asprintf_errstring(ldb,
678                         "Invalid entry type!");
679                 return LDB_ERR_OPERATIONS_ERROR;
680         }
681
682         return samldb_first_step(ac);
683 }
684
685 static int samldb_fill_foreignSecurityPrincipal_object(struct samldb_ctx *ac)
686 {
687         struct ldb_context *ldb;
688         struct dom_sid *sid;
689         int ret;
690
691         ldb = ldb_module_get_ctx(ac->module);
692
693         sid = samdb_result_dom_sid(ac->msg, ac->msg, "objectSid");
694         if (sid == NULL) {
695                 sid = dom_sid_parse_talloc(ac->msg,
696                                            (const char *)ldb_dn_get_rdn_val(ac->msg->dn)->data);
697                 if (sid == NULL) {
698                         ldb_set_errstring(ldb,
699                                         "No valid SID found in "
700                                         "ForeignSecurityPrincipal CN!");
701                         return LDB_ERR_CONSTRAINT_VIOLATION;
702                 }
703                 if (! samldb_msg_add_sid(ac->msg, "objectSid", sid)) {
704                         return ldb_operr(ldb);
705                 }
706         }
707
708         /* finally proceed with adding the entry */
709         ret = samldb_add_step(ac, samldb_add_entry);
710         if (ret != LDB_SUCCESS) return ret;
711
712         return samldb_first_step(ac);
713 }
714
715 static int samldb_schema_info_update(struct samldb_ctx *ac)
716 {
717         int ret;
718         struct ldb_context *ldb;
719         struct dsdb_schema *schema;
720
721         /* replicated update should always go through */
722         if (ldb_request_get_control(ac->req,
723                                     DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
724                 return LDB_SUCCESS;
725         }
726
727         /* do not update schemaInfo during provisioning */
728         if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
729                 return LDB_SUCCESS;
730         }
731
732         ldb = ldb_module_get_ctx(ac->module);
733         schema = dsdb_get_schema(ldb, NULL);
734         if (!schema) {
735                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
736                               "samldb_schema_info_update: no dsdb_schema loaded");
737                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
738                 return ldb_operr(ldb);
739         }
740
741         ret = dsdb_module_schema_info_update(ac->module, schema,
742                                              DSDB_FLAG_NEXT_MODULE);
743         if (ret != LDB_SUCCESS) {
744                 ldb_asprintf_errstring(ldb, "samldb_schema_info_update: dsdb_module_schema_info_update failed with %s",
745                                        ldb_errstring(ldb));
746                 return ret;
747         }
748
749         return LDB_SUCCESS;
750 }
751
752 /*
753  * "Objectclass" trigger (MS-SAMR 3.1.1.8.1)
754  *
755  * Has to be invoked on "add" and "modify" operations on "user", "computer" and
756  * "group" objects.
757  * ac->msg contains the "add"/"modify" message
758  * ac->type contains the object type (main objectclass)
759  */
760 static int samldb_objectclass_trigger(struct samldb_ctx *ac)
761 {
762         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
763         struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb,
764                                          "loadparm"), struct loadparm_context);
765         struct ldb_message_element *el, *el2;
766         enum sid_generator sid_generator;
767         struct dom_sid *sid;
768         const char *tempstr;
769         int ret;
770
771         /* make sure that "sAMAccountType" is not specified */
772         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
773         if (el != NULL) {
774                 ldb_set_errstring(ldb,
775                         "samldb: sAMAccountType must not be specified!");
776                 return LDB_ERR_UNWILLING_TO_PERFORM;
777         }
778
779         /* Step 1: objectSid assignment */
780
781         /* Don't allow the objectSid to be changed. But beside the RELAX
782          * control we have also to guarantee that it can always be set with
783          * SYSTEM permissions. This is needed for the "samba3sam" backend. */
784         sid = samdb_result_dom_sid(ac, ac->msg, "objectSid");
785         if ((sid != NULL) && (!dsdb_module_am_system(ac->module)) &&
786             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
787                 ldb_asprintf_errstring(ldb, "No SID may be specified in user/group modifications for %s",
788                                        ldb_dn_get_linearized(ac->msg->dn));
789                 return LDB_ERR_UNWILLING_TO_PERFORM;
790         }
791
792         /* but generate a new SID when we do have an add operations */
793         if ((sid == NULL) && (ac->req->operation == LDB_ADD)) {
794                 sid_generator = lpcfg_sid_generator(lp_ctx);
795                 if (sid_generator == SID_GENERATOR_INTERNAL) {
796                         ret = samldb_add_step(ac, samldb_allocate_sid);
797                         if (ret != LDB_SUCCESS) return ret;
798                 }
799         }
800
801         if (strcmp(ac->type, "user") == 0) {
802                 /* Step 1.2: Default values */
803                 tempstr = talloc_asprintf(ac->msg, "%d", UF_NORMAL_ACCOUNT);
804                 if (tempstr == NULL) return ldb_operr(ldb);
805                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
806                         "userAccountControl", tempstr);
807                 if (ret != LDB_SUCCESS) return ret;
808                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
809                         "badPwdCount", "0");
810                 if (ret != LDB_SUCCESS) return ret;
811                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
812                         "codePage", "0");
813                 if (ret != LDB_SUCCESS) return ret;
814                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
815                         "countryCode", "0");
816                 if (ret != LDB_SUCCESS) return ret;
817                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
818                         "badPasswordTime", "0");
819                 if (ret != LDB_SUCCESS) return ret;
820                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
821                         "lastLogoff", "0");
822                 if (ret != LDB_SUCCESS) return ret;
823                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
824                         "lastLogon", "0");
825                 if (ret != LDB_SUCCESS) return ret;
826                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
827                         "pwdLastSet", "0");
828                 if (ret != LDB_SUCCESS) return ret;
829                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
830                         "accountExpires", "9223372036854775807");
831                 if (ret != LDB_SUCCESS) return ret;
832                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
833                         "logonCount", "0");
834                 if (ret != LDB_SUCCESS) return ret;
835
836                 el = ldb_msg_find_element(ac->msg, "userAccountControl");
837                 if (el != NULL) {
838                         uint32_t user_account_control, account_type;
839
840                         /* Step 1.3: "userAccountControl" -> "sAMAccountType" mapping */
841                         user_account_control = ldb_msg_find_attr_as_uint(ac->msg,
842                                                                          "userAccountControl",
843                                                                          0);
844
845                         /* Temporary duplicate accounts aren't allowed */
846                         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
847                                 return LDB_ERR_OTHER;
848                         }
849
850                         account_type = ds_uf2atype(user_account_control);
851                         if (account_type == 0) {
852                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
853                                 return LDB_ERR_UNWILLING_TO_PERFORM;
854                         }
855                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
856                                                  "sAMAccountType",
857                                                  account_type);
858                         if (ret != LDB_SUCCESS) {
859                                 return ret;
860                         }
861                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
862                         el2->flags = LDB_FLAG_MOD_REPLACE;
863
864                         if (user_account_control &
865                             (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
866                                 ret = samdb_msg_set_string(ldb, ac->msg, ac->msg,
867                                                            "isCriticalSystemObject",
868                                                            "TRUE");
869                                 if (ret != LDB_SUCCESS) {
870                                         return ret;
871                                 }
872                                 el2 = ldb_msg_find_element(ac->msg,
873                                                            "isCriticalSystemObject");
874                                 el2->flags = LDB_FLAG_MOD_REPLACE;
875                         }
876
877                         /* Step 1.4: "userAccountControl" -> "primaryGroupID" mapping */
878                         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
879                                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
880                                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
881                                                          "primaryGroupID", rid);
882                                 if (ret != LDB_SUCCESS) {
883                                         return ret;
884                                 }
885                                 el2 = ldb_msg_find_element(ac->msg,
886                                                            "primaryGroupID");
887                                 el2->flags = LDB_FLAG_MOD_REPLACE;
888                         }
889
890                         /* Step 1.5: Add additional flags when needed */
891                         if ((user_account_control & UF_NORMAL_ACCOUNT) &&
892                             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
893                                 user_account_control |= UF_ACCOUNTDISABLE;
894                                 user_account_control |= UF_PASSWD_NOTREQD;
895
896                                 ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
897                                                          "userAccountControl",
898                                                          user_account_control);
899                                 if (ret != LDB_SUCCESS) {
900                                         return ret;
901                                 }
902                         }
903                 }
904
905         } else if (strcmp(ac->type, "group") == 0) {
906                 /* Step 2.2: Default values */
907                 tempstr = talloc_asprintf(ac->msg, "%d",
908                                           GTYPE_SECURITY_GLOBAL_GROUP);
909                 if (tempstr == NULL) return ldb_operr(ldb);
910                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
911                         "groupType", tempstr);
912                 if (ret != LDB_SUCCESS) return ret;
913
914                 /* Step 2.3: "groupType" -> "sAMAccountType" */
915                 el = ldb_msg_find_element(ac->msg, "groupType");
916                 if (el != NULL) {
917                         uint32_t group_type, account_type;
918
919                         group_type = ldb_msg_find_attr_as_uint(ac->msg,
920                                                                "groupType", 0);
921
922                         /* The creation of builtin groups requires the
923                          * RELAX control */
924                         if (group_type == GTYPE_SECURITY_BUILTIN_LOCAL_GROUP) {
925                                 if (ldb_request_get_control(ac->req,
926                                                             LDB_CONTROL_RELAX_OID) == NULL) {
927                                         return LDB_ERR_UNWILLING_TO_PERFORM;
928                                 }
929                         }
930
931                         account_type = ds_gtype2atype(group_type);
932                         if (account_type == 0) {
933                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
934                                 return LDB_ERR_UNWILLING_TO_PERFORM;
935                         }
936                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
937                                                  "sAMAccountType",
938                                                  account_type);
939                         if (ret != LDB_SUCCESS) {
940                                 return ret;
941                         }
942                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
943                         el2->flags = LDB_FLAG_MOD_REPLACE;
944                 }
945         }
946
947         return LDB_SUCCESS;
948 }
949
950 /*
951  * "Primary group ID" trigger (MS-SAMR 3.1.1.8.2)
952  *
953  * Has to be invoked on "add" and "modify" operations on "user" and "computer"
954  * objects.
955  * ac->msg contains the "add"/"modify" message
956  */
957
958 static int samldb_prim_group_set(struct samldb_ctx *ac)
959 {
960         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
961         struct ldb_dn *prim_group_dn;
962         uint32_t rid;
963         struct dom_sid *sid;
964
965         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
966         if (rid == (uint32_t) -1) {
967                 /* we aren't affected of any primary group set */
968                 return LDB_SUCCESS;
969
970         } else if (!ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
971                 ldb_set_errstring(ldb,
972                                   "The primary group isn't settable on add operations!");
973                 return LDB_ERR_UNWILLING_TO_PERFORM;
974         }
975
976         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
977         if (sid == NULL) {
978                 return ldb_operr(ldb);
979         }
980
981         prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
982                                         ldap_encode_ndr_dom_sid(ac, sid));
983         if (prim_group_dn == NULL) {
984                 ldb_asprintf_errstring(ldb,
985                                        "Failed to find primary group with RID %u!",
986                                        rid);
987                 return LDB_ERR_UNWILLING_TO_PERFORM;
988         }
989
990         return LDB_SUCCESS;
991 }
992
993 static int samldb_prim_group_change(struct samldb_ctx *ac)
994 {
995         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
996         const char * attrs[] = { "primaryGroupID", "memberOf", NULL };
997         struct ldb_result *res;
998         struct ldb_message_element *el;
999         struct ldb_message *msg;
1000         uint32_t rid;
1001         struct dom_sid *sid;
1002         struct ldb_dn *prev_prim_group_dn, *new_prim_group_dn;
1003         int ret;
1004
1005         /* Fetch informations from the existing object */
1006
1007         ret = ldb_search(ldb, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1008                          NULL);
1009         if (ret != LDB_SUCCESS) {
1010                 return ret;
1011         }
1012
1013         /* Finds out the DN of the old primary group */
1014
1015         rid = ldb_msg_find_attr_as_uint(res->msgs[0], "primaryGroupID", (uint32_t) -1);
1016         if (rid == (uint32_t) -1) {
1017                 /* User objects do always have a mandatory "primaryGroupID"
1018                  * attribute. If this doesn't exist then the object is of the
1019                  * wrong type. This is the exact Windows error code */
1020                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1021         }
1022
1023         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1024         if (sid == NULL) {
1025                 return ldb_operr(ldb);
1026         }
1027
1028         prev_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1029                                              ldap_encode_ndr_dom_sid(ac, sid));
1030         if (prev_prim_group_dn == NULL) {
1031                 return ldb_operr(ldb);
1032         }
1033
1034         /* Finds out the DN of the new primary group */
1035
1036         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1037         if (rid == (uint32_t) -1) {
1038                 /* we aren't affected of any primary group change */
1039                 return LDB_SUCCESS;
1040         }
1041
1042         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1043         if (sid == NULL) {
1044                 return ldb_operr(ldb);
1045         }
1046
1047         new_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1048                                             ldap_encode_ndr_dom_sid(ac, sid));
1049         if (new_prim_group_dn == NULL) {
1050                 /* Here we know if the specified new primary group candidate is
1051                  * valid or not. */
1052                 return LDB_ERR_UNWILLING_TO_PERFORM;
1053         }
1054
1055         /* Only update the "member" attributes when we really do have a change */
1056         if (ldb_dn_compare(new_prim_group_dn, prev_prim_group_dn) != 0) {
1057                 /* We need to be already a normal member of the new primary
1058                  * group in order to be successful. */
1059                 el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1060                                           ldb_dn_get_linearized(new_prim_group_dn));
1061                 if (el == NULL) {
1062                         return LDB_ERR_UNWILLING_TO_PERFORM;
1063                 }
1064
1065                 /* Remove the "member" attribute on the new primary group */
1066                 msg = talloc_zero(ac, struct ldb_message);
1067                 msg->dn = new_prim_group_dn;
1068
1069                 ret = samdb_msg_add_delval(ldb, msg, msg, "member",
1070                                            ldb_dn_get_linearized(ac->msg->dn));
1071                 if (ret != LDB_SUCCESS) {
1072                         return ret;
1073                 }
1074
1075                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1076                 if (ret != LDB_SUCCESS) {
1077                         return ret;
1078                 }
1079
1080                 /* Add a "member" attribute for the previous primary group */
1081                 msg = talloc_zero(ac, struct ldb_message);
1082                 msg->dn = prev_prim_group_dn;
1083
1084                 ret = samdb_msg_add_addval(ldb, msg, msg, "member",
1085                                            ldb_dn_get_linearized(ac->msg->dn));
1086                 if (ret != LDB_SUCCESS) {
1087                         return ret;
1088                 }
1089
1090                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1091                 if (ret != LDB_SUCCESS) {
1092                         return ret;
1093                 }
1094         }
1095
1096         return LDB_SUCCESS;
1097 }
1098
1099 static int samldb_prim_group_trigger(struct samldb_ctx *ac)
1100 {
1101         int ret;
1102
1103         if (ac->req->operation == LDB_ADD) {
1104                 ret = samldb_prim_group_set(ac);
1105         } else {
1106                 ret = samldb_prim_group_change(ac);
1107         }
1108
1109         return ret;
1110 }
1111
1112 static int samldb_member_check(struct samldb_ctx *ac)
1113 {
1114         struct ldb_context *ldb;
1115         struct ldb_message_element *el;
1116         struct ldb_dn *member_dn, *group_dn;
1117         uint32_t prim_group_rid;
1118         struct dom_sid *sid;
1119         unsigned int i;
1120
1121         ldb = ldb_module_get_ctx(ac->module);
1122
1123         el = ldb_msg_find_element(ac->msg, "member");
1124         if (el == NULL) {
1125                 /* we aren't affected */
1126                 return LDB_SUCCESS;
1127         }
1128
1129         for (i = 0; i < el->num_values; i++) {
1130                 /* Denies to add "member"s to groups which are primary ones
1131                  * for them */
1132                 member_dn = ldb_dn_from_ldb_val(ac, ldb, &el->values[i]);
1133                 if (!ldb_dn_validate(member_dn)) {
1134                         return ldb_operr(ldb);
1135                 }
1136
1137                 prim_group_rid = samdb_search_uint(ldb, ac, (uint32_t) -1,
1138                                                    member_dn, "primaryGroupID",
1139                                                    NULL);
1140                 if (prim_group_rid == (uint32_t) -1) {
1141                         /* the member hasn't to be a user account -> therefore
1142                          * no check needed in this case. */
1143                         continue;
1144                 }
1145
1146                 sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
1147                                       prim_group_rid);
1148                 if (sid == NULL) {
1149                         return ldb_operr(ldb);
1150                 }
1151
1152                 group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1153                                            ldap_encode_ndr_dom_sid(ac, sid));
1154                 if (group_dn == NULL) {
1155                         return ldb_operr(ldb);
1156                 }
1157
1158                 if (ldb_dn_compare(group_dn, ac->msg->dn) == 0) {
1159                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
1160                 }
1161         }
1162
1163         return LDB_SUCCESS;
1164 }
1165
1166
1167 /* add */
1168 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
1169 {
1170         struct ldb_context *ldb;
1171         struct samldb_ctx *ac;
1172         int ret;
1173
1174         ldb = ldb_module_get_ctx(module);
1175         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
1176
1177         /* do not manipulate our control entries */
1178         if (ldb_dn_is_special(req->op.add.message->dn)) {
1179                 return ldb_next_request(module, req);
1180         }
1181
1182         ac = samldb_ctx_init(module, req);
1183         if (ac == NULL) {
1184                 return ldb_operr(ldb);
1185         }
1186
1187         /* build the new msg */
1188         ac->msg = ldb_msg_copy_shallow(ac, req->op.add.message);
1189         if (ac->msg == NULL) {
1190                 talloc_free(ac);
1191                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1192                           "samldb_add: ldb_msg_copy_shallow failed!\n");
1193                 return ldb_operr(ldb);
1194         }
1195
1196         if (samdb_find_attribute(ldb, ac->msg,
1197                                  "objectclass", "user") != NULL) {
1198                 ac->type = "user";
1199
1200                 ret = samldb_prim_group_trigger(ac);
1201                 if (ret != LDB_SUCCESS) {
1202                         return ret;
1203                 }
1204
1205                 ret = samldb_objectclass_trigger(ac);
1206                 if (ret != LDB_SUCCESS) {
1207                         return ret;
1208                 }
1209
1210                 return samldb_fill_object(ac);
1211         }
1212
1213         if (samdb_find_attribute(ldb, ac->msg,
1214                                  "objectclass", "group") != NULL) {
1215                 ac->type = "group";
1216
1217                 ret = samldb_objectclass_trigger(ac);
1218                 if (ret != LDB_SUCCESS) {
1219                         return ret;
1220                 }
1221
1222                 return samldb_fill_object(ac);
1223         }
1224
1225         /* perhaps a foreignSecurityPrincipal? */
1226         if (samdb_find_attribute(ldb, ac->msg,
1227                                  "objectclass",
1228                                  "foreignSecurityPrincipal") != NULL) {
1229                 return samldb_fill_foreignSecurityPrincipal_object(ac);
1230         }
1231
1232         if (samdb_find_attribute(ldb, ac->msg,
1233                                  "objectclass", "classSchema") != NULL) {
1234                 ret = samldb_schema_info_update(ac);
1235                 if (ret != LDB_SUCCESS) {
1236                         talloc_free(ac);
1237                         return ret;
1238                 }
1239
1240                 ac->type = "classSchema";
1241                 return samldb_fill_object(ac);
1242         }
1243
1244         if (samdb_find_attribute(ldb, ac->msg,
1245                                  "objectclass", "attributeSchema") != NULL) {
1246                 ret = samldb_schema_info_update(ac);
1247                 if (ret != LDB_SUCCESS) {
1248                         talloc_free(ac);
1249                         return ret;
1250                 }
1251
1252                 ac->type = "attributeSchema";
1253                 return samldb_fill_object(ac);
1254         }
1255
1256         talloc_free(ac);
1257
1258         /* nothing matched, go on */
1259         return ldb_next_request(module, req);
1260 }
1261
1262 /* modify */
1263 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
1264 {
1265         struct ldb_context *ldb;
1266         struct samldb_ctx *ac;
1267         struct ldb_message_element *el, *el2;
1268         bool modified = false;
1269         int ret;
1270         uint32_t account_type;
1271
1272         if (ldb_dn_is_special(req->op.mod.message->dn)) {
1273                 /* do not manipulate our control entries */
1274                 return ldb_next_request(module, req);
1275         }
1276
1277         ldb = ldb_module_get_ctx(module);
1278
1279         /* make sure that "sAMAccountType" is not specified */
1280         el = ldb_msg_find_element(req->op.mod.message, "sAMAccountType");
1281         if (el != NULL) {
1282                 ldb_set_errstring(ldb,
1283                         "samldb: sAMAccountType must not be specified!");
1284                 return LDB_ERR_UNWILLING_TO_PERFORM;
1285         }
1286         /* make sure that "isCriticalSystemObject" is not specified */
1287         el = ldb_msg_find_element(req->op.mod.message, "isCriticalSystemObject");
1288         if (el != NULL) {
1289                 if (ldb_request_get_control(req, LDB_CONTROL_RELAX_OID) == NULL) {
1290                         ldb_set_errstring(ldb,
1291                                 "samldb: isCriticalSystemObject must not be specified!");
1292                         return LDB_ERR_UNWILLING_TO_PERFORM;
1293                 }
1294         }
1295
1296         /* msDS-IntId is not allowed to be modified
1297          * except when modification comes from replication */
1298         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
1299                 if (!ldb_request_get_control(req,
1300                                              DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
1301                         return LDB_ERR_CONSTRAINT_VIOLATION;
1302                 }
1303         }
1304
1305         ac = samldb_ctx_init(module, req);
1306         if (ac == NULL) {
1307                 return ldb_operr(ldb);
1308         }
1309
1310         /* build the new msg */
1311         ac->msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
1312         if (ac->msg == NULL) {
1313                 talloc_free(ac);
1314                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1315                           "samldb_modify: ldb_msg_copy_shallow failed!\n");
1316                 return ldb_operr(ldb);
1317         }
1318
1319         el = ldb_msg_find_element(ac->msg, "groupType");
1320         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE)
1321             && el->num_values == 1) {
1322                 uint32_t group_type, old_group_type;
1323
1324                 modified = true;
1325
1326                 group_type = ldb_msg_find_attr_as_uint(ac->msg, "groupType", 0);
1327                 old_group_type = samdb_search_uint(ldb, ac, 0, ac->msg->dn,
1328                                                    "groupType", NULL);
1329                 if (old_group_type == 0) {
1330                         return ldb_operr(ldb);
1331                 }
1332
1333                 /* Group type switching isn't so easy as it seems: We can only
1334                  * change in this directions: global <-> universal <-> local
1335                  * On each step also the group type itself
1336                  * (security/distribution) is variable. */
1337
1338                 switch (group_type) {
1339                 case GTYPE_SECURITY_GLOBAL_GROUP:
1340                 case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
1341                         /* change to "universal" allowed */
1342                         if ((old_group_type == GTYPE_SECURITY_DOMAIN_LOCAL_GROUP) ||
1343                             (old_group_type == GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP)) {
1344                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1345                         }
1346                 break;
1347
1348                 case GTYPE_SECURITY_UNIVERSAL_GROUP:
1349                 case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
1350                         /* each change allowed */
1351                 break;
1352
1353                 case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
1354                 case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
1355                         /* change to "universal" allowed */
1356                         if ((old_group_type == GTYPE_SECURITY_GLOBAL_GROUP) ||
1357                             (old_group_type == GTYPE_DISTRIBUTION_GLOBAL_GROUP)) {
1358                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1359                         }
1360                 break;
1361
1362                 case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
1363                 default:
1364                         /* we don't allow this "groupType" values */
1365                         return LDB_ERR_UNWILLING_TO_PERFORM;
1366                 break;
1367                 }
1368
1369                 account_type =  ds_gtype2atype(group_type);
1370                 if (account_type == 0) {
1371                         ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1372                         return LDB_ERR_UNWILLING_TO_PERFORM;
1373                 }
1374                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1375                                          "sAMAccountType",
1376                                          account_type);
1377                 if (ret != LDB_SUCCESS) {
1378                         return ret;
1379                 }
1380                 el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
1381                 el2->flags = LDB_FLAG_MOD_REPLACE;
1382         }
1383         el = ldb_msg_find_element(ac->msg, "groupType");
1384         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1385                 return LDB_ERR_UNWILLING_TO_PERFORM;
1386         }
1387
1388         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
1389         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE)
1390             && el->num_values == 1) {
1391                 modified = true;
1392
1393                 ret = samldb_prim_group_change(ac);
1394                 if (ret != LDB_SUCCESS) {
1395                         return ret;
1396                 }
1397         }
1398         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
1399         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1400                 return LDB_ERR_UNWILLING_TO_PERFORM;
1401         }
1402
1403         el = ldb_msg_find_element(ac->msg, "userAccountControl");
1404         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE)
1405             && el->num_values == 1) {
1406                 uint32_t user_account_control;
1407
1408                 modified = true;
1409
1410                 user_account_control = ldb_msg_find_attr_as_uint(ac->msg,
1411                                                                  "userAccountControl",
1412                                                                  0);
1413
1414                 /* Temporary duplicate accounts aren't allowed */
1415                 if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
1416                         return LDB_ERR_OTHER;
1417                 }
1418
1419                 account_type = ds_uf2atype(user_account_control);
1420                 if (account_type == 0) {
1421                         ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1422                         return LDB_ERR_UNWILLING_TO_PERFORM;
1423                 }
1424                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1425                                          "sAMAccountType",
1426                                          account_type);
1427                 if (ret != LDB_SUCCESS) {
1428                         return ret;
1429                 }
1430                 el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
1431                 el2->flags = LDB_FLAG_MOD_REPLACE;
1432
1433                 if (user_account_control & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1434                         ret = samdb_msg_add_string(ldb, ac->msg, ac->msg,
1435                                                    "isCriticalSystemObject",
1436                                                    "TRUE");
1437                         if (ret != LDB_SUCCESS) {
1438                                 return ret;
1439                         }
1440                         el2 = ldb_msg_find_element(ac->msg,
1441                                                    "isCriticalSystemObject");
1442                         el2->flags = LDB_FLAG_MOD_REPLACE;
1443                 }
1444
1445                 if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
1446                         uint32_t rid = ds_uf2prim_group_rid(user_account_control);
1447
1448                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1449                                                  "primaryGroupID", rid);
1450                         if (ret != LDB_SUCCESS) {
1451                                 return ret;
1452                         }
1453                         el2 = ldb_msg_find_element(ac->msg,
1454                                                    "primaryGroupID");
1455                         el2->flags = LDB_FLAG_MOD_REPLACE;
1456                 }
1457         }
1458         el = ldb_msg_find_element(ac->msg, "userAccountControl");
1459         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1460                 return LDB_ERR_UNWILLING_TO_PERFORM;
1461         }
1462
1463         el = ldb_msg_find_element(ac->msg, "member");
1464         if (el && el->flags & (LDB_FLAG_MOD_ADD|LDB_FLAG_MOD_REPLACE)
1465             && el->num_values == 1) {
1466                 ret = samldb_member_check(ac);
1467                 if (ret != LDB_SUCCESS) {
1468                         return ret;
1469                 }
1470         }
1471
1472         if (modified) {
1473                 struct ldb_request *child_req;
1474
1475                 /* Now perform the real modifications as a child request */
1476                 ret = ldb_build_mod_req(&child_req, ldb, ac,
1477                                         ac->msg,
1478                                         req->controls,
1479                                         req, dsdb_next_callback,
1480                                         req);
1481                 LDB_REQ_SET_LOCATION(child_req);
1482                 if (ret != LDB_SUCCESS) {
1483                         return ret;
1484                 }
1485
1486                 return ldb_next_request(module, child_req);
1487         }
1488
1489         talloc_free(ac);
1490
1491         /* no change which interests us, go on */
1492         return ldb_next_request(module, req);
1493 }
1494
1495 /* delete */
1496
1497 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
1498 {
1499         struct ldb_context *ldb;
1500         struct dom_sid *sid;
1501         uint32_t rid;
1502         NTSTATUS status;
1503         int count;
1504
1505         ldb = ldb_module_get_ctx(ac->module);
1506
1507         /* Finds out the SID/RID of the SAM object */
1508         sid = samdb_search_dom_sid(ldb, ac, ac->req->op.del.dn, "objectSid",
1509                                    NULL);
1510         if (sid == NULL) {
1511                 /* No SID - it might not be a SAM object - therefore ok */
1512                 return LDB_SUCCESS;
1513         }
1514         status = dom_sid_split_rid(ac, sid, NULL, &rid);
1515         if (!NT_STATUS_IS_OK(status)) {
1516                 return ldb_operr(ldb);
1517         }
1518         if (rid == 0) {
1519                 /* Special object (security principal?) */
1520                 return LDB_SUCCESS;
1521         }
1522
1523         /* Deny delete requests from groups which are primary ones */
1524         count = samdb_search_count(ldb, NULL,
1525                                    "(&(primaryGroupID=%u)(objectClass=user))",
1526                                    rid);
1527         if (count < 0) {
1528                 return ldb_operr(ldb);
1529         }
1530         if (count > 0) {
1531                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1532         }
1533
1534         return LDB_SUCCESS;
1535 }
1536
1537 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
1538 {
1539         struct samldb_ctx *ac;
1540         int ret;
1541
1542         if (ldb_dn_is_special(req->op.del.dn)) {
1543                 /* do not manipulate our control entries */
1544                 return ldb_next_request(module, req);
1545         }
1546
1547         ac = samldb_ctx_init(module, req);
1548         if (ac == NULL) {
1549                 return ldb_operr(ldb_module_get_ctx(module));
1550         }
1551
1552         ret = samldb_prim_group_users_check(ac);
1553         if (ret != LDB_SUCCESS) {
1554                 return ret;
1555         }
1556
1557         talloc_free(ac);
1558
1559         return ldb_next_request(module, req);
1560 }
1561
1562 /* extended */
1563
1564 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
1565 {
1566         struct ldb_context *ldb = ldb_module_get_ctx(module);
1567         struct dsdb_fsmo_extended_op *exop;
1568         int ret;
1569
1570         exop = talloc_get_type(req->op.extended.data,
1571                                struct dsdb_fsmo_extended_op);
1572         if (!exop) {
1573                 ldb_debug(ldb, LDB_DEBUG_FATAL, "samldb_extended_allocate_rid_pool: invalid extended data\n");
1574                 return LDB_ERR_PROTOCOL_ERROR;
1575         }
1576
1577         ret = ridalloc_allocate_rid_pool_fsmo(module, exop);
1578         if (ret != LDB_SUCCESS) {
1579                 return ret;
1580         }
1581
1582         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1583 }
1584
1585 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
1586 {
1587         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
1588                 return samldb_extended_allocate_rid_pool(module, req);
1589         }
1590
1591         return ldb_next_request(module, req);
1592 }
1593
1594
1595 _PUBLIC_ const struct ldb_module_ops ldb_samldb_module_ops = {
1596         .name          = "samldb",
1597         .add           = samldb_add,
1598         .modify        = samldb_modify,
1599         .del           = samldb_delete,
1600         .extended      = samldb_extended
1601 };
1602