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