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