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