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