8db93b2a8a278a53e87a3e1ae5c146f65393f25a
[abartlet/samba.git/.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         WERROR werr;
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         werr = dsdb_module_schema_info_update(ac->module, schema, DSDB_FLAG_NEXT_MODULE);
733         if (!W_ERROR_IS_OK(werr)) {
734                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
735                               "samldb_schema_info_update: "
736                               "dsdb_module_schema_info_update failed with %s",
737                               win_errstr(werr));
738                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
739                 return ldb_operr(ldb);
740         }
741
742         return LDB_SUCCESS;
743 }
744
745 /*
746  * "Objectclass" trigger (MS-SAMR 3.1.1.8.1)
747  *
748  * Has to be invoked on "add" and "modify" operations on "user", "computer" and
749  * "group" objects.
750  * ac->msg contains the "add"/"modify" message
751  * ac->type contains the object type (main objectclass)
752  */
753 static int samldb_objectclass_trigger(struct samldb_ctx *ac)
754 {
755         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
756         struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb,
757                                          "loadparm"), struct loadparm_context);
758         struct ldb_message_element *el, *el2;
759         enum sid_generator sid_generator;
760         struct dom_sid *sid;
761         const char *tempstr;
762         int ret;
763
764         /* make sure that "sAMAccountType" is not specified */
765         el = ldb_msg_find_element(ac->msg, "sAMAccountType");
766         if (el != NULL) {
767                 ldb_set_errstring(ldb,
768                         "samldb: sAMAccountType must not be specified!");
769                 return LDB_ERR_UNWILLING_TO_PERFORM;
770         }
771
772         /* Step 1: objectSid assignment */
773
774         /* Don't allow the objectSid to be changed. But beside the RELAX
775          * control we have also to guarantee that it can always be set with
776          * SYSTEM permissions. This is needed for the "samba3sam" backend. */
777         sid = samdb_result_dom_sid(ac, ac->msg, "objectSid");
778         if ((sid != NULL) && (!dsdb_module_am_system(ac->module)) &&
779             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
780                 ldb_asprintf_errstring(ldb, "No SID may be specified in user/group modifications for %s",
781                                        ldb_dn_get_linearized(ac->msg->dn));
782                 return LDB_ERR_UNWILLING_TO_PERFORM;
783         }
784
785         /* but generate a new SID when we do have an add operations */
786         if ((sid == NULL) && (ac->req->operation == LDB_ADD)) {
787                 sid_generator = lpcfg_sid_generator(lp_ctx);
788                 if (sid_generator == SID_GENERATOR_INTERNAL) {
789                         ret = samldb_add_step(ac, samldb_allocate_sid);
790                         if (ret != LDB_SUCCESS) return ret;
791                 }
792         }
793
794         if (strcmp(ac->type, "user") == 0) {
795                 /* Step 1.2: Default values */
796                 tempstr = talloc_asprintf(ac->msg, "%d", UF_NORMAL_ACCOUNT);
797                 if (tempstr == NULL) return ldb_operr(ldb);
798                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
799                         "userAccountControl", tempstr);
800                 if (ret != LDB_SUCCESS) return ret;
801                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
802                         "badPwdCount", "0");
803                 if (ret != LDB_SUCCESS) return ret;
804                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
805                         "codePage", "0");
806                 if (ret != LDB_SUCCESS) return ret;
807                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
808                         "countryCode", "0");
809                 if (ret != LDB_SUCCESS) return ret;
810                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
811                         "badPasswordTime", "0");
812                 if (ret != LDB_SUCCESS) return ret;
813                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
814                         "lastLogoff", "0");
815                 if (ret != LDB_SUCCESS) return ret;
816                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
817                         "lastLogon", "0");
818                 if (ret != LDB_SUCCESS) return ret;
819                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
820                         "pwdLastSet", "0");
821                 if (ret != LDB_SUCCESS) return ret;
822                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
823                         "accountExpires", "9223372036854775807");
824                 if (ret != LDB_SUCCESS) return ret;
825                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
826                         "logonCount", "0");
827                 if (ret != LDB_SUCCESS) return ret;
828
829                 el = ldb_msg_find_element(ac->msg, "userAccountControl");
830                 if (el != NULL) {
831                         uint32_t user_account_control, account_type;
832
833                         /* Step 1.3: "userAccountControl" -> "sAMAccountType" mapping */
834                         user_account_control = ldb_msg_find_attr_as_uint(ac->msg,
835                                                                          "userAccountControl",
836                                                                          0);
837
838                         /* Temporary duplicate accounts aren't allowed */
839                         if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
840                                 return LDB_ERR_OTHER;
841                         }
842
843                         account_type = ds_uf2atype(user_account_control);
844                         if (account_type == 0) {
845                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
846                                 return LDB_ERR_UNWILLING_TO_PERFORM;
847                         }
848                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
849                                                  "sAMAccountType",
850                                                  account_type);
851                         if (ret != LDB_SUCCESS) {
852                                 return ret;
853                         }
854                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
855                         el2->flags = LDB_FLAG_MOD_REPLACE;
856
857                         if (user_account_control &
858                             (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
859                                 ret = samdb_msg_set_string(ldb, ac->msg, ac->msg,
860                                                            "isCriticalSystemObject",
861                                                            "TRUE");
862                                 if (ret != LDB_SUCCESS) {
863                                         return ret;
864                                 }
865                                 el2 = ldb_msg_find_element(ac->msg,
866                                                            "isCriticalSystemObject");
867                                 el2->flags = LDB_FLAG_MOD_REPLACE;
868                         }
869
870                         /* Step 1.4: "userAccountControl" -> "primaryGroupID" mapping */
871                         if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
872                                 uint32_t rid = ds_uf2prim_group_rid(user_account_control);
873                                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
874                                                          "primaryGroupID", rid);
875                                 if (ret != LDB_SUCCESS) {
876                                         return ret;
877                                 }
878                                 el2 = ldb_msg_find_element(ac->msg,
879                                                            "primaryGroupID");
880                                 el2->flags = LDB_FLAG_MOD_REPLACE;
881                         }
882
883                         /* Step 1.5: Add additional flags when needed */
884                         if ((user_account_control & UF_NORMAL_ACCOUNT) &&
885                             (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) == NULL)) {
886                                 user_account_control |= UF_ACCOUNTDISABLE;
887                                 user_account_control |= UF_PASSWD_NOTREQD;
888
889                                 ret = samdb_msg_set_uint(ldb, ac->msg, ac->msg,
890                                                          "userAccountControl",
891                                                          user_account_control);
892                                 if (ret != LDB_SUCCESS) {
893                                         return ret;
894                                 }
895                         }
896                 }
897
898         } else if (strcmp(ac->type, "group") == 0) {
899                 /* Step 2.2: Default values */
900                 tempstr = talloc_asprintf(ac->msg, "%d",
901                                           GTYPE_SECURITY_GLOBAL_GROUP);
902                 if (tempstr == NULL) return ldb_operr(ldb);
903                 ret = samdb_find_or_add_attribute(ldb, ac->msg,
904                         "groupType", tempstr);
905                 if (ret != LDB_SUCCESS) return ret;
906
907                 /* Step 2.3: "groupType" -> "sAMAccountType" */
908                 el = ldb_msg_find_element(ac->msg, "groupType");
909                 if (el != NULL) {
910                         uint32_t group_type, account_type;
911
912                         group_type = ldb_msg_find_attr_as_uint(ac->msg,
913                                                                "groupType", 0);
914
915                         /* The creation of builtin groups requires the
916                          * RELAX control */
917                         if (group_type == GTYPE_SECURITY_BUILTIN_LOCAL_GROUP) {
918                                 if (ldb_request_get_control(ac->req,
919                                                             LDB_CONTROL_RELAX_OID) == NULL) {
920                                         return LDB_ERR_UNWILLING_TO_PERFORM;
921                                 }
922                         }
923
924                         account_type = ds_gtype2atype(group_type);
925                         if (account_type == 0) {
926                                 ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
927                                 return LDB_ERR_UNWILLING_TO_PERFORM;
928                         }
929                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
930                                                  "sAMAccountType",
931                                                  account_type);
932                         if (ret != LDB_SUCCESS) {
933                                 return ret;
934                         }
935                         el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
936                         el2->flags = LDB_FLAG_MOD_REPLACE;
937                 }
938         }
939
940         return LDB_SUCCESS;
941 }
942
943 /*
944  * "Primary group ID" trigger (MS-SAMR 3.1.1.8.2)
945  *
946  * Has to be invoked on "add" and "modify" operations on "user" and "computer"
947  * objects.
948  * ac->msg contains the "add"/"modify" message
949  */
950
951 static int samldb_prim_group_set(struct samldb_ctx *ac)
952 {
953         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
954         struct ldb_dn *prim_group_dn;
955         uint32_t rid;
956         struct dom_sid *sid;
957
958         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
959         if (rid == (uint32_t) -1) {
960                 /* we aren't affected of any primary group set */
961                 return LDB_SUCCESS;
962
963         } else if (!ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
964                 ldb_set_errstring(ldb,
965                                   "The primary group isn't settable on add operations!");
966                 return LDB_ERR_UNWILLING_TO_PERFORM;
967         }
968
969         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
970         if (sid == NULL) {
971                 return ldb_operr(ldb);
972         }
973
974         prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
975                                         ldap_encode_ndr_dom_sid(ac, sid));
976         if (prim_group_dn == NULL) {
977                 ldb_asprintf_errstring(ldb,
978                                        "Failed to find primary group with RID %u!",
979                                        rid);
980                 return LDB_ERR_UNWILLING_TO_PERFORM;
981         }
982
983         return LDB_SUCCESS;
984 }
985
986 static int samldb_prim_group_change(struct samldb_ctx *ac)
987 {
988         struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
989         const char * attrs[] = { "primaryGroupID", "memberOf", NULL };
990         struct ldb_result *res;
991         struct ldb_message_element *el;
992         struct ldb_message *msg;
993         uint32_t rid;
994         struct dom_sid *sid;
995         struct ldb_dn *prev_prim_group_dn, *new_prim_group_dn;
996         int ret;
997
998         /* Fetch informations from the existing object */
999
1000         ret = ldb_search(ldb, ac, &res, ac->msg->dn, LDB_SCOPE_BASE, attrs,
1001                          NULL);
1002         if (ret != LDB_SUCCESS) {
1003                 return ret;
1004         }
1005
1006         /* Finds out the DN of the old primary group */
1007
1008         rid = ldb_msg_find_attr_as_uint(res->msgs[0], "primaryGroupID", (uint32_t) -1);
1009         if (rid == (uint32_t) -1) {
1010                 /* User objects do always have a mandatory "primaryGroupID"
1011                  * attribute. If this doesn't exist then the object is of the
1012                  * wrong type. This is the exact Windows error code */
1013                 return LDB_ERR_OBJECT_CLASS_VIOLATION;
1014         }
1015
1016         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1017         if (sid == NULL) {
1018                 return ldb_operr(ldb);
1019         }
1020
1021         prev_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1022                                              ldap_encode_ndr_dom_sid(ac, sid));
1023         if (prev_prim_group_dn == NULL) {
1024                 return ldb_operr(ldb);
1025         }
1026
1027         /* Finds out the DN of the new primary group */
1028
1029         rid = ldb_msg_find_attr_as_uint(ac->msg, "primaryGroupID", (uint32_t) -1);
1030         if (rid == (uint32_t) -1) {
1031                 /* we aren't affected of any primary group change */
1032                 return LDB_SUCCESS;
1033         }
1034
1035         sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb), rid);
1036         if (sid == NULL) {
1037                 return ldb_operr(ldb);
1038         }
1039
1040         new_prim_group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1041                                             ldap_encode_ndr_dom_sid(ac, sid));
1042         if (new_prim_group_dn == NULL) {
1043                 /* Here we know if the specified new primary group candidate is
1044                  * valid or not. */
1045                 return LDB_ERR_UNWILLING_TO_PERFORM;
1046         }
1047
1048         /* Only update the "member" attributes when we really do have a change */
1049         if (ldb_dn_compare(new_prim_group_dn, prev_prim_group_dn) != 0) {
1050                 /* We need to be already a normal member of the new primary
1051                  * group in order to be successful. */
1052                 el = samdb_find_attribute(ldb, res->msgs[0], "memberOf",
1053                                           ldb_dn_get_linearized(new_prim_group_dn));
1054                 if (el == NULL) {
1055                         return LDB_ERR_UNWILLING_TO_PERFORM;
1056                 }
1057
1058                 /* Remove the "member" attribute on the new primary group */
1059                 msg = talloc_zero(ac, struct ldb_message);
1060                 msg->dn = new_prim_group_dn;
1061
1062                 ret = samdb_msg_add_delval(ldb, ac, msg, "member",
1063                                            ldb_dn_get_linearized(ac->msg->dn));
1064                 if (ret != LDB_SUCCESS) {
1065                         return ret;
1066                 }
1067
1068                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1069                 if (ret != LDB_SUCCESS) {
1070                         return ret;
1071                 }
1072
1073                 /* Add a "member" attribute for the previous primary group */
1074                 msg = talloc_zero(ac, struct ldb_message);
1075                 msg->dn = prev_prim_group_dn;
1076
1077                 ret = samdb_msg_add_addval(ldb, ac, msg, "member",
1078                                            ldb_dn_get_linearized(ac->msg->dn));
1079                 if (ret != LDB_SUCCESS) {
1080                         return ret;
1081                 }
1082
1083                 ret = dsdb_module_modify(ac->module, msg, DSDB_FLAG_NEXT_MODULE);
1084                 if (ret != LDB_SUCCESS) {
1085                         return ret;
1086                 }
1087         }
1088
1089         return LDB_SUCCESS;
1090 }
1091
1092 static int samldb_prim_group_trigger(struct samldb_ctx *ac)
1093 {
1094         int ret;
1095
1096         if (ac->req->operation == LDB_ADD) {
1097                 ret = samldb_prim_group_set(ac);
1098         } else {
1099                 ret = samldb_prim_group_change(ac);
1100         }
1101
1102         return ret;
1103 }
1104
1105 static int samldb_member_check(struct samldb_ctx *ac)
1106 {
1107         struct ldb_context *ldb;
1108         struct ldb_message_element *el;
1109         struct ldb_dn *member_dn, *group_dn;
1110         uint32_t prim_group_rid;
1111         struct dom_sid *sid;
1112         unsigned int i;
1113
1114         ldb = ldb_module_get_ctx(ac->module);
1115
1116         el = ldb_msg_find_element(ac->msg, "member");
1117         if (el == NULL) {
1118                 /* we aren't affected */
1119                 return LDB_SUCCESS;
1120         }
1121
1122         for (i = 0; i < el->num_values; i++) {
1123                 /* Denies to add "member"s to groups which are primary ones
1124                  * for them */
1125                 member_dn = ldb_dn_from_ldb_val(ac, ldb, &el->values[i]);
1126                 if (!ldb_dn_validate(member_dn)) {
1127                         return ldb_operr(ldb);
1128                 }
1129
1130                 prim_group_rid = samdb_search_uint(ldb, ac, (uint32_t) -1,
1131                                                    member_dn, "primaryGroupID",
1132                                                    NULL);
1133                 if (prim_group_rid == (uint32_t) -1) {
1134                         /* the member hasn't to be a user account -> therefore
1135                          * no check needed in this case. */
1136                         continue;
1137                 }
1138
1139                 sid = dom_sid_add_rid(ac, samdb_domain_sid(ldb),
1140                                       prim_group_rid);
1141                 if (sid == NULL) {
1142                         return ldb_operr(ldb);
1143                 }
1144
1145                 group_dn = samdb_search_dn(ldb, ac, NULL, "(objectSid=%s)",
1146                                            ldap_encode_ndr_dom_sid(ac, sid));
1147                 if (group_dn == NULL) {
1148                         return ldb_operr(ldb);
1149                 }
1150
1151                 if (ldb_dn_compare(group_dn, ac->msg->dn) == 0) {
1152                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
1153                 }
1154         }
1155
1156         return LDB_SUCCESS;
1157 }
1158
1159
1160 /* add */
1161 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
1162 {
1163         struct ldb_context *ldb;
1164         struct samldb_ctx *ac;
1165         int ret;
1166
1167         ldb = ldb_module_get_ctx(module);
1168         ldb_debug(ldb, LDB_DEBUG_TRACE, "samldb_add\n");
1169
1170         /* do not manipulate our control entries */
1171         if (ldb_dn_is_special(req->op.add.message->dn)) {
1172                 return ldb_next_request(module, req);
1173         }
1174
1175         ac = samldb_ctx_init(module, req);
1176         if (ac == NULL) {
1177                 return ldb_operr(ldb);
1178         }
1179
1180         /* build the new msg */
1181         ac->msg = ldb_msg_copy_shallow(ac, req->op.add.message);
1182         if (ac->msg == NULL) {
1183                 talloc_free(ac);
1184                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1185                           "samldb_add: ldb_msg_copy_shallow failed!\n");
1186                 return ldb_operr(ldb);
1187         }
1188
1189         if (samdb_find_attribute(ldb, ac->msg,
1190                                  "objectclass", "user") != NULL) {
1191                 ac->type = "user";
1192
1193                 ret = samldb_prim_group_trigger(ac);
1194                 if (ret != LDB_SUCCESS) {
1195                         return ret;
1196                 }
1197
1198                 ret = samldb_objectclass_trigger(ac);
1199                 if (ret != LDB_SUCCESS) {
1200                         return ret;
1201                 }
1202
1203                 return samldb_fill_object(ac);
1204         }
1205
1206         if (samdb_find_attribute(ldb, ac->msg,
1207                                  "objectclass", "group") != NULL) {
1208                 ac->type = "group";
1209
1210                 ret = samldb_objectclass_trigger(ac);
1211                 if (ret != LDB_SUCCESS) {
1212                         return ret;
1213                 }
1214
1215                 return samldb_fill_object(ac);
1216         }
1217
1218         /* perhaps a foreignSecurityPrincipal? */
1219         if (samdb_find_attribute(ldb, ac->msg,
1220                                  "objectclass",
1221                                  "foreignSecurityPrincipal") != NULL) {
1222                 return samldb_fill_foreignSecurityPrincipal_object(ac);
1223         }
1224
1225         if (samdb_find_attribute(ldb, ac->msg,
1226                                  "objectclass", "classSchema") != NULL) {
1227                 ret = samldb_schema_info_update(ac);
1228                 if (ret != LDB_SUCCESS) {
1229                         talloc_free(ac);
1230                         return ret;
1231                 }
1232
1233                 ac->type = "classSchema";
1234                 return samldb_fill_object(ac);
1235         }
1236
1237         if (samdb_find_attribute(ldb, ac->msg,
1238                                  "objectclass", "attributeSchema") != NULL) {
1239                 ret = samldb_schema_info_update(ac);
1240                 if (ret != LDB_SUCCESS) {
1241                         talloc_free(ac);
1242                         return ret;
1243                 }
1244
1245                 ac->type = "attributeSchema";
1246                 return samldb_fill_object(ac);
1247         }
1248
1249         talloc_free(ac);
1250
1251         /* nothing matched, go on */
1252         return ldb_next_request(module, req);
1253 }
1254
1255 /* modify */
1256 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
1257 {
1258         struct ldb_context *ldb;
1259         struct samldb_ctx *ac;
1260         struct ldb_message_element *el, *el2;
1261         bool modified = false;
1262         int ret;
1263         uint32_t account_type;
1264
1265         if (ldb_dn_is_special(req->op.mod.message->dn)) {
1266                 /* do not manipulate our control entries */
1267                 return ldb_next_request(module, req);
1268         }
1269
1270         ldb = ldb_module_get_ctx(module);
1271
1272         /* make sure that "sAMAccountType" is not specified */
1273         el = ldb_msg_find_element(req->op.mod.message, "sAMAccountType");
1274         if (el != NULL) {
1275                 ldb_set_errstring(ldb,
1276                         "samldb: sAMAccountType must not be specified!");
1277                 return LDB_ERR_UNWILLING_TO_PERFORM;
1278         }
1279         /* make sure that "isCriticalSystemObject" is not specified */
1280         el = ldb_msg_find_element(req->op.mod.message, "isCriticalSystemObject");
1281         if (el != NULL) {
1282                 if (ldb_request_get_control(req, LDB_CONTROL_RELAX_OID) == NULL) {
1283                         ldb_set_errstring(ldb,
1284                                 "samldb: isCriticalSystemObject must not be specified!");
1285                         return LDB_ERR_UNWILLING_TO_PERFORM;
1286                 }
1287         }
1288
1289         /* msDS-IntId is not allowed to be modified
1290          * except when modification comes from replication */
1291         if (ldb_msg_find_element(req->op.mod.message, "msDS-IntId")) {
1292                 if (!ldb_request_get_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
1293                         return LDB_ERR_CONSTRAINT_VIOLATION;
1294                 }
1295         }
1296
1297         ac = samldb_ctx_init(module, req);
1298         if (ac == NULL) {
1299                 return ldb_operr(ldb);
1300         }
1301
1302         /* build the new msg */
1303         ac->msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
1304         if (ac->msg == NULL) {
1305                 talloc_free(ac);
1306                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1307                           "samldb_modify: ldb_msg_copy_shallow failed!\n");
1308                 return ldb_operr(ldb);
1309         }
1310
1311         el = ldb_msg_find_element(ac->msg, "groupType");
1312         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1313                 uint32_t group_type, old_group_type;
1314
1315                 modified = true;
1316
1317                 group_type = ldb_msg_find_attr_as_uint(ac->msg, "groupType", 0);
1318                 old_group_type = samdb_search_uint(ldb, ac, 0, ac->msg->dn,
1319                                                    "groupType", NULL);
1320                 if (old_group_type == 0) {
1321                         return ldb_operr(ldb);
1322                 }
1323
1324                 /* Group type switching isn't so easy as it seems: We can only
1325                  * change in this directions: global <-> universal <-> local
1326                  * On each step also the group type itself
1327                  * (security/distribution) is variable. */
1328
1329                 switch (group_type) {
1330                 case GTYPE_SECURITY_GLOBAL_GROUP:
1331                 case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
1332                         /* change to "universal" allowed */
1333                         if ((old_group_type == GTYPE_SECURITY_DOMAIN_LOCAL_GROUP) ||
1334                             (old_group_type == GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP)) {
1335                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1336                         }
1337                 break;
1338
1339                 case GTYPE_SECURITY_UNIVERSAL_GROUP:
1340                 case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
1341                         /* each change allowed */
1342                 break;
1343
1344                 case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
1345                 case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
1346                         /* change to "universal" allowed */
1347                         if ((old_group_type == GTYPE_SECURITY_GLOBAL_GROUP) ||
1348                             (old_group_type == GTYPE_DISTRIBUTION_GLOBAL_GROUP)) {
1349                                 return LDB_ERR_UNWILLING_TO_PERFORM;
1350                         }
1351                 break;
1352
1353                 case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
1354                 default:
1355                         /* we don't allow this "groupType" values */
1356                         return LDB_ERR_UNWILLING_TO_PERFORM;
1357                 break;
1358                 }
1359
1360                 account_type =  ds_gtype2atype(group_type);
1361                 if (account_type == 0) {
1362                         ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1363                         return LDB_ERR_UNWILLING_TO_PERFORM;
1364                 }
1365                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1366                                          "sAMAccountType",
1367                                          account_type);
1368                 if (ret != LDB_SUCCESS) {
1369                         return ret;
1370                 }
1371                 el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
1372                 el2->flags = LDB_FLAG_MOD_REPLACE;
1373         }
1374         el = ldb_msg_find_element(ac->msg, "groupType");
1375         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1376                 return LDB_ERR_UNWILLING_TO_PERFORM;
1377         }
1378
1379         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
1380         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1381                 modified = true;
1382
1383                 ret = samldb_prim_group_change(ac);
1384                 if (ret != LDB_SUCCESS) {
1385                         return ret;
1386                 }
1387         }
1388         el = ldb_msg_find_element(ac->msg, "primaryGroupID");
1389         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1390                 return LDB_ERR_UNWILLING_TO_PERFORM;
1391         }
1392
1393         el = ldb_msg_find_element(ac->msg, "userAccountControl");
1394         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1395                 uint32_t user_account_control;
1396
1397                 modified = true;
1398
1399                 user_account_control = ldb_msg_find_attr_as_uint(ac->msg,
1400                                                                  "userAccountControl",
1401                                                                  0);
1402
1403                 /* Temporary duplicate accounts aren't allowed */
1404                 if ((user_account_control & UF_TEMP_DUPLICATE_ACCOUNT) != 0) {
1405                         return LDB_ERR_OTHER;
1406                 }
1407
1408                 account_type = ds_uf2atype(user_account_control);
1409                 if (account_type == 0) {
1410                         ldb_set_errstring(ldb, "samldb: Unrecognized account type!");
1411                         return LDB_ERR_UNWILLING_TO_PERFORM;
1412                 }
1413                 ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1414                                          "sAMAccountType",
1415                                          account_type);
1416                 if (ret != LDB_SUCCESS) {
1417                         return ret;
1418                 }
1419                 el2 = ldb_msg_find_element(ac->msg, "sAMAccountType");
1420                 el2->flags = LDB_FLAG_MOD_REPLACE;
1421
1422                 if (user_account_control & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
1423                         ret = samdb_msg_add_string(ldb, ac->msg, ac->msg,
1424                                                    "isCriticalSystemObject",
1425                                                    "TRUE");
1426                         if (ret != LDB_SUCCESS) {
1427                                 return ret;
1428                         }
1429                         el2 = ldb_msg_find_element(ac->msg,
1430                                                    "isCriticalSystemObject");
1431                         el2->flags = LDB_FLAG_MOD_REPLACE;
1432                 }
1433
1434                 if (!ldb_msg_find_element(ac->msg, "primaryGroupID")) {
1435                         uint32_t rid = ds_uf2prim_group_rid(user_account_control);
1436
1437                         ret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,
1438                                                  "primaryGroupID", rid);
1439                         if (ret != LDB_SUCCESS) {
1440                                 return ret;
1441                         }
1442                         el2 = ldb_msg_find_element(ac->msg,
1443                                                    "primaryGroupID");
1444                         el2->flags = LDB_FLAG_MOD_REPLACE;
1445                 }
1446         }
1447         el = ldb_msg_find_element(ac->msg, "userAccountControl");
1448         if (el && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
1449                 return LDB_ERR_UNWILLING_TO_PERFORM;
1450         }
1451
1452         el = ldb_msg_find_element(ac->msg, "member");
1453         if (el && el->flags & (LDB_FLAG_MOD_ADD|LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
1454                 ret = samldb_member_check(ac);
1455                 if (ret != LDB_SUCCESS) {
1456                         return ret;
1457                 }
1458         }
1459
1460         if (modified) {
1461                 struct ldb_request *child_req;
1462
1463                 /* Now perform the real modifications as a child request */
1464                 ret = ldb_build_mod_req(&child_req, ldb, ac,
1465                                         ac->msg,
1466                                         req->controls,
1467                                         req, dsdb_next_callback,
1468                                         req);
1469                 LDB_REQ_SET_LOCATION(child_req);
1470                 if (ret != LDB_SUCCESS) {
1471                         return ret;
1472                 }
1473
1474                 return ldb_next_request(module, child_req);
1475         }
1476
1477         talloc_free(ac);
1478
1479         /* no change which interests us, go on */
1480         return ldb_next_request(module, req);
1481 }
1482
1483 /* delete */
1484
1485 static int samldb_prim_group_users_check(struct samldb_ctx *ac)
1486 {
1487         struct ldb_context *ldb;
1488         struct dom_sid *sid;
1489         uint32_t rid;
1490         NTSTATUS status;
1491         int count;
1492
1493         ldb = ldb_module_get_ctx(ac->module);
1494
1495         /* Finds out the SID/RID of the SAM object */
1496         sid = samdb_search_dom_sid(ldb, ac, ac->req->op.del.dn, "objectSid",
1497                                    NULL);
1498         if (sid == NULL) {
1499                 /* No SID - it might not be a SAM object - therefore ok */
1500                 return LDB_SUCCESS;
1501         }
1502         status = dom_sid_split_rid(ac, sid, NULL, &rid);
1503         if (!NT_STATUS_IS_OK(status)) {
1504                 return ldb_operr(ldb);
1505         }
1506         if (rid == 0) {
1507                 /* Special object (security principal?) */
1508                 return LDB_SUCCESS;
1509         }
1510
1511         /* Deny delete requests from groups which are primary ones */
1512         count = samdb_search_count(ldb, NULL,
1513                                    "(&(primaryGroupID=%u)(objectClass=user))",
1514                                    rid);
1515         if (count < 0) {
1516                 return ldb_operr(ldb);
1517         }
1518         if (count > 0) {
1519                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
1520         }
1521
1522         return LDB_SUCCESS;
1523 }
1524
1525 static int samldb_delete(struct ldb_module *module, struct ldb_request *req)
1526 {
1527         struct samldb_ctx *ac;
1528         int ret;
1529
1530         if (ldb_dn_is_special(req->op.del.dn)) {
1531                 /* do not manipulate our control entries */
1532                 return ldb_next_request(module, req);
1533         }
1534
1535         ac = samldb_ctx_init(module, req);
1536         if (ac == NULL) {
1537                 return ldb_operr(ldb_module_get_ctx(module));
1538         }
1539
1540         ret = samldb_prim_group_users_check(ac);
1541         if (ret != LDB_SUCCESS) {
1542                 return ret;
1543         }
1544
1545         talloc_free(ac);
1546
1547         return ldb_next_request(module, req);
1548 }
1549
1550 /* extended */
1551
1552 static int samldb_extended_allocate_rid_pool(struct ldb_module *module, struct ldb_request *req)
1553 {
1554         struct ldb_context *ldb = ldb_module_get_ctx(module);
1555         struct dsdb_fsmo_extended_op *exop;
1556         int ret;
1557
1558         exop = talloc_get_type(req->op.extended.data, struct dsdb_fsmo_extended_op);
1559         if (!exop) {
1560                 ldb_debug(ldb, LDB_DEBUG_FATAL, "samldb_extended_allocate_rid_pool: invalid extended data\n");
1561                 return LDB_ERR_PROTOCOL_ERROR;
1562         }
1563
1564         ret = ridalloc_allocate_rid_pool_fsmo(module, exop);
1565         if (ret != LDB_SUCCESS) {
1566                 return ret;
1567         }
1568
1569         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1570 }
1571
1572 static int samldb_extended(struct ldb_module *module, struct ldb_request *req)
1573 {
1574         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_ALLOCATE_RID_POOL) == 0) {
1575                 return samldb_extended_allocate_rid_pool(module, req);
1576         }
1577
1578         return ldb_next_request(module, req);
1579 }
1580
1581
1582 _PUBLIC_ const struct ldb_module_ops ldb_samldb_module_ops = {
1583         .name          = "samldb",
1584         .add           = samldb_add,
1585         .modify        = samldb_modify,
1586         .del           = samldb_delete,
1587         .extended      = samldb_extended
1588 };
1589