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