s4-dsdb Fix segfault in error case in rootdse module
[metze/samba/wip.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         LDB_REQ_SET_LOCATION(req2);
119         if (ret != LDB_SUCCESS) {
120                 talloc_free(tmp_ctx);
121                 return ret;
122         }
123
124
125         ret = ldb_request_add_control(req2,
126                                       LDB_CONTROL_EXTENDED_DN_OID,
127                                       edn_control->critical, edn);
128         if (ret != LDB_SUCCESS) {
129                 talloc_free(tmp_ctx);
130                 return ret;
131         }
132
133         ret = ldb_next_request(module, req2);
134         if (ret == LDB_SUCCESS) {
135                 ret = ldb_wait(req2->handle, LDB_WAIT_ALL);
136         }
137         if (ret != LDB_SUCCESS) {
138                 talloc_free(tmp_ctx);
139                 return ret;
140         }
141
142         if (!res || res->count != 1) {
143                 talloc_free(tmp_ctx);
144                 return ldb_operr(ldb);
145         }
146
147         dn2 = res->msgs[0]->dn;
148
149         v->data = (uint8_t *)ldb_dn_get_extended_linearized(msg->elements, dn2, edn_type);
150         if (v->data == NULL) {
151                 talloc_free(tmp_ctx);
152                 return ldb_operr(ldb);
153         }
154         v->length = strlen((char *)v->data);
155
156
157         talloc_free(tmp_ctx);
158
159         return LDB_SUCCESS;
160 }
161
162
163 /*
164   add dynamically generated attributes to rootDSE result
165 */
166 static int rootdse_add_dynamic(struct ldb_module *module, struct ldb_message *msg,
167                                const char * const *attrs, struct ldb_request *req)
168 {
169         struct ldb_context *ldb;
170         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
171         char **server_sasl;
172         const struct dsdb_schema *schema;
173         int *val;
174         struct ldb_control *edn_control;
175         const char *dn_attrs[] = {
176                 "configurationNamingContext",
177                 "defaultNamingContext",
178                 "dsServiceName",
179                 "rootDomainNamingContext",
180                 "schemaNamingContext",
181                 "serverName",
182                 NULL
183         };
184
185         ldb = ldb_module_get_ctx(module);
186         schema = dsdb_get_schema(ldb, NULL);
187
188         msg->dn = ldb_dn_new(msg, ldb, NULL);
189
190         /* don't return the distinguishedName, cn and name attributes */
191         ldb_msg_remove_attr(msg, "distinguishedName");
192         ldb_msg_remove_attr(msg, "cn");
193         ldb_msg_remove_attr(msg, "name");
194
195         if (do_attribute(attrs, "serverName")) {
196                 if (ldb_msg_add_linearized_dn(msg, "serverName",
197                         samdb_server_dn(ldb, msg)) != LDB_SUCCESS) {
198                         goto failed;
199                 }
200         }
201
202         if (do_attribute(attrs, "dnsHostName")) {
203                 if (ldb_msg_add_string(msg, "dnsHostName",
204                         samdb_search_string(ldb, msg, samdb_server_dn(ldb, msg),
205                                             "dNSHostName", NULL)) != LDB_SUCCESS) {
206                         goto failed;
207                 }
208         }
209
210         if (do_attribute(attrs, "ldapServiceName")) {
211                 struct loadparm_context *lp_ctx
212                         = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
213                                           struct loadparm_context);
214                 char *ldap_service_name, *hostname;
215
216                 hostname = talloc_strdup(msg, lpcfg_netbios_name(lp_ctx));
217                 if (hostname == NULL) {
218                         goto failed;
219                 }
220                 strlower_m(hostname);
221
222                 ldap_service_name = talloc_asprintf(msg, "%s:%s$@%s",
223                                                     samdb_forest_name(ldb, msg),
224                                                     hostname, lpcfg_realm(lp_ctx));
225                 if (ldap_service_name == NULL) {
226                         goto failed;
227                 }
228
229                 if (ldb_msg_add_string(msg, "ldapServiceName",
230                                        ldap_service_name) != LDB_SUCCESS) {
231                         goto failed;
232                 }
233         }
234
235         if (do_attribute(attrs, "currentTime")) {
236                 if (ldb_msg_add_steal_string(msg, "currentTime",
237                                              ldb_timestring(msg, time(NULL))) != LDB_SUCCESS) {
238                         goto failed;
239                 }
240         }
241
242         if (priv && do_attribute(attrs, "supportedControl")) {
243                 unsigned int i;
244                 for (i = 0; i < priv->num_controls; i++) {
245                         char *control = talloc_strdup(msg, priv->controls[i]);
246                         if (!control) {
247                                 goto failed;
248                         }
249                         if (ldb_msg_add_steal_string(msg, "supportedControl",
250                                                      control) != LDB_SUCCESS) {
251                                 goto failed;
252                         }
253                 }
254         }
255
256         if (priv && do_attribute(attrs, "namingContexts")) {
257                 unsigned int i;
258                 for (i = 0; i < priv->num_partitions; i++) {
259                         struct ldb_dn *dn = priv->partitions[i];
260                         if (ldb_msg_add_steal_string(msg, "namingContexts",
261                                                      ldb_dn_alloc_linearized(msg, dn)) != LDB_SUCCESS) {
262                                 goto failed;
263                         }
264                 }
265         }
266
267         server_sasl = talloc_get_type(ldb_get_opaque(ldb, "supportedSASLMechanisms"),
268                                        char *);
269         if (server_sasl && do_attribute(attrs, "supportedSASLMechanisms")) {
270                 unsigned int i;
271                 for (i = 0; server_sasl && server_sasl[i]; i++) {
272                         char *sasl_name = talloc_strdup(msg, server_sasl[i]);
273                         if (!sasl_name) {
274                                 goto failed;
275                         }
276                         if (ldb_msg_add_steal_string(msg, "supportedSASLMechanisms",
277                                                      sasl_name) != LDB_SUCCESS) {
278                                 goto failed;
279                         }
280                 }
281         }
282
283         if (do_attribute(attrs, "highestCommittedUSN")) {
284                 uint64_t seq_num;
285                 int ret = ldb_sequence_number(ldb, LDB_SEQ_HIGHEST_SEQ, &seq_num);
286                 if (ret == LDB_SUCCESS) {
287                         if (ldb_msg_add_fmt(msg, "highestCommittedUSN",
288                                             "%llu", (unsigned long long)seq_num) != LDB_SUCCESS) {
289                                 goto failed;
290                         }
291                 }
292         }
293
294         if (schema && do_attribute_explicit(attrs, "dsSchemaAttrCount")) {
295                 struct dsdb_attribute *cur;
296                 unsigned int n = 0;
297
298                 for (cur = schema->attributes; cur; cur = cur->next) {
299                         n++;
300                 }
301
302                 if (ldb_msg_add_fmt(msg, "dsSchemaAttrCount",
303                                     "%u", n) != LDB_SUCCESS) {
304                         goto failed;
305                 }
306         }
307
308         if (schema && do_attribute_explicit(attrs, "dsSchemaClassCount")) {
309                 struct dsdb_class *cur;
310                 unsigned int n = 0;
311
312                 for (cur = schema->classes; cur; cur = cur->next) {
313                         n++;
314                 }
315
316                 if (ldb_msg_add_fmt(msg, "dsSchemaClassCount",
317                                     "%u", n) != LDB_SUCCESS) {
318                         goto failed;
319                 }
320         }
321
322         if (schema && do_attribute_explicit(attrs, "dsSchemaPrefixCount")) {
323                 if (ldb_msg_add_fmt(msg, "dsSchemaPrefixCount",
324                                     "%u", schema->prefixmap->length) != LDB_SUCCESS) {
325                         goto failed;
326                 }
327         }
328
329         if (do_attribute_explicit(attrs, "validFSMOs")) {
330                 const struct dsdb_naming_fsmo *naming_fsmo;
331                 const struct dsdb_pdc_fsmo *pdc_fsmo;
332                 const char *dn_str;
333
334                 if (schema && schema->fsmo.we_are_master) {
335                         dn_str = ldb_dn_get_linearized(ldb_get_schema_basedn(ldb));
336                         if (dn_str && dn_str[0]) {
337                                 if (ldb_msg_add_fmt(msg, "validFSMOs", "%s", dn_str) != LDB_SUCCESS) {
338                                         goto failed;
339                                 }
340                         }
341                 }
342
343                 naming_fsmo = talloc_get_type(ldb_get_opaque(ldb, "dsdb_naming_fsmo"),
344                                               struct dsdb_naming_fsmo);
345                 if (naming_fsmo && naming_fsmo->we_are_master) {
346                         dn_str = ldb_dn_get_linearized(samdb_partitions_dn(ldb, msg));
347                         if (dn_str && dn_str[0]) {
348                                 if (ldb_msg_add_fmt(msg, "validFSMOs", "%s", dn_str) != LDB_SUCCESS) {
349                                         goto failed;
350                                 }
351                         }
352                 }
353
354                 pdc_fsmo = talloc_get_type(ldb_get_opaque(ldb, "dsdb_pdc_fsmo"),
355                                            struct dsdb_pdc_fsmo);
356                 if (pdc_fsmo && pdc_fsmo->we_are_master) {
357                         dn_str = ldb_dn_get_linearized(ldb_get_default_basedn(ldb));
358                         if (dn_str && dn_str[0]) {
359                                 if (ldb_msg_add_fmt(msg, "validFSMOs", "%s", dn_str) != LDB_SUCCESS) {
360                                         goto failed;
361                                 }
362                         }
363                 }
364         }
365
366         if (do_attribute_explicit(attrs, "vendorVersion")) {
367                 if (ldb_msg_add_fmt(msg, "vendorVersion",
368                                     "%s", SAMBA_VERSION_STRING) != LDB_SUCCESS) {
369                         goto failed;
370                 }
371         }
372
373         if (do_attribute(attrs, "domainFunctionality")) {
374                 if (ldb_msg_add_fmt(msg, "domainFunctionality",
375                                     "%d", dsdb_functional_level(ldb)) != LDB_SUCCESS) {
376                         goto failed;
377                 }
378         }
379
380         if (do_attribute(attrs, "forestFunctionality")) {
381                 if (ldb_msg_add_fmt(msg, "forestFunctionality",
382                                     "%d", dsdb_forest_functional_level(ldb)) != 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         LDB_REQ_SET_LOCATION(down_req);
596         if (ret != LDB_SUCCESS) {
597                 return ret;
598         }
599
600         return ldb_next_request(module, down_req);
601 }
602
603 static int rootdse_register_control(struct ldb_module *module, struct ldb_request *req)
604 {
605         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
606         char **list;
607
608         list = talloc_realloc(priv, priv->controls, char *, priv->num_controls + 1);
609         if (!list) {
610                 return ldb_oom(ldb_module_get_ctx(module));
611         }
612
613         list[priv->num_controls] = talloc_strdup(list, req->op.reg_control.oid);
614         if (!list[priv->num_controls]) {
615                 return ldb_oom(ldb_module_get_ctx(module));
616         }
617
618         priv->num_controls += 1;
619         priv->controls = list;
620
621         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
622 }
623
624 static int rootdse_register_partition(struct ldb_module *module, struct ldb_request *req)
625 {
626         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
627         struct ldb_dn **list;
628
629         list = talloc_realloc(priv, priv->partitions, struct ldb_dn *, priv->num_partitions + 1);
630         if (!list) {
631                 return ldb_oom(ldb_module_get_ctx(module));
632         }
633
634         list[priv->num_partitions] = ldb_dn_copy(list, req->op.reg_partition.dn);
635         if (!list[priv->num_partitions]) {
636                 return ldb_operr(ldb_module_get_ctx(module));
637         }
638
639         priv->num_partitions += 1;
640         priv->partitions = list;
641
642         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
643 }
644
645
646 static int rootdse_request(struct ldb_module *module, struct ldb_request *req)
647 {
648         switch (req->operation) {
649
650         case LDB_REQ_REGISTER_CONTROL:
651                 return rootdse_register_control(module, req);
652         case LDB_REQ_REGISTER_PARTITION:
653                 return rootdse_register_partition(module, req);
654
655         default:
656                 break;
657         }
658         return ldb_next_request(module, req);
659 }
660
661 static int rootdse_init(struct ldb_module *module)
662 {
663         int ret;
664         struct ldb_context *ldb;
665         struct ldb_result *res;
666         struct private_data *data;
667         const char *attrs[] = { "msDS-Behavior-Version", NULL };
668         const char *ds_attrs[] = { "dsServiceName", NULL };
669         TALLOC_CTX *mem_ctx;
670
671         ldb = ldb_module_get_ctx(module);
672
673         data = talloc_zero(module, struct private_data);
674         if (data == NULL) {
675                 return ldb_oom(ldb);
676         }
677
678         data->num_controls = 0;
679         data->controls = NULL;
680         data->num_partitions = 0;
681         data->partitions = NULL;
682         ldb_module_set_private(module, data);
683
684         ldb_set_default_dns(ldb);
685
686         ret = ldb_next_init(module);
687
688         if (ret != LDB_SUCCESS) {
689                 return ret;
690         }
691
692         mem_ctx = talloc_new(data);
693         if (!mem_ctx) {
694                 return ldb_oom(ldb);
695         }
696
697         /* Now that the partitions are set up, do a search for:
698            - domainControllerFunctionality
699            - domainFunctionality
700            - forestFunctionality
701
702            Then stuff these values into an opaque
703         */
704         ret = ldb_search(ldb, mem_ctx, &res,
705                          ldb_get_default_basedn(ldb),
706                          LDB_SCOPE_BASE, attrs, NULL);
707         if (ret == LDB_SUCCESS && res->count == 1) {
708                 int domain_behaviour_version
709                         = ldb_msg_find_attr_as_int(res->msgs[0],
710                                                    "msDS-Behavior-Version", -1);
711                 if (domain_behaviour_version != -1) {
712                         int *val = talloc(ldb, int);
713                         if (!val) {
714                                 talloc_free(mem_ctx);
715                                 return ldb_oom(ldb);
716                         }
717                         *val = domain_behaviour_version;
718                         ret = ldb_set_opaque(ldb, "domainFunctionality", val);
719                         if (ret != LDB_SUCCESS) {
720                                 talloc_free(mem_ctx);
721                                 return ret;
722                         }
723                 }
724         }
725
726         ret = ldb_search(ldb, mem_ctx, &res,
727                          samdb_partitions_dn(ldb, mem_ctx),
728                          LDB_SCOPE_BASE, attrs, NULL);
729         if (ret == LDB_SUCCESS && res->count == 1) {
730                 int forest_behaviour_version
731                         = ldb_msg_find_attr_as_int(res->msgs[0],
732                                                    "msDS-Behavior-Version", -1);
733                 if (forest_behaviour_version != -1) {
734                         int *val = talloc(ldb, int);
735                         if (!val) {
736                                 talloc_free(mem_ctx);
737                                 return ldb_oom(ldb);
738                         }
739                         *val = forest_behaviour_version;
740                         ret = ldb_set_opaque(ldb, "forestFunctionality", val);
741                         if (ret != LDB_SUCCESS) {
742                                 talloc_free(mem_ctx);
743                                 return ret;
744                         }
745                 }
746         }
747
748         ret = ldb_search(ldb, mem_ctx, &res,
749                          ldb_dn_new(mem_ctx, ldb, ""),
750                          LDB_SCOPE_BASE, ds_attrs, NULL);
751         if (ret == LDB_SUCCESS && res->count == 1) {
752                 struct ldb_dn *ds_dn
753                         = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0],
754                                                   "dsServiceName");
755                 if (ds_dn) {
756                         ret = ldb_search(ldb, mem_ctx, &res, ds_dn,
757                                          LDB_SCOPE_BASE, attrs, NULL);
758                         if (ret == LDB_SUCCESS && res->count == 1) {
759                                 int domain_controller_behaviour_version
760                                         = ldb_msg_find_attr_as_int(res->msgs[0],
761                                                                    "msDS-Behavior-Version", -1);
762                                 if (domain_controller_behaviour_version != -1) {
763                                         int *val = talloc(ldb, int);
764                                         if (!val) {
765                                                 talloc_free(mem_ctx);
766                                                 return ldb_oom(ldb);
767                                         }
768                                         *val = domain_controller_behaviour_version;
769                                         ret = ldb_set_opaque(ldb,
770                                                              "domainControllerFunctionality", val);
771                                         if (ret != LDB_SUCCESS) {
772                                                 talloc_free(mem_ctx);
773                                                 return ret;
774                                         }
775                                 }
776                         }
777                 }
778         }
779
780         talloc_free(mem_ctx);
781
782         return LDB_SUCCESS;
783 }
784
785 /*
786  * This function gets the string SCOPE_DN:OPTIONAL_FEATURE_GUID and parse it
787  * to a DN and a GUID object
788  */
789 static int get_optional_feature_dn_guid(struct ldb_request *req, struct ldb_context *ldb,
790                                                 TALLOC_CTX *mem_ctx,
791                                                 struct ldb_dn **op_feature_scope_dn,
792                                                 struct GUID *op_feature_guid)
793 {
794         const struct ldb_message *msg = req->op.mod.message;
795         const char *ldb_val_str;
796         char *dn, *guid;
797         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
798         NTSTATUS status;
799
800         ldb_val_str = ldb_msg_find_attr_as_string(msg, "enableOptionalFeature", NULL);
801         if (!ldb_val_str) {
802                 ldb_set_errstring(ldb,
803                                   "rootdse: unable to find 'enableOptionalFeature'!");
804                 return LDB_ERR_UNWILLING_TO_PERFORM;
805         }
806
807         guid = strchr(ldb_val_str, ':');
808         if (!guid) {
809                 ldb_set_errstring(ldb,
810                                   "rootdse: unable to find GUID in 'enableOptionalFeature'!");
811                 return LDB_ERR_UNWILLING_TO_PERFORM;
812         }
813         status = GUID_from_string(guid+1, op_feature_guid);
814         if (!NT_STATUS_IS_OK(status)) {
815                 ldb_set_errstring(ldb,
816                                   "rootdse: bad GUID in 'enableOptionalFeature'!");
817                 return LDB_ERR_UNWILLING_TO_PERFORM;
818         }
819
820         dn = talloc_strndup(tmp_ctx, ldb_val_str, guid-ldb_val_str);
821         if (!dn) {
822                 ldb_set_errstring(ldb,
823                                   "rootdse: bad DN in 'enableOptionalFeature'!");
824                 return LDB_ERR_UNWILLING_TO_PERFORM;
825         }
826
827         *op_feature_scope_dn = ldb_dn_new(mem_ctx, ldb, dn);
828
829         talloc_free(tmp_ctx);
830         return LDB_SUCCESS;
831 }
832
833 /*
834  * This function gets the OPTIONAL_FEATURE_GUID and looks for the optional feature
835  * ldb_message object.
836  */
837 static int dsdb_find_optional_feature(struct ldb_module *module, struct ldb_context *ldb,
838                                 TALLOC_CTX *mem_ctx, struct GUID op_feature_guid, struct ldb_message **msg)
839 {
840         struct ldb_result *res;
841         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
842         int ret;
843
844         ret = dsdb_module_search(module, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE,
845                                 NULL,
846                                 DSDB_FLAG_NEXT_MODULE |
847                                 DSDB_SEARCH_SEARCH_ALL_PARTITIONS,
848                                  "(&(objectClass=msDS-OptionalFeature)"
849                                  "(msDS-OptionalFeatureGUID=%s))",GUID_string(tmp_ctx, &op_feature_guid));
850
851         if (ret != LDB_SUCCESS) {
852                 talloc_free(tmp_ctx);
853                 return ret;
854         }
855         if (res->count == 0) {
856                 talloc_free(tmp_ctx);
857                 return LDB_ERR_NO_SUCH_OBJECT;
858         }
859         if (res->count != 1) {
860                 ldb_asprintf_errstring(ldb,
861                                        "More than one object found matching optional feature GUID %s\n",
862                                        GUID_string(tmp_ctx, &op_feature_guid));
863                 talloc_free(tmp_ctx);
864                 return LDB_ERR_OPERATIONS_ERROR;
865         }
866
867         *msg = talloc_steal(mem_ctx, res->msgs[0]);
868
869         talloc_free(tmp_ctx);
870         return LDB_SUCCESS;
871 }
872
873 static int rootdse_enable_recycle_bin(struct ldb_module *module,struct ldb_context *ldb,
874                         TALLOC_CTX *mem_ctx, struct ldb_dn *op_feature_scope_dn,
875                         struct ldb_message *op_feature_msg)
876 {
877         int ret;
878         const int domain_func_level = dsdb_functional_level(ldb);
879         struct ldb_dn *ntds_settings_dn;
880         TALLOC_CTX *tmp_ctx;
881         unsigned int el_count = 0;
882         struct ldb_message *msg;
883
884         ret = ldb_msg_find_attr_as_int(op_feature_msg, "msDS-RequiredForestBehaviorVersion", 0);
885         if (domain_func_level < ret){
886                 ldb_asprintf_errstring(ldb,
887                                        "rootdse_enable_recycle_bin: Domain functional level must be at least %d\n",
888                                        ret);
889                 return LDB_ERR_UNWILLING_TO_PERFORM;
890         }
891
892         tmp_ctx = talloc_new(mem_ctx);
893         ntds_settings_dn = samdb_ntds_settings_dn(ldb);
894         if (!ntds_settings_dn) {
895                 DEBUG(0, (__location__ ": Failed to find NTDS settings DN\n"));
896                 ret = LDB_ERR_OPERATIONS_ERROR;
897                 talloc_free(tmp_ctx);
898                 return ret;
899         }
900
901         ntds_settings_dn = ldb_dn_copy(tmp_ctx, ntds_settings_dn);
902         if (!ntds_settings_dn) {
903                 DEBUG(0, (__location__ ": Failed to copy NTDS settings DN\n"));
904                 ret = LDB_ERR_OPERATIONS_ERROR;
905                 talloc_free(tmp_ctx);
906                 return ret;
907         }
908
909         msg = ldb_msg_new(tmp_ctx);
910         msg->dn = ntds_settings_dn;
911
912         ldb_msg_add_linearized_dn(msg, "msDS-EnabledFeature", op_feature_msg->dn);
913         msg->elements[el_count++].flags = LDB_FLAG_MOD_ADD;
914
915         ret = dsdb_module_modify(module, msg, DSDB_FLAG_NEXT_MODULE);
916         if (ret != LDB_SUCCESS) {
917                 ldb_asprintf_errstring(ldb,
918                                        "rootdse_enable_recycle_bin: Failed to modify object %s - %s",
919                                        ldb_dn_get_linearized(ntds_settings_dn),
920                                        ldb_errstring(ldb));
921                 talloc_free(tmp_ctx);
922                 return ret;
923         }
924
925         msg->dn = op_feature_scope_dn;
926         ret = dsdb_module_modify(module, msg, DSDB_FLAG_NEXT_MODULE);
927         if (ret != LDB_SUCCESS) {
928                 ldb_asprintf_errstring(ldb,
929                                        "rootdse_enable_recycle_bin: Failed to modify object %s - %s",
930                                        ldb_dn_get_linearized(op_feature_scope_dn),
931                                        ldb_errstring(ldb));
932                 talloc_free(tmp_ctx);
933                 return ret;
934         }
935
936         return LDB_SUCCESS;
937 }
938
939 static int rootdse_enableoptionalfeature(struct ldb_module *module, struct ldb_request *req)
940 {
941         /*
942           steps:
943                - check for system (only system can enable features)
944                - extract GUID from the request
945                - find the feature object
946                - check functional level, must be at least msDS-RequiredForestBehaviorVersion
947                - check if it is already enabled (if enabled return LDAP_ATTRIBUTE_OR_VALUE_EXISTS) - probably not needed, just return error from the add/modify
948                - add/modify objects (see ntdsconnection code for an example)
949          */
950
951         struct ldb_context *ldb = ldb_module_get_ctx(module);
952         struct GUID op_feature_guid;
953         struct ldb_dn *op_feature_scope_dn;
954         struct ldb_message *op_feature_msg;
955         struct auth_session_info *session_info =
956                                 (struct auth_session_info *)ldb_get_opaque(ldb, "sessionInfo");
957         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
958         int ret;
959         const char *guid_string;
960
961         if (security_session_user_level(session_info, NULL) != SECURITY_SYSTEM) {
962                 ldb_set_errstring(ldb, "rootdse: Insufficient rights for enableoptionalfeature");
963                 return LDB_ERR_UNWILLING_TO_PERFORM;
964         }
965
966         ret = get_optional_feature_dn_guid(req, ldb, tmp_ctx, &op_feature_scope_dn, &op_feature_guid);
967         if (ret != LDB_SUCCESS) {
968                 talloc_free(tmp_ctx);
969                 return ret;
970         }
971
972         guid_string = GUID_string(tmp_ctx, &op_feature_guid);
973         if (!guid_string) {
974                 ldb_set_errstring(ldb, "rootdse: bad optional feature GUID");
975                 return LDB_ERR_UNWILLING_TO_PERFORM;
976         }
977
978         ret = dsdb_find_optional_feature(module, ldb, tmp_ctx, op_feature_guid, &op_feature_msg);
979         if (ret != LDB_SUCCESS) {
980                 ldb_asprintf_errstring(ldb,
981                                        "rootdse: unable to find optional feature for %s - %s",
982                                        guid_string, ldb_errstring(ldb));
983                 talloc_free(tmp_ctx);
984                 return ret;
985         }
986
987         if (strcasecmp(DS_GUID_FEATURE_RECYCLE_BIN, guid_string) == 0) {
988                         ret = rootdse_enable_recycle_bin(module, ldb,
989                                                          tmp_ctx, op_feature_scope_dn,
990                                                          op_feature_msg);
991         } else {
992                 ldb_asprintf_errstring(ldb,
993                                        "rootdse: unknown optional feature %s",
994                                        guid_string);
995                 talloc_free(tmp_ctx);
996                 return LDB_ERR_UNWILLING_TO_PERFORM;
997         }
998         if (ret != LDB_SUCCESS) {
999                 ldb_asprintf_errstring(ldb,
1000                                        "rootdse: failed to set optional feature for %s - %s",
1001                                        guid_string, ldb_errstring(ldb));
1002                 talloc_free(tmp_ctx);
1003                 return ret;
1004         }
1005
1006         talloc_free(tmp_ctx);
1007         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);;
1008 }
1009
1010 static int rootdse_schemaupdatenow(struct ldb_module *module, struct ldb_request *req)
1011 {
1012         struct ldb_context *ldb = ldb_module_get_ctx(module);
1013         struct ldb_result *ext_res;
1014         int ret;
1015         struct ldb_dn *schema_dn;
1016
1017         schema_dn = ldb_get_schema_basedn(ldb);
1018         if (!schema_dn) {
1019                 ldb_reset_err_string(ldb);
1020                 ldb_debug(ldb, LDB_DEBUG_WARNING,
1021                           "rootdse_modify: no schema dn present: (skip ldb_extended call)\n");
1022                 return ldb_next_request(module, req);
1023         }
1024
1025         ret = ldb_extended(ldb, DSDB_EXTENDED_SCHEMA_UPDATE_NOW_OID, schema_dn, &ext_res);
1026         if (ret != LDB_SUCCESS) {
1027                 return ldb_operr(ldb);
1028         }
1029
1030         talloc_free(ext_res);
1031         return ldb_module_done(req, NULL, NULL, ret);
1032 }
1033
1034 static int rootdse_add(struct ldb_module *module, struct ldb_request *req)
1035 {
1036         struct ldb_context *ldb = ldb_module_get_ctx(module);
1037
1038         rootdse_mark_noncritical(module, req->controls);
1039
1040         /*
1041                 If dn is not "" we should let it pass through
1042         */
1043         if (!ldb_dn_is_null(req->op.add.message->dn)) {
1044                 return ldb_next_request(module, req);
1045         }
1046
1047         ldb_set_errstring(ldb, "rootdse_add: you cannot add a new rootdse entry!");
1048         return LDB_ERR_NAMING_VIOLATION;
1049 }
1050
1051 static int rootdse_become_master(struct ldb_module *module,
1052                                  struct ldb_request *req,
1053                                  uint32_t role)
1054 {
1055         struct drepl_takeFSMORole r;
1056         struct messaging_context *msg;
1057         struct ldb_context *ldb = ldb_module_get_ctx(module);
1058         TALLOC_CTX *tmp_ctx = talloc_new(req);
1059         struct loadparm_context *lp_ctx = ldb_get_opaque(ldb, "loadparm");
1060         NTSTATUS status_call;
1061         WERROR status_fn;
1062         struct dcerpc_binding_handle *irpc_handle;
1063
1064         msg = messaging_client_init(tmp_ctx, lpcfg_messaging_path(tmp_ctx, lp_ctx),
1065                                     ldb_get_event_context(ldb));
1066         if (!msg) {
1067                 ldb_asprintf_errstring(ldb, "Failed to generate client messaging context in %s", lpcfg_messaging_path(tmp_ctx, lp_ctx));
1068                 return LDB_ERR_OPERATIONS_ERROR;
1069         }
1070         irpc_handle = irpc_binding_handle_by_name(tmp_ctx, msg,
1071                                                   "dreplsrv",
1072                                                   &ndr_table_irpc);
1073         if (irpc_handle == NULL) {
1074                 return ldb_oom(ldb);
1075         }
1076         r.in.role = role;
1077
1078         status_call = dcerpc_drepl_takeFSMORole_r(irpc_handle, tmp_ctx, &r);
1079         if (!NT_STATUS_IS_OK(status_call)) {
1080                 return LDB_ERR_OPERATIONS_ERROR;
1081         }
1082         status_fn = r.out.result;
1083         if (!W_ERROR_IS_OK(status_fn)) {
1084                 return LDB_ERR_OPERATIONS_ERROR;
1085         }
1086         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1087 }
1088
1089 static int rootdse_modify(struct ldb_module *module, struct ldb_request *req)
1090 {
1091         struct ldb_context *ldb = ldb_module_get_ctx(module);
1092
1093         rootdse_mark_noncritical(module, req->controls);
1094
1095         /*
1096                 If dn is not "" we should let it pass through
1097         */
1098         if (!ldb_dn_is_null(req->op.mod.message->dn)) {
1099                 return ldb_next_request(module, req);
1100         }
1101
1102         /*
1103                 dn is empty so check for schemaUpdateNow attribute
1104                 "The type of modification and values specified in the LDAP modify operation do not matter." MSDN
1105         */
1106         if (ldb_msg_find_element(req->op.mod.message, "schemaUpdateNow")) {
1107                 return rootdse_schemaupdatenow(module, req);
1108         }
1109         if (ldb_msg_find_element(req->op.mod.message, "becomeDomainMaster")) {
1110                 return rootdse_become_master(module, req, DREPL_NAMING_MASTER);
1111         }
1112         if (ldb_msg_find_element(req->op.mod.message, "becomeInfrastructureMaster")) {
1113                 return rootdse_become_master(module, req, DREPL_INFRASTRUCTURE_MASTER);
1114         }
1115         if (ldb_msg_find_element(req->op.mod.message, "becomeRidMaster")) {
1116                 return rootdse_become_master(module, req, DREPL_RID_MASTER);
1117         }
1118         if (ldb_msg_find_element(req->op.mod.message, "becomeSchemaMaster")) {
1119                 return rootdse_become_master(module, req, DREPL_SCHEMA_MASTER);
1120         }
1121         if (ldb_msg_find_element(req->op.mod.message, "becomePdc")) {
1122                 return rootdse_become_master(module, req, DREPL_PDC_MASTER);
1123         }
1124         if (ldb_msg_find_element(req->op.mod.message, "enableOptionalFeature")) {
1125                 return rootdse_enableoptionalfeature(module, req);
1126         }
1127
1128         ldb_set_errstring(ldb, "rootdse_modify: unknown attribute to change!");
1129         return LDB_ERR_UNWILLING_TO_PERFORM;
1130 }
1131
1132 static int rootdse_delete(struct ldb_module *module, struct ldb_request *req)
1133 {
1134         struct ldb_context *ldb = ldb_module_get_ctx(module);
1135
1136         rootdse_mark_noncritical(module, req->controls);
1137
1138         /*
1139                 If dn is not "" we should let it pass through
1140         */
1141         if (!ldb_dn_is_null(req->op.del.dn)) {
1142                 return ldb_next_request(module, req);
1143         }
1144
1145         ldb_set_errstring(ldb, "rootdse_remove: you cannot delete the rootdse entry!");
1146         return LDB_ERR_NO_SUCH_OBJECT;
1147 }
1148
1149 _PUBLIC_ const struct ldb_module_ops ldb_rootdse_module_ops = {
1150         .name           = "rootdse",
1151         .init_context   = rootdse_init,
1152         .search         = rootdse_search,
1153         .request        = rootdse_request,
1154         .add            = rootdse_add,
1155         .modify         = rootdse_modify,
1156         .del            = rootdse_delete
1157 };