s4:rootdse LDB module - introduce dynamic "ldapServiceName"
[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
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "lib/ldb/include/ldb.h"
25 #include "lib/ldb/include/ldb_module.h"
26 #include "system/time.h"
27 #include "dsdb/samdb/samdb.h"
28 #include "version.h"
29 #include "dsdb/samdb/ldb_modules/util.h"
30 #include "libcli/security/security.h"
31 #include "librpc/ndr/libndr.h"
32 #include "auth/auth.h"
33 #include "param/param.h"
34 #include "lib/messaging/irpc.h"
35 #include "librpc/gen_ndr/ndr_irpc_c.h"
36
37 struct private_data {
38         unsigned int num_controls;
39         char **controls;
40         unsigned int num_partitions;
41         struct ldb_dn **partitions;
42 };
43
44 /*
45   return 1 if a specific attribute has been requested
46 */
47 static int do_attribute(const char * const *attrs, const char *name)
48 {
49         return attrs == NULL ||
50                 ldb_attr_in_list(attrs, name) ||
51                 ldb_attr_in_list(attrs, "*");
52 }
53
54 static int do_attribute_explicit(const char * const *attrs, const char *name)
55 {
56         return attrs != NULL && ldb_attr_in_list(attrs, name);
57 }
58
59
60 /*
61   expand a DN attribute to include extended DN information if requested
62  */
63 static int expand_dn_in_message(struct ldb_module *module, struct ldb_message *msg,
64                                 const char *attrname, struct ldb_control *edn_control,
65                                 struct ldb_request *req)
66 {
67         struct ldb_dn *dn, *dn2;
68         struct ldb_val *v;
69         int ret;
70         struct ldb_request *req2;
71         char *dn_string;
72         const char *no_attrs[] = { NULL };
73         struct ldb_result *res;
74         struct ldb_extended_dn_control *edn;
75         TALLOC_CTX *tmp_ctx = talloc_new(req);
76         struct ldb_context *ldb;
77         int edn_type = 0;
78
79         ldb = ldb_module_get_ctx(module);
80
81         edn = talloc_get_type(edn_control->data, struct ldb_extended_dn_control);
82         if (edn) {
83                 edn_type = edn->type;
84         }
85
86         v = discard_const_p(struct ldb_val, ldb_msg_find_ldb_val(msg, attrname));
87         if (v == NULL) {
88                 talloc_free(tmp_ctx);
89                 return LDB_SUCCESS;
90         }
91
92         dn_string = talloc_strndup(tmp_ctx, (const char *)v->data, v->length);
93         if (dn_string == NULL) {
94                 talloc_free(tmp_ctx);
95                 return ldb_operr(ldb);
96         }
97
98         res = talloc_zero(tmp_ctx, struct ldb_result);
99         if (res == NULL) {
100                 talloc_free(tmp_ctx);
101                 return ldb_operr(ldb);
102         }
103
104         dn = ldb_dn_new(tmp_ctx, ldb, dn_string);
105         if (!ldb_dn_validate(dn)) {
106                 talloc_free(tmp_ctx);
107                 return ldb_operr(ldb);
108         }
109
110         ret = ldb_build_search_req(&req2, ldb, tmp_ctx,
111                                    dn,
112                                    LDB_SCOPE_BASE,
113                                    NULL,
114                                    no_attrs,
115                                    NULL,
116                                    res, ldb_search_default_callback,
117                                    req);
118         if (ret != LDB_SUCCESS) {
119                 talloc_free(tmp_ctx);
120                 return ret;
121         }
122
123
124         ret = ldb_request_add_control(req2,
125                                       LDB_CONTROL_EXTENDED_DN_OID,
126                                       edn_control->critical, edn);
127         if (ret != LDB_SUCCESS) {
128                 talloc_free(tmp_ctx);
129                 return ret;
130         }
131
132         ret = ldb_next_request(module, req2);
133         if (ret == LDB_SUCCESS) {
134                 ret = ldb_wait(req2->handle, LDB_WAIT_ALL);
135         }
136         if (ret != LDB_SUCCESS) {
137                 talloc_free(tmp_ctx);
138                 return ret;
139         }
140
141         if (!res || res->count != 1) {
142                 talloc_free(tmp_ctx);
143                 return ldb_operr(ldb);
144         }
145
146         dn2 = res->msgs[0]->dn;
147
148         v->data = (uint8_t *)ldb_dn_get_extended_linearized(msg->elements, dn2, edn_type);
149         if (v->data == NULL) {
150                 talloc_free(tmp_ctx);
151                 return ldb_operr(ldb);
152         }
153         v->length = strlen((char *)v->data);
154
155
156         talloc_free(tmp_ctx);
157
158         return LDB_SUCCESS;
159 }
160
161
162 /*
163   add dynamically generated attributes to rootDSE result
164 */
165 static int rootdse_add_dynamic(struct ldb_module *module, struct ldb_message *msg,
166                                const char * const *attrs, struct ldb_request *req)
167 {
168         struct ldb_context *ldb;
169         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
170         char **server_sasl;
171         const struct dsdb_schema *schema;
172         int *val;
173         struct ldb_control *edn_control;
174         const char *dn_attrs[] = {
175                 "configurationNamingContext",
176                 "defaultNamingContext",
177                 "dsServiceName",
178                 "rootDomainNamingContext",
179                 "schemaNamingContext",
180                 "serverName",
181                 NULL
182         };
183
184         ldb = ldb_module_get_ctx(module);
185         schema = dsdb_get_schema(ldb, NULL);
186
187         msg->dn = ldb_dn_new(msg, ldb, NULL);
188
189         /* don't return the distinguishedName, cn and name attributes */
190         ldb_msg_remove_attr(msg, "distinguishedName");
191         ldb_msg_remove_attr(msg, "cn");
192         ldb_msg_remove_attr(msg, "name");
193
194         if (do_attribute(attrs, "serverName")) {
195                 if (ldb_msg_add_linearized_dn(msg, "serverName",
196                         samdb_server_dn(ldb, msg)) != LDB_SUCCESS) {
197                         goto failed;
198                 }
199         }
200
201         if (do_attribute(attrs, "dnsHostName")) {
202                 if (ldb_msg_add_string(msg, "dnsHostName",
203                         samdb_search_string(ldb, msg, samdb_server_dn(ldb, msg),
204                                             "dNSHostName", NULL)) != LDB_SUCCESS) {
205                         goto failed;
206                 }
207         }
208
209         if (do_attribute(attrs, "ldapServiceName")) {
210                 struct loadparm_context *lp_ctx
211                         = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
212                                           struct loadparm_context);
213                 char *ldap_service_name, *hostname;
214
215                 hostname = talloc_strdup(msg, lpcfg_netbios_name(lp_ctx));
216                 if (hostname == NULL) {
217                         goto failed;
218                 }
219                 strlower_m(hostname);
220
221                 ldap_service_name = talloc_asprintf(msg, "%s:%s$@%s",
222                                                     samdb_forest_name(ldb, msg),
223                                                     hostname, lpcfg_realm(lp_ctx));
224                 if (ldap_service_name == NULL) {
225                         goto failed;
226                 }
227
228                 if (ldb_msg_add_string(msg, "ldapServiceName",
229                                        ldap_service_name) != LDB_SUCCESS) {
230                         goto failed;
231                 }
232         }
233
234         if (do_attribute(attrs, "currentTime")) {
235                 if (ldb_msg_add_steal_string(msg, "currentTime",
236                                              ldb_timestring(msg, time(NULL))) != LDB_SUCCESS) {
237                         goto failed;
238                 }
239         }
240
241         if (priv && do_attribute(attrs, "supportedControl")) {
242                 unsigned int i;
243                 for (i = 0; i < priv->num_controls; i++) {
244                         char *control = talloc_strdup(msg, priv->controls[i]);
245                         if (!control) {
246                                 goto failed;
247                         }
248                         if (ldb_msg_add_steal_string(msg, "supportedControl",
249                                                      control) != LDB_SUCCESS) {
250                                 goto failed;
251                         }
252                 }
253         }
254
255         if (priv && do_attribute(attrs, "namingContexts")) {
256                 unsigned int i;
257                 for (i = 0; i < priv->num_partitions; i++) {
258                         struct ldb_dn *dn = priv->partitions[i];
259                         if (ldb_msg_add_steal_string(msg, "namingContexts",
260                                                      ldb_dn_alloc_linearized(msg, dn)) != LDB_SUCCESS) {
261                                 goto failed;
262                         }
263                 }
264         }
265
266         server_sasl = talloc_get_type(ldb_get_opaque(ldb, "supportedSASLMechanisms"),
267                                        char *);
268         if (server_sasl && do_attribute(attrs, "supportedSASLMechanisms")) {
269                 unsigned int i;
270                 for (i = 0; server_sasl && server_sasl[i]; i++) {
271                         char *sasl_name = talloc_strdup(msg, server_sasl[i]);
272                         if (!sasl_name) {
273                                 goto failed;
274                         }
275                         if (ldb_msg_add_steal_string(msg, "supportedSASLMechanisms",
276                                                      sasl_name) != LDB_SUCCESS) {
277                                 goto failed;
278                         }
279                 }
280         }
281
282         if (do_attribute(attrs, "highestCommittedUSN")) {
283                 uint64_t seq_num;
284                 int ret = ldb_sequence_number(ldb, LDB_SEQ_HIGHEST_SEQ, &seq_num);
285                 if (ret == LDB_SUCCESS) {
286                         if (ldb_msg_add_fmt(msg, "highestCommittedUSN",
287                                             "%llu", (unsigned long long)seq_num) != LDB_SUCCESS) {
288                                 goto failed;
289                         }
290                 }
291         }
292
293         if (schema && do_attribute_explicit(attrs, "dsSchemaAttrCount")) {
294                 struct dsdb_attribute *cur;
295                 unsigned int n = 0;
296
297                 for (cur = schema->attributes; cur; cur = cur->next) {
298                         n++;
299                 }
300
301                 if (ldb_msg_add_fmt(msg, "dsSchemaAttrCount",
302                                     "%u", n) != LDB_SUCCESS) {
303                         goto failed;
304                 }
305         }
306
307         if (schema && do_attribute_explicit(attrs, "dsSchemaClassCount")) {
308                 struct dsdb_class *cur;
309                 unsigned int n = 0;
310
311                 for (cur = schema->classes; cur; cur = cur->next) {
312                         n++;
313                 }
314
315                 if (ldb_msg_add_fmt(msg, "dsSchemaClassCount",
316                                     "%u", n) != LDB_SUCCESS) {
317                         goto failed;
318                 }
319         }
320
321         if (schema && do_attribute_explicit(attrs, "dsSchemaPrefixCount")) {
322                 if (ldb_msg_add_fmt(msg, "dsSchemaPrefixCount",
323                                     "%u", schema->prefixmap->length) != LDB_SUCCESS) {
324                         goto failed;
325                 }
326         }
327
328         if (do_attribute_explicit(attrs, "validFSMOs")) {
329                 const struct dsdb_naming_fsmo *naming_fsmo;
330                 const struct dsdb_pdc_fsmo *pdc_fsmo;
331                 const char *dn_str;
332
333                 if (schema && schema->fsmo.we_are_master) {
334                         dn_str = ldb_dn_get_linearized(ldb_get_schema_basedn(ldb));
335                         if (dn_str && dn_str[0]) {
336                                 if (ldb_msg_add_fmt(msg, "validFSMOs", "%s", dn_str) != LDB_SUCCESS) {
337                                         goto failed;
338                                 }
339                         }
340                 }
341
342                 naming_fsmo = talloc_get_type(ldb_get_opaque(ldb, "dsdb_naming_fsmo"),
343                                               struct dsdb_naming_fsmo);
344                 if (naming_fsmo && naming_fsmo->we_are_master) {
345                         dn_str = ldb_dn_get_linearized(samdb_partitions_dn(ldb, msg));
346                         if (dn_str && dn_str[0]) {
347                                 if (ldb_msg_add_fmt(msg, "validFSMOs", "%s", dn_str) != LDB_SUCCESS) {
348                                         goto failed;
349                                 }
350                         }
351                 }
352
353                 pdc_fsmo = talloc_get_type(ldb_get_opaque(ldb, "dsdb_pdc_fsmo"),
354                                            struct dsdb_pdc_fsmo);
355                 if (pdc_fsmo && pdc_fsmo->we_are_master) {
356                         dn_str = ldb_dn_get_linearized(ldb_get_default_basedn(ldb));
357                         if (dn_str && dn_str[0]) {
358                                 if (ldb_msg_add_fmt(msg, "validFSMOs", "%s", dn_str) != LDB_SUCCESS) {
359                                         goto failed;
360                                 }
361                         }
362                 }
363         }
364
365         if (do_attribute_explicit(attrs, "vendorVersion")) {
366                 if (ldb_msg_add_fmt(msg, "vendorVersion",
367                                     "%s", SAMBA_VERSION_STRING) != LDB_SUCCESS) {
368                         goto failed;
369                 }
370         }
371
372         if (do_attribute(attrs, "domainFunctionality")) {
373                 if (ldb_msg_add_fmt(msg, "domainFunctionality",
374                                     "%d", dsdb_functional_level(ldb)) != LDB_SUCCESS) {
375                         goto failed;
376                 }
377         }
378
379         if (do_attribute(attrs, "forestFunctionality")
380             && (val = talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int))) {
381                 if (ldb_msg_add_fmt(msg, "forestFunctionality",
382                                     "%d", *val) != LDB_SUCCESS) {
383                         goto failed;
384                 }
385         }
386
387         if (do_attribute(attrs, "domainControllerFunctionality")
388             && (val = talloc_get_type(ldb_get_opaque(ldb, "domainControllerFunctionality"), int))) {
389                 if (ldb_msg_add_fmt(msg, "domainControllerFunctionality",
390                                     "%d", *val) != LDB_SUCCESS) {
391                         goto failed;
392                 }
393         }
394
395         if (do_attribute(attrs, "isGlobalCatalogReady")) {
396                 /* MS-ADTS 3.1.1.3.2.10
397                    Note, we should only return true here is we have
398                    completed at least one synchronisation. As both
399                    provision and vampire do a full sync, this means we
400                    can return true is the gc bit is set in the NTDSDSA
401                    options */
402                 if (ldb_msg_add_fmt(msg, "isGlobalCatalogReady",
403                                     "%s", samdb_is_gc(ldb)?"TRUE":"FALSE") != LDB_SUCCESS) {
404                         goto failed;
405                 }
406         }
407
408         if (do_attribute_explicit(attrs, "tokenGroups")) {
409                 unsigned int i;
410                 /* Obtain the user's session_info */
411                 struct auth_session_info *session_info
412                         = (struct auth_session_info *)ldb_get_opaque(ldb, "sessionInfo");
413                 if (session_info && session_info->security_token) {
414                         /* The list of groups this user is in */
415                         for (i = 0; i < session_info->security_token->num_sids; i++) {
416                                 if (samdb_msg_add_dom_sid(ldb, msg, msg,
417                                                           "tokenGroups",
418                                                           &session_info->security_token->sids[i]) != LDB_SUCCESS) {
419                                         goto failed;
420                                 }
421                         }
422                 }
423         }
424
425         /* TODO: lots more dynamic attributes should be added here */
426
427         edn_control = ldb_request_get_control(req, LDB_CONTROL_EXTENDED_DN_OID);
428
429         /* if the client sent us the EXTENDED_DN control then we need
430            to expand the DNs to have GUID and SID. W2K8 join relies on
431            this */
432         if (edn_control) {
433                 unsigned int i;
434                 int ret;
435                 for (i=0; dn_attrs[i]; i++) {
436                         if (!do_attribute(attrs, dn_attrs[i])) continue;
437                         ret = expand_dn_in_message(module, msg, dn_attrs[i],
438                                                    edn_control, req);
439                         if (ret != LDB_SUCCESS) {
440                                 DEBUG(0,(__location__ ": Failed to expand DN in rootDSE for %s\n",
441                                          dn_attrs[i]));
442                                 goto failed;
443                         }
444                 }
445         }
446
447         return LDB_SUCCESS;
448
449 failed:
450         return ldb_operr(ldb);
451 }
452
453 /*
454   handle search requests
455 */
456
457 struct rootdse_context {
458         struct ldb_module *module;
459         struct ldb_request *req;
460 };
461
462 static struct rootdse_context *rootdse_init_context(struct ldb_module *module,
463                                                     struct ldb_request *req)
464 {
465         struct ldb_context *ldb;
466         struct rootdse_context *ac;
467
468         ldb = ldb_module_get_ctx(module);
469
470         ac = talloc_zero(req, struct rootdse_context);
471         if (ac == NULL) {
472                 ldb_set_errstring(ldb, "Out of Memory");
473                 return NULL;
474         }
475
476         ac->module = module;
477         ac->req = req;
478
479         return ac;
480 }
481
482 static int rootdse_callback(struct ldb_request *req, struct ldb_reply *ares)
483 {
484         struct rootdse_context *ac;
485         int ret;
486
487         ac = talloc_get_type(req->context, struct rootdse_context);
488
489         if (!ares) {
490                 return ldb_module_done(ac->req, NULL, NULL,
491                                         LDB_ERR_OPERATIONS_ERROR);
492         }
493         if (ares->error != LDB_SUCCESS) {
494                 return ldb_module_done(ac->req, ares->controls,
495                                         ares->response, ares->error);
496         }
497
498         switch (ares->type) {
499         case LDB_REPLY_ENTRY:
500                 /*
501                  * if the client explicit asks for the 'netlogon' attribute
502                  * the reply_entry needs to be skipped
503                  */
504                 if (ac->req->op.search.attrs &&
505                     ldb_attr_in_list(ac->req->op.search.attrs, "netlogon")) {
506                         talloc_free(ares);
507                         return LDB_SUCCESS;
508                 }
509
510                 /* for each record returned post-process to add any dynamic
511                    attributes that have been asked for */
512                 ret = rootdse_add_dynamic(ac->module, ares->message,
513                                           ac->req->op.search.attrs, ac->req);
514                 if (ret != LDB_SUCCESS) {
515                         talloc_free(ares);
516                         return ldb_module_done(ac->req, NULL, NULL, ret);
517                 }
518
519                 return ldb_module_send_entry(ac->req, ares->message, ares->controls);
520
521         case LDB_REPLY_REFERRAL:
522                 /* should we allow the backend to return referrals in this case
523                  * ?? */
524                 break;
525
526         case LDB_REPLY_DONE:
527                 return ldb_module_done(ac->req, ares->controls,
528                                         ares->response, ares->error);
529         }
530
531         talloc_free(ares);
532         return LDB_SUCCESS;
533 }
534
535 /*
536   mark our registered controls as non-critical in the request
537
538   This is needed as clients may mark controls as critical even if they
539   are not needed at all in a request. For example, the centrify client
540   sets the SD_FLAGS control as critical on ldap modify requests which
541   are setting the dNSHostName attribute on the machine account. That
542   request doesn't need SD_FLAGS at all, but centrify adds it on all
543   ldap requests.
544  */
545 static void rootdse_mark_noncritical(struct ldb_module *module, struct ldb_control **controls)
546 {
547         unsigned int i, j;
548         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
549
550         if (!controls) return;
551
552         for (i=0; controls[i]; i++) {
553                 if (controls[i]->critical == 0) {
554                         continue;
555                 }
556                 for (j=0; j<priv->num_controls; j++) {
557                         if (strcasecmp(priv->controls[j], controls[i]->oid) == 0) {
558                                 controls[i]->critical = 0;
559                         }
560                 }
561         }
562 }
563
564 static int rootdse_search(struct ldb_module *module, struct ldb_request *req)
565 {
566         struct ldb_context *ldb;
567         struct rootdse_context *ac;
568         struct ldb_request *down_req;
569         int ret;
570
571         rootdse_mark_noncritical(module, req->controls);
572
573         ldb = ldb_module_get_ctx(module);
574
575         /* see if its for the rootDSE - only a base search on the "" DN qualifies */
576         if (!(req->op.search.scope == LDB_SCOPE_BASE && ldb_dn_is_null(req->op.search.base))) {
577                 /* Otherwise, pass down to the rest of the stack */
578                 return ldb_next_request(module, req);
579         }
580
581         ac = rootdse_init_context(module, req);
582         if (ac == NULL) {
583                 return ldb_operr(ldb);
584         }
585
586         /* in our db we store the rootDSE with a DN of @ROOTDSE */
587         ret = ldb_build_search_req(&down_req, ldb, ac,
588                                         ldb_dn_new(ac, ldb, "@ROOTDSE"),
589                                         LDB_SCOPE_BASE,
590                                         NULL,
591                                         req->op.search.attrs,
592                                         NULL,/* for now skip the controls from the client */
593                                         ac, rootdse_callback,
594                                         req);
595         if (ret != LDB_SUCCESS) {
596                 return ret;
597         }
598
599         return ldb_next_request(module, down_req);
600 }
601
602 static int rootdse_register_control(struct ldb_module *module, struct ldb_request *req)
603 {
604         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
605         char **list;
606
607         list = talloc_realloc(priv, priv->controls, char *, priv->num_controls + 1);
608         if (!list) {
609                 return ldb_oom(ldb_module_get_ctx(module));
610         }
611
612         list[priv->num_controls] = talloc_strdup(list, req->op.reg_control.oid);
613         if (!list[priv->num_controls]) {
614                 return ldb_oom(ldb_module_get_ctx(module));
615         }
616
617         priv->num_controls += 1;
618         priv->controls = list;
619
620         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
621 }
622
623 static int rootdse_register_partition(struct ldb_module *module, struct ldb_request *req)
624 {
625         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
626         struct ldb_dn **list;
627
628         list = talloc_realloc(priv, priv->partitions, struct ldb_dn *, priv->num_partitions + 1);
629         if (!list) {
630                 return ldb_oom(ldb_module_get_ctx(module));
631         }
632
633         list[priv->num_partitions] = ldb_dn_copy(list, req->op.reg_partition.dn);
634         if (!list[priv->num_partitions]) {
635                 return ldb_operr(ldb_module_get_ctx(module));
636         }
637
638         priv->num_partitions += 1;
639         priv->partitions = list;
640
641         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
642 }
643
644
645 static int rootdse_request(struct ldb_module *module, struct ldb_request *req)
646 {
647         switch (req->operation) {
648
649         case LDB_REQ_REGISTER_CONTROL:
650                 return rootdse_register_control(module, req);
651         case LDB_REQ_REGISTER_PARTITION:
652                 return rootdse_register_partition(module, req);
653
654         default:
655                 break;
656         }
657         return ldb_next_request(module, req);
658 }
659
660 static int rootdse_init(struct ldb_module *module)
661 {
662         int ret;
663         struct ldb_context *ldb;
664         struct ldb_result *res;
665         struct private_data *data;
666         const char *attrs[] = { "msDS-Behavior-Version", NULL };
667         const char *ds_attrs[] = { "dsServiceName", NULL };
668         TALLOC_CTX *mem_ctx;
669
670         ldb = ldb_module_get_ctx(module);
671
672         data = talloc_zero(module, struct private_data);
673         if (data == NULL) {
674                 return ldb_oom(ldb);
675         }
676
677         data->num_controls = 0;
678         data->controls = NULL;
679         data->num_partitions = 0;
680         data->partitions = NULL;
681         ldb_module_set_private(module, data);
682
683         ldb_set_default_dns(ldb);
684
685         ret = ldb_next_init(module);
686
687         if (ret != LDB_SUCCESS) {
688                 return ret;
689         }
690
691         mem_ctx = talloc_new(data);
692         if (!mem_ctx) {
693                 return ldb_oom(ldb);
694         }
695
696         /* Now that the partitions are set up, do a search for:
697            - domainControllerFunctionality
698            - domainFunctionality
699            - forestFunctionality
700
701            Then stuff these values into an opaque
702         */
703         ret = ldb_search(ldb, mem_ctx, &res,
704                          ldb_get_default_basedn(ldb),
705                          LDB_SCOPE_BASE, attrs, NULL);
706         if (ret == LDB_SUCCESS && res->count == 1) {
707                 int domain_behaviour_version
708                         = ldb_msg_find_attr_as_int(res->msgs[0],
709                                                    "msDS-Behavior-Version", -1);
710                 if (domain_behaviour_version != -1) {
711                         int *val = talloc(ldb, int);
712                         if (!val) {
713                                 talloc_free(mem_ctx);
714                                 return ldb_oom(ldb);
715                         }
716                         *val = domain_behaviour_version;
717                         ret = ldb_set_opaque(ldb, "domainFunctionality", val);
718                         if (ret != LDB_SUCCESS) {
719                                 talloc_free(mem_ctx);
720                                 return ret;
721                         }
722                 }
723         }
724
725         ret = ldb_search(ldb, mem_ctx, &res,
726                          samdb_partitions_dn(ldb, mem_ctx),
727                          LDB_SCOPE_BASE, attrs, NULL);
728         if (ret == LDB_SUCCESS && res->count == 1) {
729                 int forest_behaviour_version
730                         = ldb_msg_find_attr_as_int(res->msgs[0],
731                                                    "msDS-Behavior-Version", -1);
732                 if (forest_behaviour_version != -1) {
733                         int *val = talloc(ldb, int);
734                         if (!val) {
735                                 talloc_free(mem_ctx);
736                                 return ldb_oom(ldb);
737                         }
738                         *val = forest_behaviour_version;
739                         ret = ldb_set_opaque(ldb, "forestFunctionality", val);
740                         if (ret != LDB_SUCCESS) {
741                                 talloc_free(mem_ctx);
742                                 return ret;
743                         }
744                 }
745         }
746
747         ret = ldb_search(ldb, mem_ctx, &res,
748                          ldb_dn_new(mem_ctx, ldb, ""),
749                          LDB_SCOPE_BASE, ds_attrs, NULL);
750         if (ret == LDB_SUCCESS && res->count == 1) {
751                 struct ldb_dn *ds_dn
752                         = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0],
753                                                   "dsServiceName");
754                 if (ds_dn) {
755                         ret = ldb_search(ldb, mem_ctx, &res, ds_dn,
756                                          LDB_SCOPE_BASE, attrs, NULL);
757                         if (ret == LDB_SUCCESS && res->count == 1) {
758                                 int domain_controller_behaviour_version
759                                         = ldb_msg_find_attr_as_int(res->msgs[0],
760                                                                    "msDS-Behavior-Version", -1);
761                                 if (domain_controller_behaviour_version != -1) {
762                                         int *val = talloc(ldb, int);
763                                         if (!val) {
764                                                 talloc_free(mem_ctx);
765                                                 return ldb_oom(ldb);
766                                         }
767                                         *val = domain_controller_behaviour_version;
768                                         ret = ldb_set_opaque(ldb,
769                                                              "domainControllerFunctionality", val);
770                                         if (ret != LDB_SUCCESS) {
771                                                 talloc_free(mem_ctx);
772                                                 return ret;
773                                         }
774                                 }
775                         }
776                 }
777         }
778
779         talloc_free(mem_ctx);
780
781         return LDB_SUCCESS;
782 }
783
784 /*
785  * This function gets the string SCOPE_DN:OPTIONAL_FEATURE_GUID and parse it
786  * to a DN and a GUID object
787  */
788 static int get_optional_feature_dn_guid(struct ldb_request *req, struct ldb_context *ldb,
789                                                 TALLOC_CTX *mem_ctx,
790                                                 struct ldb_dn **op_feature_scope_dn,
791                                                 struct GUID *op_feature_guid)
792 {
793         const struct ldb_message *msg = req->op.mod.message;
794         const char *ldb_val_str;
795         char *dn, *guid;
796         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
797         NTSTATUS status;
798
799         ldb_val_str = ldb_msg_find_attr_as_string(msg, "enableOptionalFeature", NULL);
800         if (!ldb_val_str) {
801                 ldb_set_errstring(ldb,
802                                   "rootdse: unable to find 'enableOptionalFeature'!");
803                 return LDB_ERR_UNWILLING_TO_PERFORM;
804         }
805
806         guid = strchr(ldb_val_str, ':');
807         if (!guid) {
808                 ldb_set_errstring(ldb,
809                                   "rootdse: unable to find GUID in 'enableOptionalFeature'!");
810                 return LDB_ERR_UNWILLING_TO_PERFORM;
811         }
812         status = GUID_from_string(guid+1, op_feature_guid);
813         if (!NT_STATUS_IS_OK(status)) {
814                 ldb_set_errstring(ldb,
815                                   "rootdse: bad GUID in 'enableOptionalFeature'!");
816                 return LDB_ERR_UNWILLING_TO_PERFORM;
817         }
818
819         dn = talloc_strndup(tmp_ctx, ldb_val_str, guid-ldb_val_str);
820         if (!dn) {
821                 ldb_set_errstring(ldb,
822                                   "rootdse: bad DN in 'enableOptionalFeature'!");
823                 return LDB_ERR_UNWILLING_TO_PERFORM;
824         }
825
826         *op_feature_scope_dn = ldb_dn_new(mem_ctx, ldb, dn);
827
828         talloc_free(tmp_ctx);
829         return LDB_SUCCESS;
830 }
831
832 /*
833  * This function gets the OPTIONAL_FEATURE_GUID and looks for the optional feature
834  * ldb_message object.
835  */
836 static int dsdb_find_optional_feature(struct ldb_module *module, struct ldb_context *ldb,
837                                 TALLOC_CTX *mem_ctx, struct GUID op_feature_guid, struct ldb_message **msg)
838 {
839         struct ldb_result *res;
840         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
841         int ret;
842
843         ret = dsdb_module_search(module, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE,
844                                 NULL,
845                                 DSDB_FLAG_NEXT_MODULE |
846                                 DSDB_SEARCH_SEARCH_ALL_PARTITIONS,
847                                  "(&(objectClass=msDS-OptionalFeature)"
848                                  "(msDS-OptionalFeatureGUID=%s))",GUID_string(tmp_ctx, &op_feature_guid));
849
850         if (ret != LDB_SUCCESS) {
851                 talloc_free(tmp_ctx);
852                 return ret;
853         }
854         if (res->count == 0) {
855                 talloc_free(tmp_ctx);
856                 return LDB_ERR_NO_SUCH_OBJECT;
857         }
858         if (res->count != 1) {
859                 ldb_asprintf_errstring(ldb,
860                                        "More than one object found matching optional feature GUID %s\n",
861                                        GUID_string(tmp_ctx, &op_feature_guid));
862                 talloc_free(tmp_ctx);
863                 return LDB_ERR_OPERATIONS_ERROR;
864         }
865
866         *msg = talloc_steal(mem_ctx, res->msgs[0]);
867
868         talloc_free(tmp_ctx);
869         return LDB_SUCCESS;
870 }
871
872 static int rootdse_enable_recycle_bin(struct ldb_module *module,struct ldb_context *ldb,
873                         TALLOC_CTX *mem_ctx, struct ldb_dn *op_feature_scope_dn,
874                         struct ldb_message *op_feature_msg)
875 {
876         int ret;
877         const int domain_func_level = dsdb_functional_level(ldb);
878         struct ldb_dn *ntds_settings_dn;
879         TALLOC_CTX *tmp_ctx;
880         unsigned int el_count = 0;
881         struct ldb_message *msg;
882
883         ret = ldb_msg_find_attr_as_int(op_feature_msg, "msDS-RequiredForestBehaviorVersion", 0);
884         if (domain_func_level < ret){
885                 ldb_asprintf_errstring(ldb,
886                                        "rootdse_enable_recycle_bin: Domain functional level must be at least %d\n",
887                                        ret);
888                 return LDB_ERR_UNWILLING_TO_PERFORM;
889         }
890
891         tmp_ctx = talloc_new(mem_ctx);
892         ntds_settings_dn = samdb_ntds_settings_dn(ldb);
893         if (!ntds_settings_dn) {
894                 DEBUG(0, (__location__ ": Failed to find NTDS settings DN\n"));
895                 ret = LDB_ERR_OPERATIONS_ERROR;
896                 talloc_free(tmp_ctx);
897                 return ret;
898         }
899
900         ntds_settings_dn = ldb_dn_copy(tmp_ctx, ntds_settings_dn);
901         if (!ntds_settings_dn) {
902                 DEBUG(0, (__location__ ": Failed to copy NTDS settings DN\n"));
903                 ret = LDB_ERR_OPERATIONS_ERROR;
904                 talloc_free(tmp_ctx);
905                 return ret;
906         }
907
908         msg = ldb_msg_new(tmp_ctx);
909         msg->dn = ntds_settings_dn;
910
911         ldb_msg_add_linearized_dn(msg, "msDS-EnabledFeature", op_feature_msg->dn);
912         msg->elements[el_count++].flags = LDB_FLAG_MOD_ADD;
913
914         ret = dsdb_module_modify(module, msg, DSDB_FLAG_NEXT_MODULE);
915         if (ret != LDB_SUCCESS) {
916                 ldb_asprintf_errstring(ldb,
917                                        "rootdse_enable_recycle_bin: Failed to modify object %s - %s",
918                                        ldb_dn_get_linearized(ntds_settings_dn),
919                                        ldb_errstring(ldb));
920                 talloc_free(tmp_ctx);
921                 return ret;
922         }
923
924         msg->dn = op_feature_scope_dn;
925         ret = dsdb_module_modify(module, msg, DSDB_FLAG_NEXT_MODULE);
926         if (ret != LDB_SUCCESS) {
927                 ldb_asprintf_errstring(ldb,
928                                        "rootdse_enable_recycle_bin: Failed to modify object %s - %s",
929                                        ldb_dn_get_linearized(op_feature_scope_dn),
930                                        ldb_errstring(ldb));
931                 talloc_free(tmp_ctx);
932                 return ret;
933         }
934
935         return LDB_SUCCESS;
936 }
937
938 static int rootdse_enableoptionalfeature(struct ldb_module *module, struct ldb_request *req)
939 {
940         /*
941           steps:
942                - check for system (only system can enable features)
943                - extract GUID from the request
944                - find the feature object
945                - check functional level, must be at least msDS-RequiredForestBehaviorVersion
946                - check if it is already enabled (if enabled return LDAP_ATTRIBUTE_OR_VALUE_EXISTS) - probably not needed, just return error from the add/modify
947                - add/modify objects (see ntdsconnection code for an example)
948          */
949
950         struct ldb_context *ldb = ldb_module_get_ctx(module);
951         struct GUID op_feature_guid;
952         struct ldb_dn *op_feature_scope_dn;
953         struct ldb_message *op_feature_msg;
954         struct auth_session_info *session_info =
955                                 (struct auth_session_info *)ldb_get_opaque(ldb, "sessionInfo");
956         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
957         int ret;
958         const char *guid_string;
959
960         if (security_session_user_level(session_info, NULL) != SECURITY_SYSTEM) {
961                 ldb_set_errstring(ldb, "rootdse: Insufficient rights for enableoptionalfeature");
962                 return LDB_ERR_UNWILLING_TO_PERFORM;
963         }
964
965         ret = get_optional_feature_dn_guid(req, ldb, tmp_ctx, &op_feature_scope_dn, &op_feature_guid);
966         if (ret != LDB_SUCCESS) {
967                 talloc_free(tmp_ctx);
968                 return ret;
969         }
970
971         guid_string = GUID_string(tmp_ctx, &op_feature_guid);
972         if (!guid_string) {
973                 ldb_set_errstring(ldb, "rootdse: bad optional feature GUID");
974                 return LDB_ERR_UNWILLING_TO_PERFORM;
975         }
976
977         ret = dsdb_find_optional_feature(module, ldb, tmp_ctx, op_feature_guid, &op_feature_msg);
978         if (ret != LDB_SUCCESS) {
979                 ldb_asprintf_errstring(ldb,
980                                        "rootdse: unable to find optional feature for %s - %s",
981                                        guid_string, ldb_errstring(ldb));
982                 talloc_free(tmp_ctx);
983                 return ret;
984         }
985
986         if (strcasecmp(DS_GUID_FEATURE_RECYCLE_BIN, guid_string) == 0) {
987                         ret = rootdse_enable_recycle_bin(module, ldb,
988                                                          tmp_ctx, op_feature_scope_dn,
989                                                          op_feature_msg);
990         } else {
991                 ldb_asprintf_errstring(ldb,
992                                        "rootdse: unknown optional feature %s",
993                                        guid_string);
994                 talloc_free(tmp_ctx);
995                 return LDB_ERR_UNWILLING_TO_PERFORM;
996         }
997         if (ret != LDB_SUCCESS) {
998                 ldb_asprintf_errstring(ldb,
999                                        "rootdse: failed to set optional feature for %s - %s",
1000                                        guid_string, ldb_errstring(ldb));
1001                 talloc_free(tmp_ctx);
1002                 return ret;
1003         }
1004
1005         talloc_free(tmp_ctx);
1006         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);;
1007 }
1008
1009 static int rootdse_schemaupdatenow(struct ldb_module *module, struct ldb_request *req)
1010 {
1011         struct ldb_context *ldb = ldb_module_get_ctx(module);
1012         struct ldb_result *ext_res;
1013         int ret;
1014         struct ldb_dn *schema_dn;
1015
1016         schema_dn = ldb_get_schema_basedn(ldb);
1017         if (!schema_dn) {
1018                 ldb_reset_err_string(ldb);
1019                 ldb_debug(ldb, LDB_DEBUG_WARNING,
1020                           "rootdse_modify: no schema dn present: (skip ldb_extended call)\n");
1021                 return ldb_next_request(module, req);
1022         }
1023
1024         ret = ldb_extended(ldb, DSDB_EXTENDED_SCHEMA_UPDATE_NOW_OID, schema_dn, &ext_res);
1025         if (ret != LDB_SUCCESS) {
1026                 return ldb_operr(ldb);
1027         }
1028
1029         talloc_free(ext_res);
1030         return ldb_module_done(req, NULL, NULL, ret);
1031 }
1032
1033 static int rootdse_add(struct ldb_module *module, struct ldb_request *req)
1034 {
1035         struct ldb_context *ldb = ldb_module_get_ctx(module);
1036
1037         rootdse_mark_noncritical(module, req->controls);
1038
1039         /*
1040                 If dn is not "" we should let it pass through
1041         */
1042         if (!ldb_dn_is_null(req->op.add.message->dn)) {
1043                 return ldb_next_request(module, req);
1044         }
1045
1046         ldb_set_errstring(ldb, "rootdse_add: you cannot add a new rootdse entry!");
1047         return LDB_ERR_NAMING_VIOLATION;
1048 }
1049
1050 static int rootdse_become_master(struct ldb_module *module,
1051                                  struct ldb_request *req,
1052                                  uint32_t role)
1053 {
1054         struct drepl_takeFSMORole r;
1055         struct messaging_context *msg;
1056         struct ldb_context *ldb = ldb_module_get_ctx(module);
1057         TALLOC_CTX *tmp_ctx = talloc_new(req);
1058         struct loadparm_context *lp_ctx = ldb_get_opaque(ldb, "loadparm");
1059         NTSTATUS status_call;
1060         WERROR status_fn;
1061         struct dcerpc_binding_handle *irpc_handle;
1062
1063         msg = messaging_client_init(tmp_ctx, lpcfg_messaging_path(tmp_ctx, lp_ctx),
1064                                     ldb_get_event_context(ldb));
1065
1066         irpc_handle = irpc_binding_handle_by_name(tmp_ctx, msg,
1067                                                   "dreplsrv",
1068                                                   &ndr_table_irpc);
1069         if (irpc_handle == NULL) {
1070                 return ldb_oom(ldb);
1071         }
1072         r.in.role = role;
1073
1074         status_call = dcerpc_drepl_takeFSMORole_r(irpc_handle, tmp_ctx, &r);
1075         if (!NT_STATUS_IS_OK(status_call)) {
1076                 return LDB_ERR_OPERATIONS_ERROR;
1077         }
1078         status_fn = r.out.result;
1079         if (!W_ERROR_IS_OK(status_fn)) {
1080                 return LDB_ERR_OPERATIONS_ERROR;
1081         }
1082         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1083 }
1084
1085 static int rootdse_modify(struct ldb_module *module, struct ldb_request *req)
1086 {
1087         struct ldb_context *ldb = ldb_module_get_ctx(module);
1088
1089         rootdse_mark_noncritical(module, req->controls);
1090
1091         /*
1092                 If dn is not "" we should let it pass through
1093         */
1094         if (!ldb_dn_is_null(req->op.mod.message->dn)) {
1095                 return ldb_next_request(module, req);
1096         }
1097
1098         /*
1099                 dn is empty so check for schemaUpdateNow attribute
1100                 "The type of modification and values specified in the LDAP modify operation do not matter." MSDN
1101         */
1102         if (ldb_msg_find_element(req->op.mod.message, "schemaUpdateNow")) {
1103                 return rootdse_schemaupdatenow(module, req);
1104         }
1105         if (ldb_msg_find_element(req->op.mod.message, "becomeDomainMaster")) {
1106                 return rootdse_become_master(module, req, DREPL_NAMING_MASTER);
1107         }
1108         if (ldb_msg_find_element(req->op.mod.message, "becomeInfrastructureMaster")) {
1109                 return rootdse_become_master(module, req, DREPL_INFRASTRUCTURE_MASTER);
1110         }
1111         if (ldb_msg_find_element(req->op.mod.message, "becomeRidMaster")) {
1112                 return rootdse_become_master(module, req, DREPL_RID_MASTER);
1113         }
1114         if (ldb_msg_find_element(req->op.mod.message, "becomeSchemaMaster")) {
1115                 return rootdse_become_master(module, req, DREPL_SCHEMA_MASTER);
1116         }
1117         if (ldb_msg_find_element(req->op.mod.message, "becomePdc")) {
1118                 return rootdse_become_master(module, req, DREPL_PDC_MASTER);
1119         }
1120         if (ldb_msg_find_element(req->op.mod.message, "enableOptionalFeature")) {
1121                 return rootdse_enableoptionalfeature(module, req);
1122         }
1123
1124         ldb_set_errstring(ldb, "rootdse_modify: unknown attribute to change!");
1125         return LDB_ERR_UNWILLING_TO_PERFORM;
1126 }
1127
1128 static int rootdse_delete(struct ldb_module *module, struct ldb_request *req)
1129 {
1130         struct ldb_context *ldb = ldb_module_get_ctx(module);
1131
1132         rootdse_mark_noncritical(module, req->controls);
1133
1134         /*
1135                 If dn is not "" we should let it pass through
1136         */
1137         if (!ldb_dn_is_null(req->op.del.dn)) {
1138                 return ldb_next_request(module, req);
1139         }
1140
1141         ldb_set_errstring(ldb, "rootdse_remove: you cannot delete the rootdse entry!");
1142         return LDB_ERR_NO_SUCH_OBJECT;
1143 }
1144
1145 _PUBLIC_ const struct ldb_module_ops ldb_rootdse_module_ops = {
1146         .name           = "rootdse",
1147         .init_context   = rootdse_init,
1148         .search         = rootdse_search,
1149         .request        = rootdse_request,
1150         .add            = rootdse_add,
1151         .modify         = rootdse_modify,
1152         .del            = rootdse_delete
1153 };