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