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