drs-fsmo: Improve handling of FSMO role takeover.
[kai/samba.git] / source4 / dsdb / samdb / ldb_modules / rootdse.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    rootDSE ldb module
5
6    Copyright (C) Andrew Tridgell 2005
7    Copyright (C) Simo Sorce 2005-2008
8    Copyright (C) Matthieu Patou <mat@matws.net> 2011
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include <ldb.h>
26 #include <ldb_module.h>
27 #include "system/time.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "version.h"
30 #include "dsdb/samdb/ldb_modules/util.h"
31 #include "libcli/security/security.h"
32 #include "librpc/ndr/libndr.h"
33 #include "auth/auth.h"
34 #include "param/param.h"
35 #include "lib/messaging/irpc.h"
36 #include "librpc/gen_ndr/ndr_irpc_c.h"
37
38 struct private_data {
39         unsigned int num_controls;
40         char **controls;
41         unsigned int num_partitions;
42         struct ldb_dn **partitions;
43         bool block_anonymous;
44 };
45
46 /*
47   return 1 if a specific attribute has been requested
48 */
49 static int do_attribute(const char * const *attrs, const char *name)
50 {
51         return attrs == NULL ||
52                 ldb_attr_in_list(attrs, name) ||
53                 ldb_attr_in_list(attrs, "*");
54 }
55
56 static int do_attribute_explicit(const char * const *attrs, const char *name)
57 {
58         return attrs != NULL && ldb_attr_in_list(attrs, name);
59 }
60
61
62 /*
63   expand a DN attribute to include extended DN information if requested
64  */
65 static int expand_dn_in_message(struct ldb_module *module, struct ldb_message *msg,
66                                 const char *attrname, struct ldb_control *edn_control,
67                                 struct ldb_request *req)
68 {
69         struct ldb_dn *dn, *dn2;
70         struct ldb_val *v;
71         int ret;
72         struct ldb_request *req2;
73         char *dn_string;
74         const char *no_attrs[] = { NULL };
75         struct ldb_result *res;
76         struct ldb_extended_dn_control *edn;
77         TALLOC_CTX *tmp_ctx = talloc_new(req);
78         struct ldb_context *ldb;
79         int edn_type = 0;
80         unsigned int i;
81         struct ldb_message_element *el;
82
83         ldb = ldb_module_get_ctx(module);
84
85         edn = talloc_get_type(edn_control->data, struct ldb_extended_dn_control);
86         if (edn) {
87                 edn_type = edn->type;
88         }
89
90         el = ldb_msg_find_element(msg, attrname);
91         if (!el || el->num_values == 0) {
92                 return LDB_SUCCESS;
93         }
94
95         for (i = 0; i < el->num_values; i++) {
96                 v = &el->values[i];
97                 if (v == NULL) {
98                         talloc_free(tmp_ctx);
99                         return LDB_SUCCESS;
100                 }
101
102                 dn_string = talloc_strndup(tmp_ctx, (const char *)v->data, v->length);
103                 if (dn_string == NULL) {
104                         talloc_free(tmp_ctx);
105                         return ldb_operr(ldb);
106                 }
107
108                 res = talloc_zero(tmp_ctx, struct ldb_result);
109                 if (res == NULL) {
110                         talloc_free(tmp_ctx);
111                         return ldb_operr(ldb);
112                 }
113
114                 dn = ldb_dn_new(tmp_ctx, ldb, dn_string);
115                 if (dn == NULL) {
116                         talloc_free(tmp_ctx);
117                         return ldb_operr(ldb);
118                 }
119
120                 ret = ldb_build_search_req(&req2, ldb, tmp_ctx,
121                                         dn,
122                                         LDB_SCOPE_BASE,
123                                         NULL,
124                                         no_attrs,
125                                         NULL,
126                                         res, ldb_search_default_callback,
127                                         req);
128                 LDB_REQ_SET_LOCATION(req2);
129                 if (ret != LDB_SUCCESS) {
130                         talloc_free(tmp_ctx);
131                         return ret;
132                 }
133
134
135                 ret = ldb_request_add_control(req2,
136                                         LDB_CONTROL_EXTENDED_DN_OID,
137                                         edn_control->critical, edn);
138                 if (ret != LDB_SUCCESS) {
139                         talloc_free(tmp_ctx);
140                         return ldb_error(ldb, ret, "Failed to add control");
141                 }
142
143                 ret = ldb_next_request(module, req2);
144                 if (ret == LDB_SUCCESS) {
145                         ret = ldb_wait(req2->handle, LDB_WAIT_ALL);
146                 }
147
148                 if (ret != LDB_SUCCESS) {
149                         talloc_free(tmp_ctx);
150                         return ret;
151                 }
152
153                 if (!res || res->count != 1) {
154                         talloc_free(tmp_ctx);
155                         return ldb_operr(ldb);
156                 }
157
158                 dn2 = res->msgs[0]->dn;
159
160                 v->data = (uint8_t *)ldb_dn_get_extended_linearized(msg->elements, dn2, edn_type);
161                 if (v->data == NULL) {
162                         talloc_free(tmp_ctx);
163                         return ldb_operr(ldb);
164                 }
165                 v->length = strlen((char *)v->data);
166         }
167
168         talloc_free(tmp_ctx);
169
170         return LDB_SUCCESS;
171 }
172
173 /*
174   see if we are master for a FSMO role
175  */
176 static int dsdb_module_we_are_master(struct ldb_module *module, struct ldb_dn *dn, bool *master,
177                                      struct ldb_request *parent)
178 {
179         const char *attrs[] = { "fSMORoleOwner", NULL };
180         TALLOC_CTX *tmp_ctx = talloc_new(parent);
181         struct ldb_result *res;
182         int ret;
183         struct ldb_dn *owner_dn;
184
185         ret = dsdb_module_search_dn(module, tmp_ctx, &res,
186                                     dn, attrs,
187                                     DSDB_FLAG_NEXT_MODULE |
188                                     DSDB_FLAG_AS_SYSTEM |
189                                     DSDB_SEARCH_SHOW_EXTENDED_DN,
190                                     parent);
191         if (ret != LDB_SUCCESS) {
192                 talloc_free(tmp_ctx);
193                 return ret;
194         }
195
196         owner_dn = ldb_msg_find_attr_as_dn(ldb_module_get_ctx(module),
197                                            tmp_ctx, res->msgs[0], "fSMORoleOwner");
198         if (!owner_dn) {
199                 *master = false;
200                 talloc_free(tmp_ctx);
201                 return LDB_SUCCESS;
202         }
203
204         ret = samdb_dn_is_our_ntdsa(ldb_module_get_ctx(module), dn, master);
205         if (ret != LDB_SUCCESS) {
206                 ldb_asprintf_errstring(ldb_module_get_ctx(module), "Failed to confirm if our ntdsDsa is %s: %s",
207                                        ldb_dn_get_linearized(owner_dn), ldb_errstring(ldb_module_get_ctx(module)));
208                 talloc_free(tmp_ctx);
209                 return ret;
210         }
211         
212         talloc_free(tmp_ctx);
213         return LDB_SUCCESS;
214 }
215
216 /*
217   add dynamically generated attributes to rootDSE result
218 */
219 static int rootdse_add_dynamic(struct ldb_module *module, struct ldb_message *msg,
220                                const char * const *attrs, struct ldb_request *req)
221 {
222         struct ldb_context *ldb;
223         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
224         char **server_sasl;
225         const struct dsdb_schema *schema;
226         int *val;
227         struct ldb_control *edn_control;
228         const char *dn_attrs[] = {
229                 "configurationNamingContext",
230                 "defaultNamingContext",
231                 "rootDomainNamingContext",
232                 "schemaNamingContext",
233                 "serverName",
234                 "validFSMOs",
235                 "namingContexts",
236                 NULL
237         };
238         const char *guid_attrs[] = {
239                 "dsServiceName",
240                 NULL
241         };
242         unsigned int i;
243
244         ldb = ldb_module_get_ctx(module);
245         schema = dsdb_get_schema(ldb, NULL);
246
247         msg->dn = ldb_dn_new(msg, ldb, NULL);
248
249         /* don't return the distinguishedName, cn and name attributes */
250         ldb_msg_remove_attr(msg, "distinguishedName");
251         ldb_msg_remove_attr(msg, "cn");
252         ldb_msg_remove_attr(msg, "name");
253
254         if (do_attribute(attrs, "serverName")) {
255                 if (ldb_msg_add_linearized_dn(msg, "serverName",
256                         samdb_server_dn(ldb, msg)) != LDB_SUCCESS) {
257                         goto failed;
258                 }
259         }
260
261         if (do_attribute(attrs, "dnsHostName")) {
262                 struct ldb_result *res;
263                 int ret;
264                 const char *dns_attrs[] = { "dNSHostName", NULL };
265                 ret = dsdb_module_search_dn(module, msg, &res, samdb_server_dn(ldb, msg),
266                                             dns_attrs,
267                                             DSDB_FLAG_NEXT_MODULE |
268                                             DSDB_FLAG_AS_SYSTEM,
269                                             req);
270                 if (ret == LDB_SUCCESS) {
271                         const char *hostname = ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
272                         if (hostname != NULL) {
273                                 if (ldb_msg_add_string(msg, "dNSHostName", hostname)) {
274                                         goto failed;
275                                 }
276                         }
277                 }
278         }
279
280         if (do_attribute(attrs, "ldapServiceName")) {
281                 struct loadparm_context *lp_ctx
282                         = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
283                                           struct loadparm_context);
284                 char *ldap_service_name, *hostname;
285
286                 hostname = strlower_talloc(msg, lpcfg_netbios_name(lp_ctx));
287                 if (hostname == NULL) {
288                         goto failed;
289                 }
290
291                 ldap_service_name = talloc_asprintf(msg, "%s:%s$@%s",
292                                                     samdb_forest_name(ldb, msg),
293                                                     hostname, lpcfg_realm(lp_ctx));
294                 if (ldap_service_name == NULL) {
295                         goto failed;
296                 }
297
298                 if (ldb_msg_add_string(msg, "ldapServiceName",
299                                        ldap_service_name) != LDB_SUCCESS) {
300                         goto failed;
301                 }
302         }
303
304         if (do_attribute(attrs, "currentTime")) {
305                 if (ldb_msg_add_steal_string(msg, "currentTime",
306                                              ldb_timestring(msg, time(NULL))) != LDB_SUCCESS) {
307                         goto failed;
308                 }
309         }
310
311         if (priv && do_attribute(attrs, "supportedControl")) {
312                 for (i = 0; i < priv->num_controls; i++) {
313                         char *control = talloc_strdup(msg, priv->controls[i]);
314                         if (!control) {
315                                 goto failed;
316                         }
317                         if (ldb_msg_add_steal_string(msg, "supportedControl",
318                                                      control) != LDB_SUCCESS) {
319                                 goto failed;
320                         }
321                 }
322         }
323
324         if (priv && do_attribute(attrs, "namingContexts")) {
325                 for (i = 0; i < priv->num_partitions; i++) {
326                         struct ldb_dn *dn = priv->partitions[i];
327                         if (ldb_msg_add_steal_string(msg, "namingContexts",
328                                                      ldb_dn_alloc_linearized(msg, dn)) != LDB_SUCCESS) {
329                                 goto failed;
330                         }
331                 }
332         }
333
334         server_sasl = talloc_get_type(ldb_get_opaque(ldb, "supportedSASLMechanisms"),
335                                        char *);
336         if (server_sasl && do_attribute(attrs, "supportedSASLMechanisms")) {
337                 for (i = 0; server_sasl && server_sasl[i]; i++) {
338                         char *sasl_name = talloc_strdup(msg, server_sasl[i]);
339                         if (!sasl_name) {
340                                 goto failed;
341                         }
342                         if (ldb_msg_add_steal_string(msg, "supportedSASLMechanisms",
343                                                      sasl_name) != LDB_SUCCESS) {
344                                 goto failed;
345                         }
346                 }
347         }
348
349         if (do_attribute(attrs, "highestCommittedUSN")) {
350                 uint64_t seq_num;
351                 int ret = ldb_sequence_number(ldb, LDB_SEQ_HIGHEST_SEQ, &seq_num);
352                 if (ret == LDB_SUCCESS) {
353                         if (samdb_msg_add_uint64(ldb, msg, msg,
354                                                  "highestCommittedUSN",
355                                                  seq_num) != LDB_SUCCESS) {
356                                 goto failed;
357                         }
358                 }
359         }
360
361         if (schema && do_attribute_explicit(attrs, "dsSchemaAttrCount")) {
362                 struct dsdb_attribute *cur;
363                 unsigned int n = 0;
364
365                 for (cur = schema->attributes; cur; cur = cur->next) {
366                         n++;
367                 }
368
369                 if (samdb_msg_add_uint(ldb, msg, msg, "dsSchemaAttrCount",
370                                        n) != LDB_SUCCESS) {
371                         goto failed;
372                 }
373         }
374
375         if (schema && do_attribute_explicit(attrs, "dsSchemaClassCount")) {
376                 struct dsdb_class *cur;
377                 unsigned int n = 0;
378
379                 for (cur = schema->classes; cur; cur = cur->next) {
380                         n++;
381                 }
382
383                 if (samdb_msg_add_uint(ldb, msg, msg, "dsSchemaClassCount",
384                                        n) != LDB_SUCCESS) {
385                         goto failed;
386                 }
387         }
388
389         if (schema && do_attribute_explicit(attrs, "dsSchemaPrefixCount")) {
390                 if (samdb_msg_add_uint(ldb, msg, msg, "dsSchemaPrefixCount",
391                                        schema->prefixmap->length) != LDB_SUCCESS) {
392                         goto failed;
393                 }
394         }
395
396         if (do_attribute_explicit(attrs, "validFSMOs")) {
397                 struct ldb_dn *dns[3];
398
399                 dns[0] = ldb_get_schema_basedn(ldb);
400                 dns[1] = samdb_partitions_dn(ldb, msg);
401                 dns[2] = ldb_get_default_basedn(ldb);
402
403                 for (i=0; i<3; i++) {
404                         bool master;
405                         int ret = dsdb_module_we_are_master(module, dns[i], &master, req);
406                         if (ret != LDB_SUCCESS) {
407                                 goto failed;
408                         }
409                         if (master && ldb_msg_add_fmt(msg, "validFSMOs", "%s",
410                                                       ldb_dn_get_linearized(dns[i])) != LDB_SUCCESS) {
411                                 goto failed;
412                         }
413                 }
414         }
415
416         if (do_attribute_explicit(attrs, "vendorVersion")) {
417                 if (ldb_msg_add_fmt(msg, "vendorVersion",
418                                     "%s", SAMBA_VERSION_STRING) != LDB_SUCCESS) {
419                         goto failed;
420                 }
421         }
422
423         if (do_attribute(attrs, "domainFunctionality")) {
424                 if (samdb_msg_add_int(ldb, msg, msg, "domainFunctionality",
425                                       dsdb_functional_level(ldb)) != LDB_SUCCESS) {
426                         goto failed;
427                 }
428         }
429
430         if (do_attribute(attrs, "forestFunctionality")) {
431                 if (samdb_msg_add_int(ldb, msg, msg, "forestFunctionality",
432                                       dsdb_forest_functional_level(ldb)) != LDB_SUCCESS) {
433                         goto failed;
434                 }
435         }
436
437         if (do_attribute(attrs, "domainControllerFunctionality")
438             && (val = talloc_get_type(ldb_get_opaque(ldb, "domainControllerFunctionality"), int))) {
439                 if (samdb_msg_add_int(ldb, msg, msg,
440                                       "domainControllerFunctionality",
441                                       *val) != LDB_SUCCESS) {
442                         goto failed;
443                 }
444         }
445
446         if (do_attribute(attrs, "isGlobalCatalogReady")) {
447                 /* MS-ADTS 3.1.1.3.2.10
448                    Note, we should only return true here is we have
449                    completed at least one synchronisation. As both
450                    provision and vampire do a full sync, this means we
451                    can return true is the gc bit is set in the NTDSDSA
452                    options */
453                 if (ldb_msg_add_fmt(msg, "isGlobalCatalogReady",
454                                     "%s", samdb_is_gc(ldb)?"TRUE":"FALSE") != LDB_SUCCESS) {
455                         goto failed;
456                 }
457         }
458
459         if (do_attribute_explicit(attrs, "tokenGroups")) {
460                 /* Obtain the user's session_info */
461                 struct auth_session_info *session_info
462                         = (struct auth_session_info *)ldb_get_opaque(ldb, "sessionInfo");
463                 if (session_info && session_info->security_token) {
464                         /* The list of groups this user is in */
465                         for (i = 0; i < session_info->security_token->num_sids; i++) {
466                                 if (samdb_msg_add_dom_sid(ldb, msg, msg,
467                                                           "tokenGroups",
468                                                           &session_info->security_token->sids[i]) != LDB_SUCCESS) {
469                                         goto failed;
470                                 }
471                         }
472                 }
473         }
474
475         /* TODO: lots more dynamic attributes should be added here */
476
477         edn_control = ldb_request_get_control(req, LDB_CONTROL_EXTENDED_DN_OID);
478
479         /* convert any GUID attributes to be in the right form */
480         for (i=0; guid_attrs[i]; i++) {
481                 struct ldb_result *res;
482                 struct ldb_message_element *el;
483                 struct ldb_dn *attr_dn;
484                 const char *no_attrs[] = { NULL };
485                 int ret;
486
487                 if (!do_attribute(attrs, guid_attrs[i])) continue;
488
489                 attr_dn = ldb_msg_find_attr_as_dn(ldb, req, msg, guid_attrs[i]);
490                 if (attr_dn == NULL) {
491                         continue;
492                 }
493
494                 ret = dsdb_module_search_dn(module, req, &res,
495                                             attr_dn, no_attrs,
496                                             DSDB_FLAG_NEXT_MODULE |
497                                             DSDB_FLAG_AS_SYSTEM |
498                                             DSDB_SEARCH_SHOW_EXTENDED_DN,
499                                             req);
500                 if (ret != LDB_SUCCESS) {
501                         return ldb_operr(ldb);
502                 }
503
504                 el = ldb_msg_find_element(msg, guid_attrs[i]);
505                 if (el == NULL) {
506                         return ldb_operr(ldb);
507                 }
508
509                 talloc_steal(el->values, res->msgs[0]->dn);
510                 if (edn_control) {
511                         struct ldb_extended_dn_control *edn;
512                         int edn_type = 0;
513                         edn = talloc_get_type(edn_control->data, struct ldb_extended_dn_control);
514                         if (edn != NULL) {
515                                 edn_type = edn->type;
516                         }
517                         el->values[0].data  = (uint8_t *)ldb_dn_get_extended_linearized(el->values,
518                                                                                         res->msgs[0]->dn,
519                                                                                         edn_type);
520                 } else {
521                         el->values[0].data  = (uint8_t *)talloc_strdup(el->values,
522                                                                        ldb_dn_get_linearized(res->msgs[0]->dn));
523                 }
524                 if (el->values[0].data == NULL) {
525                         return ldb_oom(ldb);
526                 }
527                 el->values[0].length = strlen((const char *)el->values[0].data);
528         }
529
530         /* if the client sent us the EXTENDED_DN control then we need
531            to expand the DNs to have GUID and SID. W2K8 join relies on
532            this */
533         if (edn_control) {
534                 int ret;
535                 for (i=0; dn_attrs[i]; i++) {
536                         if (!do_attribute(attrs, dn_attrs[i])) continue;
537                         ret = expand_dn_in_message(module, msg, dn_attrs[i],
538                                                    edn_control, req);
539                         if (ret != LDB_SUCCESS) {
540                                 DEBUG(0,(__location__ ": Failed to expand DN in rootDSE for %s\n",
541                                          dn_attrs[i]));
542                                 goto failed;
543                         }
544                 }
545         }
546
547         return LDB_SUCCESS;
548
549 failed:
550         return ldb_operr(ldb);
551 }
552
553 /*
554   handle search requests
555 */
556
557 struct rootdse_context {
558         struct ldb_module *module;
559         struct ldb_request *req;
560 };
561
562 static struct rootdse_context *rootdse_init_context(struct ldb_module *module,
563                                                     struct ldb_request *req)
564 {
565         struct ldb_context *ldb;
566         struct rootdse_context *ac;
567
568         ldb = ldb_module_get_ctx(module);
569
570         ac = talloc_zero(req, struct rootdse_context);
571         if (ac == NULL) {
572                 ldb_set_errstring(ldb, "Out of Memory");
573                 return NULL;
574         }
575
576         ac->module = module;
577         ac->req = req;
578
579         return ac;
580 }
581
582 static int rootdse_callback(struct ldb_request *req, struct ldb_reply *ares)
583 {
584         struct rootdse_context *ac;
585         int ret;
586
587         ac = talloc_get_type(req->context, struct rootdse_context);
588
589         if (!ares) {
590                 return ldb_module_done(ac->req, NULL, NULL,
591                                         LDB_ERR_OPERATIONS_ERROR);
592         }
593         if (ares->error != LDB_SUCCESS) {
594                 return ldb_module_done(ac->req, ares->controls,
595                                         ares->response, ares->error);
596         }
597
598         switch (ares->type) {
599         case LDB_REPLY_ENTRY:
600                 /*
601                  * if the client explicit asks for the 'netlogon' attribute
602                  * the reply_entry needs to be skipped
603                  */
604                 if (ac->req->op.search.attrs &&
605                     ldb_attr_in_list(ac->req->op.search.attrs, "netlogon")) {
606                         talloc_free(ares);
607                         return LDB_SUCCESS;
608                 }
609
610                 /* for each record returned post-process to add any dynamic
611                    attributes that have been asked for */
612                 ret = rootdse_add_dynamic(ac->module, ares->message,
613                                           ac->req->op.search.attrs, ac->req);
614                 if (ret != LDB_SUCCESS) {
615                         talloc_free(ares);
616                         return ldb_module_done(ac->req, NULL, NULL, ret);
617                 }
618
619                 return ldb_module_send_entry(ac->req, ares->message, ares->controls);
620
621         case LDB_REPLY_REFERRAL:
622                 /* should we allow the backend to return referrals in this case
623                  * ?? */
624                 break;
625
626         case LDB_REPLY_DONE:
627                 return ldb_module_done(ac->req, ares->controls,
628                                         ares->response, ares->error);
629         }
630
631         talloc_free(ares);
632         return LDB_SUCCESS;
633 }
634
635 /*
636   filter from controls from clients in several ways
637
638   1) mark our registered controls as non-critical in the request
639
640     This is needed as clients may mark controls as critical even if
641     they are not needed at all in a request. For example, the centrify
642     client sets the SD_FLAGS control as critical on ldap modify
643     requests which are setting the dNSHostName attribute on the
644     machine account. That request doesn't need SD_FLAGS at all, but
645     centrify adds it on all ldap requests.
646
647   2) if this request is untrusted then remove any non-registered
648      controls that are non-critical
649
650     This is used on ldap:// connections to prevent remote users from
651     setting an internal control that may be dangerous
652
653   3) if this request is untrusted then fail any request that includes
654      a critical non-registered control
655  */
656 static int rootdse_filter_controls(struct ldb_module *module, struct ldb_request *req)
657 {
658         unsigned int i, j;
659         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
660         bool is_untrusted;
661
662         if (!req->controls) {
663                 return LDB_SUCCESS;
664         }
665
666         is_untrusted = ldb_req_is_untrusted(req);
667
668         for (i=0; req->controls[i]; i++) {
669                 bool is_registered = false;
670                 bool is_critical = (req->controls[i]->critical != 0);
671
672                 if (req->controls[i]->oid == NULL) {
673                         continue;
674                 }
675
676                 if (is_untrusted || is_critical) {
677                         for (j=0; j<priv->num_controls; j++) {
678                                 if (strcasecmp(priv->controls[j], req->controls[i]->oid) == 0) {
679                                         is_registered = true;
680                                         break;
681                                 }
682                         }
683                 }
684
685                 if (is_untrusted && !is_registered) {
686                         if (!is_critical) {
687                                 /* remove it by marking the oid NULL */
688                                 req->controls[i]->oid = NULL;
689                                 req->controls[i]->data = NULL;
690                                 req->controls[i]->critical = 0;
691                                 continue;
692                         }
693                         /* its a critical unregistered control - give
694                            an error */
695                         ldb_asprintf_errstring(ldb_module_get_ctx(module),
696                                                "Attempt to use critical non-registered control '%s'",
697                                                req->controls[i]->oid);
698                         return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
699                 }
700
701                 if (!is_critical) {
702                         continue;
703                 }
704
705                 /* If the control is DIRSYNC control then we keep the critical
706                  * flag as the dirsync module will need to act upon it
707                  */
708                 if (is_registered && strcmp(req->controls[i]->oid,
709                                         LDB_CONTROL_DIRSYNC_OID)!= 0) {
710                         req->controls[i]->critical = 0;
711                 }
712         }
713
714         return LDB_SUCCESS;
715 }
716
717 /* Ensure that anonymous users are not allowed to make anything other than rootDSE search operations */
718
719 static int rootdse_filter_operations(struct ldb_module *module, struct ldb_request *req)
720 {
721         struct auth_session_info *session_info;
722         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
723         bool is_untrusted = ldb_req_is_untrusted(req);
724         bool is_anonymous = true;
725         if (is_untrusted == false) {
726                 return LDB_SUCCESS;
727         }
728
729         session_info = (struct auth_session_info *)ldb_get_opaque(ldb_module_get_ctx(module), "sessionInfo");
730         if (session_info) {
731                 is_anonymous = security_token_is_anonymous(session_info->security_token);
732         }
733         
734         if (is_anonymous == false || (priv && priv->block_anonymous == false)) {
735                 return LDB_SUCCESS;
736         }
737         
738         if (req->operation == LDB_SEARCH) {
739                 if (req->op.search.scope == LDB_SCOPE_BASE && ldb_dn_is_null(req->op.search.base)) {
740                         return LDB_SUCCESS;
741                 }
742         }
743         ldb_set_errstring(ldb_module_get_ctx(module), "Operation unavailable without authentication");
744         return LDB_ERR_OPERATIONS_ERROR;
745 }
746
747 static int rootdse_search(struct ldb_module *module, struct ldb_request *req)
748 {
749         struct ldb_context *ldb;
750         struct rootdse_context *ac;
751         struct ldb_request *down_req;
752         int ret;
753
754         ret = rootdse_filter_operations(module, req);
755         if (ret != LDB_SUCCESS) {
756                 return ret;
757         }
758
759         ret = rootdse_filter_controls(module, req);
760         if (ret != LDB_SUCCESS) {
761                 return ret;
762         }
763
764         ldb = ldb_module_get_ctx(module);
765
766         /* see if its for the rootDSE - only a base search on the "" DN qualifies */
767         if (!(req->op.search.scope == LDB_SCOPE_BASE && ldb_dn_is_null(req->op.search.base))) {
768                 /* Otherwise, pass down to the rest of the stack */
769                 return ldb_next_request(module, req);
770         }
771
772         ac = rootdse_init_context(module, req);
773         if (ac == NULL) {
774                 return ldb_operr(ldb);
775         }
776
777         /* in our db we store the rootDSE with a DN of @ROOTDSE */
778         ret = ldb_build_search_req(&down_req, ldb, ac,
779                                         ldb_dn_new(ac, ldb, "@ROOTDSE"),
780                                         LDB_SCOPE_BASE,
781                                         NULL,
782                                         req->op.search.attrs,
783                                         NULL,/* for now skip the controls from the client */
784                                         ac, rootdse_callback,
785                                         req);
786         LDB_REQ_SET_LOCATION(down_req);
787         if (ret != LDB_SUCCESS) {
788                 return ret;
789         }
790
791         return ldb_next_request(module, down_req);
792 }
793
794 static int rootdse_register_control(struct ldb_module *module, struct ldb_request *req)
795 {
796         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
797         char **list;
798
799         list = talloc_realloc(priv, priv->controls, char *, priv->num_controls + 1);
800         if (!list) {
801                 return ldb_oom(ldb_module_get_ctx(module));
802         }
803
804         list[priv->num_controls] = talloc_strdup(list, req->op.reg_control.oid);
805         if (!list[priv->num_controls]) {
806                 return ldb_oom(ldb_module_get_ctx(module));
807         }
808
809         priv->num_controls += 1;
810         priv->controls = list;
811
812         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
813 }
814
815 static int rootdse_register_partition(struct ldb_module *module, struct ldb_request *req)
816 {
817         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
818         struct ldb_dn **list;
819
820         list = talloc_realloc(priv, priv->partitions, struct ldb_dn *, priv->num_partitions + 1);
821         if (!list) {
822                 return ldb_oom(ldb_module_get_ctx(module));
823         }
824
825         list[priv->num_partitions] = ldb_dn_copy(list, req->op.reg_partition.dn);
826         if (!list[priv->num_partitions]) {
827                 return ldb_operr(ldb_module_get_ctx(module));
828         }
829
830         priv->num_partitions += 1;
831         priv->partitions = list;
832
833         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
834 }
835
836
837 static int rootdse_request(struct ldb_module *module, struct ldb_request *req)
838 {
839         switch (req->operation) {
840
841         case LDB_REQ_REGISTER_CONTROL:
842                 return rootdse_register_control(module, req);
843         case LDB_REQ_REGISTER_PARTITION:
844                 return rootdse_register_partition(module, req);
845
846         default:
847                 break;
848         }
849         return ldb_next_request(module, req);
850 }
851
852 static int rootdse_init(struct ldb_module *module)
853 {
854         int ret;
855         struct ldb_context *ldb;
856         struct ldb_result *res;
857         struct private_data *data;
858         const char *attrs[] = { "msDS-Behavior-Version", NULL };
859         const char *ds_attrs[] = { "dsServiceName", NULL };
860         TALLOC_CTX *mem_ctx;
861
862         ldb = ldb_module_get_ctx(module);
863
864         data = talloc_zero(module, struct private_data);
865         if (data == NULL) {
866                 return ldb_oom(ldb);
867         }
868
869         data->num_controls = 0;
870         data->controls = NULL;
871         data->num_partitions = 0;
872         data->partitions = NULL;
873         data->block_anonymous = true;
874
875         ldb_module_set_private(module, data);
876
877         ldb_set_default_dns(ldb);
878
879         ret = ldb_next_init(module);
880
881         if (ret != LDB_SUCCESS) {
882                 return ret;
883         }
884
885         mem_ctx = talloc_new(data);
886         if (!mem_ctx) {
887                 return ldb_oom(ldb);
888         }
889
890         /* Now that the partitions are set up, do a search for:
891            - domainControllerFunctionality
892            - domainFunctionality
893            - forestFunctionality
894
895            Then stuff these values into an opaque
896         */
897         ret = dsdb_module_search(module, mem_ctx, &res,
898                                  ldb_get_default_basedn(ldb),
899                                  LDB_SCOPE_BASE, attrs,
900                                  DSDB_FLAG_NEXT_MODULE |
901                                  DSDB_FLAG_AS_SYSTEM,
902                                  NULL, NULL);
903         if (ret == LDB_SUCCESS && res->count == 1) {
904                 int domain_behaviour_version
905                         = ldb_msg_find_attr_as_int(res->msgs[0],
906                                                    "msDS-Behavior-Version", -1);
907                 if (domain_behaviour_version != -1) {
908                         int *val = talloc(ldb, int);
909                         if (!val) {
910                                 talloc_free(mem_ctx);
911                                 return ldb_oom(ldb);
912                         }
913                         *val = domain_behaviour_version;
914                         ret = ldb_set_opaque(ldb, "domainFunctionality", val);
915                         if (ret != LDB_SUCCESS) {
916                                 talloc_free(mem_ctx);
917                                 return ret;
918                         }
919                 }
920         }
921
922         ret = dsdb_module_search(module, mem_ctx, &res,
923                                  samdb_partitions_dn(ldb, mem_ctx),
924                                  LDB_SCOPE_BASE, attrs,
925                                  DSDB_FLAG_NEXT_MODULE |
926                                  DSDB_FLAG_AS_SYSTEM,
927                                  NULL, NULL);
928         if (ret == LDB_SUCCESS && res->count == 1) {
929                 int forest_behaviour_version
930                         = ldb_msg_find_attr_as_int(res->msgs[0],
931                                                    "msDS-Behavior-Version", -1);
932                 if (forest_behaviour_version != -1) {
933                         int *val = talloc(ldb, int);
934                         if (!val) {
935                                 talloc_free(mem_ctx);
936                                 return ldb_oom(ldb);
937                         }
938                         *val = forest_behaviour_version;
939                         ret = ldb_set_opaque(ldb, "forestFunctionality", val);
940                         if (ret != LDB_SUCCESS) {
941                                 talloc_free(mem_ctx);
942                                 return ret;
943                         }
944                 }
945         }
946
947         /* For now, our own server's location in the DB is recorded in
948          * the @ROOTDSE record */
949         ret = dsdb_module_search(module, mem_ctx, &res,
950                                  ldb_dn_new(mem_ctx, ldb, "@ROOTDSE"),
951                                  LDB_SCOPE_BASE, ds_attrs,
952                                  DSDB_FLAG_NEXT_MODULE |
953                                  DSDB_FLAG_AS_SYSTEM,
954                                  NULL, NULL);
955         if (ret == LDB_SUCCESS && res->count == 1) {
956                 struct ldb_dn *ds_dn
957                         = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0],
958                                                   "dsServiceName");
959                 if (ds_dn) {
960                         ret = dsdb_module_search(module, mem_ctx, &res, ds_dn,
961                                                  LDB_SCOPE_BASE, attrs,
962                                                  DSDB_FLAG_NEXT_MODULE |
963                                                  DSDB_FLAG_AS_SYSTEM,
964                                                  NULL, NULL);
965                         if (ret == LDB_SUCCESS && res->count == 1) {
966                                 int domain_controller_behaviour_version
967                                         = ldb_msg_find_attr_as_int(res->msgs[0],
968                                                                    "msDS-Behavior-Version", -1);
969                                 if (domain_controller_behaviour_version != -1) {
970                                         int *val = talloc(ldb, int);
971                                         if (!val) {
972                                                 talloc_free(mem_ctx);
973                                                 return ldb_oom(ldb);
974                                         }
975                                         *val = domain_controller_behaviour_version;
976                                         ret = ldb_set_opaque(ldb,
977                                                              "domainControllerFunctionality", val);
978                                         if (ret != LDB_SUCCESS) {
979                                                 talloc_free(mem_ctx);
980                                                 return ret;
981                                         }
982                                 }
983                         }
984                 }
985         }
986
987         data->block_anonymous = dsdb_block_anonymous_ops(module, NULL);
988
989         talloc_free(mem_ctx);
990
991         return LDB_SUCCESS;
992 }
993
994 /*
995  * This function gets the string SCOPE_DN:OPTIONAL_FEATURE_GUID and parse it
996  * to a DN and a GUID object
997  */
998 static int get_optional_feature_dn_guid(struct ldb_request *req, struct ldb_context *ldb,
999                                                 TALLOC_CTX *mem_ctx,
1000                                                 struct ldb_dn **op_feature_scope_dn,
1001                                                 struct GUID *op_feature_guid)
1002 {
1003         const struct ldb_message *msg = req->op.mod.message;
1004         const char *ldb_val_str;
1005         char *dn, *guid;
1006         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1007         NTSTATUS status;
1008
1009         ldb_val_str = ldb_msg_find_attr_as_string(msg, "enableOptionalFeature", NULL);
1010         if (!ldb_val_str) {
1011                 ldb_set_errstring(ldb,
1012                                   "rootdse: unable to find 'enableOptionalFeature'!");
1013                 return LDB_ERR_UNWILLING_TO_PERFORM;
1014         }
1015
1016         guid = strchr(ldb_val_str, ':');
1017         if (!guid) {
1018                 ldb_set_errstring(ldb,
1019                                   "rootdse: unable to find GUID in 'enableOptionalFeature'!");
1020                 return LDB_ERR_UNWILLING_TO_PERFORM;
1021         }
1022         status = GUID_from_string(guid+1, op_feature_guid);
1023         if (!NT_STATUS_IS_OK(status)) {
1024                 ldb_set_errstring(ldb,
1025                                   "rootdse: bad GUID in 'enableOptionalFeature'!");
1026                 return LDB_ERR_UNWILLING_TO_PERFORM;
1027         }
1028
1029         dn = talloc_strndup(tmp_ctx, ldb_val_str, guid-ldb_val_str);
1030         if (!dn) {
1031                 ldb_set_errstring(ldb,
1032                                   "rootdse: bad DN in 'enableOptionalFeature'!");
1033                 return LDB_ERR_UNWILLING_TO_PERFORM;
1034         }
1035
1036         *op_feature_scope_dn = ldb_dn_new(mem_ctx, ldb, dn);
1037
1038         talloc_free(tmp_ctx);
1039         return LDB_SUCCESS;
1040 }
1041
1042 /*
1043  * This function gets the OPTIONAL_FEATURE_GUID and looks for the optional feature
1044  * ldb_message object.
1045  */
1046 static int dsdb_find_optional_feature(struct ldb_module *module, struct ldb_context *ldb,
1047                                       TALLOC_CTX *mem_ctx, struct GUID op_feature_guid, struct ldb_message **msg,
1048                                       struct ldb_request *parent)
1049 {
1050         struct ldb_result *res;
1051         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1052         int ret;
1053
1054         ret = dsdb_module_search(module, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE,
1055                                  NULL,
1056                                  DSDB_FLAG_NEXT_MODULE |
1057                                  DSDB_FLAG_AS_SYSTEM |
1058                                  DSDB_SEARCH_SEARCH_ALL_PARTITIONS,
1059                                  parent,
1060                                  "(&(objectClass=msDS-OptionalFeature)"
1061                                  "(msDS-OptionalFeatureGUID=%s))",GUID_string(tmp_ctx, &op_feature_guid));
1062
1063         if (ret != LDB_SUCCESS) {
1064                 talloc_free(tmp_ctx);
1065                 return ret;
1066         }
1067         if (res->count == 0) {
1068                 talloc_free(tmp_ctx);
1069                 return LDB_ERR_NO_SUCH_OBJECT;
1070         }
1071         if (res->count != 1) {
1072                 ldb_asprintf_errstring(ldb,
1073                                        "More than one object found matching optional feature GUID %s\n",
1074                                        GUID_string(tmp_ctx, &op_feature_guid));
1075                 talloc_free(tmp_ctx);
1076                 return LDB_ERR_OPERATIONS_ERROR;
1077         }
1078
1079         *msg = talloc_steal(mem_ctx, res->msgs[0]);
1080
1081         talloc_free(tmp_ctx);
1082         return LDB_SUCCESS;
1083 }
1084
1085 static int rootdse_enable_recycle_bin(struct ldb_module *module,struct ldb_context *ldb,
1086                                       TALLOC_CTX *mem_ctx, struct ldb_dn *op_feature_scope_dn,
1087                                       struct ldb_message *op_feature_msg, struct ldb_request *parent)
1088 {
1089         int ret;
1090         const int domain_func_level = dsdb_functional_level(ldb);
1091         struct ldb_dn *ntds_settings_dn;
1092         TALLOC_CTX *tmp_ctx;
1093         unsigned int el_count = 0;
1094         struct ldb_message *msg;
1095
1096         ret = ldb_msg_find_attr_as_int(op_feature_msg, "msDS-RequiredForestBehaviorVersion", 0);
1097         if (domain_func_level < ret){
1098                 ldb_asprintf_errstring(ldb,
1099                                        "rootdse_enable_recycle_bin: Domain functional level must be at least %d\n",
1100                                        ret);
1101                 return LDB_ERR_UNWILLING_TO_PERFORM;
1102         }
1103
1104         tmp_ctx = talloc_new(mem_ctx);
1105         ntds_settings_dn = samdb_ntds_settings_dn(ldb, tmp_ctx);
1106         if (!ntds_settings_dn) {
1107                 talloc_free(tmp_ctx);
1108                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR, "Failed to find NTDS settings DN");
1109         }
1110
1111         ntds_settings_dn = ldb_dn_copy(tmp_ctx, ntds_settings_dn);
1112         if (!ntds_settings_dn) {
1113                 talloc_free(tmp_ctx);
1114                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR, "Failed to copy NTDS settings DN");
1115         }
1116
1117         msg = ldb_msg_new(tmp_ctx);
1118         msg->dn = ntds_settings_dn;
1119
1120         ldb_msg_add_linearized_dn(msg, "msDS-EnabledFeature", op_feature_msg->dn);
1121         msg->elements[el_count++].flags = LDB_FLAG_MOD_ADD;
1122
1123         ret = dsdb_module_modify(module, msg, DSDB_FLAG_NEXT_MODULE, parent);
1124         if (ret != LDB_SUCCESS) {
1125                 ldb_asprintf_errstring(ldb,
1126                                        "rootdse_enable_recycle_bin: Failed to modify object %s - %s",
1127                                        ldb_dn_get_linearized(ntds_settings_dn),
1128                                        ldb_errstring(ldb));
1129                 talloc_free(tmp_ctx);
1130                 return ret;
1131         }
1132
1133         msg->dn = op_feature_scope_dn;
1134         ret = dsdb_module_modify(module, msg, DSDB_FLAG_NEXT_MODULE, parent);
1135         if (ret != LDB_SUCCESS) {
1136                 ldb_asprintf_errstring(ldb,
1137                                        "rootdse_enable_recycle_bin: Failed to modify object %s - %s",
1138                                        ldb_dn_get_linearized(op_feature_scope_dn),
1139                                        ldb_errstring(ldb));
1140                 talloc_free(tmp_ctx);
1141                 return ret;
1142         }
1143
1144         return LDB_SUCCESS;
1145 }
1146
1147 static int rootdse_enableoptionalfeature(struct ldb_module *module, struct ldb_request *req)
1148 {
1149         /*
1150           steps:
1151                - check for system (only system can enable features)
1152                - extract GUID from the request
1153                - find the feature object
1154                - check functional level, must be at least msDS-RequiredForestBehaviorVersion
1155                - check if it is already enabled (if enabled return LDAP_ATTRIBUTE_OR_VALUE_EXISTS) - probably not needed, just return error from the add/modify
1156                - add/modify objects (see ntdsconnection code for an example)
1157          */
1158
1159         struct ldb_context *ldb = ldb_module_get_ctx(module);
1160         struct GUID op_feature_guid;
1161         struct ldb_dn *op_feature_scope_dn;
1162         struct ldb_message *op_feature_msg;
1163         struct auth_session_info *session_info =
1164                                 (struct auth_session_info *)ldb_get_opaque(ldb, "sessionInfo");
1165         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1166         int ret;
1167         const char *guid_string;
1168
1169         if (security_session_user_level(session_info, NULL) != SECURITY_SYSTEM) {
1170                 ldb_set_errstring(ldb, "rootdse: Insufficient rights for enableoptionalfeature");
1171                 return LDB_ERR_UNWILLING_TO_PERFORM;
1172         }
1173
1174         ret = get_optional_feature_dn_guid(req, ldb, tmp_ctx, &op_feature_scope_dn, &op_feature_guid);
1175         if (ret != LDB_SUCCESS) {
1176                 talloc_free(tmp_ctx);
1177                 return ret;
1178         }
1179
1180         guid_string = GUID_string(tmp_ctx, &op_feature_guid);
1181         if (!guid_string) {
1182                 ldb_set_errstring(ldb, "rootdse: bad optional feature GUID");
1183                 return LDB_ERR_UNWILLING_TO_PERFORM;
1184         }
1185
1186         ret = dsdb_find_optional_feature(module, ldb, tmp_ctx, op_feature_guid, &op_feature_msg, req);
1187         if (ret != LDB_SUCCESS) {
1188                 ldb_asprintf_errstring(ldb,
1189                                        "rootdse: unable to find optional feature for %s - %s",
1190                                        guid_string, ldb_errstring(ldb));
1191                 talloc_free(tmp_ctx);
1192                 return ret;
1193         }
1194
1195         if (strcasecmp(DS_GUID_FEATURE_RECYCLE_BIN, guid_string) == 0) {
1196                         ret = rootdse_enable_recycle_bin(module, ldb,
1197                                                          tmp_ctx, op_feature_scope_dn,
1198                                                          op_feature_msg, req);
1199         } else {
1200                 ldb_asprintf_errstring(ldb,
1201                                        "rootdse: unknown optional feature %s",
1202                                        guid_string);
1203                 talloc_free(tmp_ctx);
1204                 return LDB_ERR_UNWILLING_TO_PERFORM;
1205         }
1206         if (ret != LDB_SUCCESS) {
1207                 ldb_asprintf_errstring(ldb,
1208                                        "rootdse: failed to set optional feature for %s - %s",
1209                                        guid_string, ldb_errstring(ldb));
1210                 talloc_free(tmp_ctx);
1211                 return ret;
1212         }
1213
1214         talloc_free(tmp_ctx);
1215         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);;
1216 }
1217
1218 static int rootdse_schemaupdatenow(struct ldb_module *module, struct ldb_request *req)
1219 {
1220         struct ldb_context *ldb = ldb_module_get_ctx(module);
1221         struct ldb_result *ext_res;
1222         int ret;
1223         struct ldb_dn *schema_dn;
1224
1225         schema_dn = ldb_get_schema_basedn(ldb);
1226         if (!schema_dn) {
1227                 ldb_reset_err_string(ldb);
1228                 ldb_debug(ldb, LDB_DEBUG_WARNING,
1229                           "rootdse_modify: no schema dn present: (skip ldb_extended call)\n");
1230                 return ldb_next_request(module, req);
1231         }
1232
1233         ret = ldb_extended(ldb, DSDB_EXTENDED_SCHEMA_UPDATE_NOW_OID, schema_dn, &ext_res);
1234         if (ret != LDB_SUCCESS) {
1235                 return ldb_operr(ldb);
1236         }
1237
1238         talloc_free(ext_res);
1239         return ldb_module_done(req, NULL, NULL, ret);
1240 }
1241
1242 static int rootdse_schemaupgradeinprogress(struct ldb_module *module, struct ldb_request *req)
1243 {
1244         struct ldb_context *ldb = ldb_module_get_ctx(module);
1245         int ret = LDB_SUCCESS;
1246         struct ldb_dn *schema_dn;
1247
1248         schema_dn = ldb_get_schema_basedn(ldb);
1249         if (!schema_dn) {
1250                 ldb_reset_err_string(ldb);
1251                 ldb_debug(ldb, LDB_DEBUG_WARNING,
1252                           "rootdse_modify: no schema dn present: (skip ldb_extended call)\n");
1253                 return ldb_next_request(module, req);
1254         }
1255
1256         /* FIXME we have to do something in order to relax constraints for DRS
1257          * setting schemaUpgradeInProgress cause the fschemaUpgradeInProgress
1258          * in all LDAP connection (2K3/2K3R2) or in the current connection (2K8 and +)
1259          * to be set to true.
1260          */
1261
1262         /* from 5.113 LDAPConnections in DRSR.pdf
1263          * fschemaUpgradeInProgress: A Boolean that specifies certain constraint
1264          * validations are skipped when adding, updating, or removing directory
1265          * objects on the opened connection. The skipped constraint validations
1266          * are documented in the applicable constraint sections in [MS-ADTS].
1267          */
1268         return ldb_module_done(req, NULL, NULL, ret);
1269 }
1270
1271 static int rootdse_add(struct ldb_module *module, struct ldb_request *req)
1272 {
1273         struct ldb_context *ldb = ldb_module_get_ctx(module);
1274         int ret;
1275
1276         ret = rootdse_filter_operations(module, req);
1277         if (ret != LDB_SUCCESS) {
1278                 return ret;
1279         }
1280
1281         ret = rootdse_filter_controls(module, req);
1282         if (ret != LDB_SUCCESS) {
1283                 return ret;
1284         }
1285
1286         /*
1287                 If dn is not "" we should let it pass through
1288         */
1289         if (!ldb_dn_is_null(req->op.add.message->dn)) {
1290                 return ldb_next_request(module, req);
1291         }
1292
1293         ldb_set_errstring(ldb, "rootdse_add: you cannot add a new rootdse entry!");
1294         return LDB_ERR_NAMING_VIOLATION;
1295 }
1296
1297 struct fsmo_transfer_state {
1298         struct ldb_context *ldb;
1299         struct ldb_request *req;
1300 };
1301
1302 /*
1303   called when a FSMO transfer operation has completed
1304  */
1305 static void rootdse_fsmo_transfer_callback(struct tevent_req *treq)
1306 {
1307         struct fsmo_transfer_state *fsmo = tevent_req_callback_data(treq, struct fsmo_transfer_state);
1308         NTSTATUS status;
1309         WERROR werr;
1310         struct ldb_request *req = fsmo->req;
1311         struct ldb_context *ldb = fsmo->ldb;
1312
1313         status = dcerpc_drepl_takeFSMORole_recv(treq, fsmo, &werr);
1314         talloc_free(fsmo);
1315         if (!NT_STATUS_IS_OK(status)) {
1316                 ldb_asprintf_errstring(ldb, "Failed FSMO transfer: %s", nt_errstr(status));
1317                 ldb_module_done(req, NULL, NULL, LDB_ERR_UNAVAILABLE);
1318                 return;
1319         }
1320         if (!W_ERROR_IS_OK(werr)) {
1321                 ldb_asprintf_errstring(ldb, "Failed FSMO transfer: %s", win_errstr(werr));
1322                 ldb_module_done(req, NULL, NULL, LDB_ERR_UNAVAILABLE);
1323                 return;
1324         }
1325
1326         ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1327 }
1328
1329 static int rootdse_become_master(struct ldb_module *module,
1330                                  struct ldb_request *req,
1331                                  enum drepl_role_master role)
1332 {
1333         struct imessaging_context *msg;
1334         struct ldb_context *ldb = ldb_module_get_ctx(module);
1335         TALLOC_CTX *tmp_ctx = talloc_new(req);
1336         struct loadparm_context *lp_ctx = ldb_get_opaque(ldb, "loadparm");
1337         bool am_rodc;
1338         struct dcerpc_binding_handle *irpc_handle;
1339         int ret;
1340         struct auth_session_info *session_info;
1341         enum security_user_level level;
1342         struct fsmo_transfer_state *fsmo;
1343         struct tevent_req *treq;
1344
1345         session_info = (struct auth_session_info *)ldb_get_opaque(ldb_module_get_ctx(module), "sessionInfo");
1346         level = security_session_user_level(session_info, NULL);
1347         if (level < SECURITY_ADMINISTRATOR) {
1348                 return ldb_error(ldb, LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS, "Denied rootDSE modify for non-administrator");
1349         }
1350
1351         ret = samdb_rodc(ldb, &am_rodc);
1352         if (ret != LDB_SUCCESS) {
1353                 return ldb_error(ldb, ret, "Could not determine if server is RODC.");
1354         }
1355
1356         if (am_rodc) {
1357                 return ldb_error(ldb, LDB_ERR_UNWILLING_TO_PERFORM,
1358                                  "RODC cannot become a role master.");
1359         }
1360
1361         msg = imessaging_client_init(tmp_ctx, lp_ctx,
1362                                     ldb_get_event_context(ldb));
1363         if (!msg) {
1364                 ldb_asprintf_errstring(ldb, "Failed to generate client messaging context in %s", lpcfg_imessaging_path(tmp_ctx, lp_ctx));
1365                 return LDB_ERR_OPERATIONS_ERROR;
1366         }
1367         irpc_handle = irpc_binding_handle_by_name(tmp_ctx, msg,
1368                                                   "dreplsrv",
1369                                                   &ndr_table_irpc);
1370         if (irpc_handle == NULL) {
1371                 return ldb_oom(ldb);
1372         }
1373         fsmo = talloc_zero(req, struct fsmo_transfer_state);
1374         if (fsmo == NULL) {
1375                 return ldb_oom(ldb);
1376         }
1377         fsmo->ldb = ldb;
1378         fsmo->req = req;
1379
1380         /*
1381          * we send the call asynchronously, as the ldap client is
1382          * expecting to get an error back if the role transfer fails
1383          *
1384          * We need more than the default 10 seconds IRPC allows, so
1385          * set a longer timeout (default ldb timeout is 300 seconds).
1386          * We send an async reply when we are done.
1387          *
1388          * We are the first module, so don't bother working out how
1389          * long we have spent so far.
1390          */
1391         dcerpc_binding_handle_set_timeout(irpc_handle, req->timeout);
1392
1393         treq = dcerpc_drepl_takeFSMORole_send(req, ldb_get_event_context(ldb), irpc_handle, role);
1394         if (treq == NULL) {
1395                 return ldb_oom(ldb);
1396         }
1397
1398         tevent_req_set_callback(treq, rootdse_fsmo_transfer_callback, fsmo);
1399         return LDB_SUCCESS;
1400 }
1401
1402 static int rootdse_modify(struct ldb_module *module, struct ldb_request *req)
1403 {
1404         struct ldb_context *ldb = ldb_module_get_ctx(module);
1405         int ret;
1406
1407         ret = rootdse_filter_operations(module, req);
1408         if (ret != LDB_SUCCESS) {
1409                 return ret;
1410         }
1411
1412         ret = rootdse_filter_controls(module, req);
1413         if (ret != LDB_SUCCESS) {
1414                 return ret;
1415         }
1416
1417         /*
1418                 If dn is not "" we should let it pass through
1419         */
1420         if (!ldb_dn_is_null(req->op.mod.message->dn)) {
1421                 return ldb_next_request(module, req);
1422         }
1423
1424         /*
1425                 dn is empty so check for schemaUpdateNow attribute
1426                 "The type of modification and values specified in the LDAP modify operation do not matter." MSDN
1427         */
1428         if (ldb_msg_find_element(req->op.mod.message, "schemaUpdateNow")) {
1429                 return rootdse_schemaupdatenow(module, req);
1430         }
1431         if (ldb_msg_find_element(req->op.mod.message, "becomeDomainMaster")) {
1432                 return rootdse_become_master(module, req, DREPL_NAMING_MASTER);
1433         }
1434         if (ldb_msg_find_element(req->op.mod.message, "becomeInfrastructureMaster")) {
1435                 return rootdse_become_master(module, req, DREPL_INFRASTRUCTURE_MASTER);
1436         }
1437         if (ldb_msg_find_element(req->op.mod.message, "becomeRidMaster")) {
1438                 return rootdse_become_master(module, req, DREPL_RID_MASTER);
1439         }
1440         if (ldb_msg_find_element(req->op.mod.message, "becomeSchemaMaster")) {
1441                 return rootdse_become_master(module, req, DREPL_SCHEMA_MASTER);
1442         }
1443         if (ldb_msg_find_element(req->op.mod.message, "becomePdc")) {
1444                 return rootdse_become_master(module, req, DREPL_PDC_MASTER);
1445         }
1446         if (ldb_msg_find_element(req->op.mod.message, "enableOptionalFeature")) {
1447                 return rootdse_enableoptionalfeature(module, req);
1448         }
1449         if (ldb_msg_find_element(req->op.mod.message, "schemaUpgradeInProgress")) {
1450                 return rootdse_schemaupgradeinprogress(module, req);
1451         }
1452
1453         ldb_set_errstring(ldb, "rootdse_modify: unknown attribute to change!");
1454         return LDB_ERR_UNWILLING_TO_PERFORM;
1455 }
1456
1457 static int rootdse_rename(struct ldb_module *module, struct ldb_request *req)
1458 {
1459         struct ldb_context *ldb = ldb_module_get_ctx(module);
1460         int ret;
1461
1462         ret = rootdse_filter_operations(module, req);
1463         if (ret != LDB_SUCCESS) {
1464                 return ret;
1465         }
1466
1467         ret = rootdse_filter_controls(module, req);
1468         if (ret != LDB_SUCCESS) {
1469                 return ret;
1470         }
1471
1472         /*
1473                 If dn is not "" we should let it pass through
1474         */
1475         if (!ldb_dn_is_null(req->op.rename.olddn)) {
1476                 return ldb_next_request(module, req);
1477         }
1478
1479         ldb_set_errstring(ldb, "rootdse_remove: you cannot rename the rootdse entry!");
1480         return LDB_ERR_NO_SUCH_OBJECT;
1481 }
1482
1483 static int rootdse_delete(struct ldb_module *module, struct ldb_request *req)
1484 {
1485         struct ldb_context *ldb = ldb_module_get_ctx(module);
1486         int ret;
1487
1488         ret = rootdse_filter_operations(module, req);
1489         if (ret != LDB_SUCCESS) {
1490                 return ret;
1491         }
1492
1493         ret = rootdse_filter_controls(module, req);
1494         if (ret != LDB_SUCCESS) {
1495                 return ret;
1496         }
1497
1498         /*
1499                 If dn is not "" we should let it pass through
1500         */
1501         if (!ldb_dn_is_null(req->op.del.dn)) {
1502                 return ldb_next_request(module, req);
1503         }
1504
1505         ldb_set_errstring(ldb, "rootdse_remove: you cannot delete the rootdse entry!");
1506         return LDB_ERR_NO_SUCH_OBJECT;
1507 }
1508
1509 static int rootdse_extended(struct ldb_module *module, struct ldb_request *req)
1510 {
1511         int ret;
1512
1513         ret = rootdse_filter_operations(module, req);
1514         if (ret != LDB_SUCCESS) {
1515                 return ret;
1516         }
1517
1518         ret = rootdse_filter_controls(module, req);
1519         if (ret != LDB_SUCCESS) {
1520                 return ret;
1521         }
1522
1523         return ldb_next_request(module, req);
1524 }
1525
1526 static const struct ldb_module_ops ldb_rootdse_module_ops = {
1527         .name           = "rootdse",
1528         .init_context   = rootdse_init,
1529         .search         = rootdse_search,
1530         .request        = rootdse_request,
1531         .add            = rootdse_add,
1532         .modify         = rootdse_modify,
1533         .rename         = rootdse_rename,
1534         .extended       = rootdse_extended,
1535         .del            = rootdse_delete
1536 };
1537
1538 int ldb_rootdse_module_init(const char *version)
1539 {
1540         LDB_MODULE_CHECK_VERSION(version);
1541         return ldb_register_module(&ldb_rootdse_module_ops);
1542 }