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