dsdb-acl: use acl_check_access_on_objectclass() instead of acl_check_access_on_class()
[samba.git] / source4 / dsdb / samdb / ldb_modules / acl.c
1 /*
2   ldb database library
3
4   Copyright (C) Simo Sorce 2006-2008
5   Copyright (C) Nadezhda Ivanova 2009
6   Copyright (C) Anatoliy Atanasov  2009
7
8   This program is free software; you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 3 of the License, or
11   (at your option) any later version.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /*
23  *  Name: ldb
24  *
25  *  Component: ldb ACL module
26  *
27  *  Description: Module that performs authorisation access checks based on the
28  *               account's security context and the DACL of the object being polled.
29  *               Only DACL checks implemented at this point
30  *
31  *  Authors: Nadezhda Ivanova, Anatoliy Atanasov
32  */
33
34 #include "includes.h"
35 #include "ldb_module.h"
36 #include "auth/auth.h"
37 #include "libcli/security/security.h"
38 #include "dsdb/samdb/samdb.h"
39 #include "librpc/gen_ndr/ndr_security.h"
40 #include "param/param.h"
41 #include "dsdb/samdb/ldb_modules/util.h"
42 #include "lib/util/tsort.h"
43 #include "system/kerberos.h"
44 #include "auth/kerberos/kerberos.h"
45
46 struct extended_access_check_attribute {
47         const char *oa_name;
48         const uint32_t requires_rights;
49 };
50
51 struct acl_private {
52         bool acl_search;
53         const char **password_attrs;
54         void *cached_schema_ptr;
55         uint64_t cached_schema_metadata_usn;
56         uint64_t cached_schema_loaded_usn;
57         const char **confidential_attrs;
58 };
59
60 struct acl_context {
61         struct ldb_module *module;
62         struct ldb_request *req;
63         bool am_system;
64         bool am_administrator;
65         bool modify_search;
66         bool constructed_attrs;
67         bool allowedAttributes;
68         bool allowedAttributesEffective;
69         bool allowedChildClasses;
70         bool allowedChildClassesEffective;
71         bool sDRightsEffective;
72         bool userPassword;
73         const char * const *attrs;
74         struct dsdb_schema *schema;
75 };
76
77 static int acl_module_init(struct ldb_module *module)
78 {
79         struct ldb_context *ldb;
80         struct acl_private *data;
81         int ret;
82         unsigned int i, n, j;
83         TALLOC_CTX *mem_ctx;
84         static const char * const attrs[] = { "passwordAttribute", NULL };
85         static const char * const secret_attrs[] = {
86                 DSDB_SECRET_ATTRIBUTES
87         };
88         struct ldb_result *res;
89         struct ldb_message *msg;
90         struct ldb_message_element *password_attributes;
91
92         ldb = ldb_module_get_ctx(module);
93
94         ret = ldb_mod_register_control(module, LDB_CONTROL_SD_FLAGS_OID);
95         if (ret != LDB_SUCCESS) {
96                 ldb_debug(ldb, LDB_DEBUG_ERROR,
97                           "acl_module_init: Unable to register control with rootdse!\n");
98                 return ldb_operr(ldb);
99         }
100
101         data = talloc_zero(module, struct acl_private);
102         if (data == NULL) {
103                 return ldb_oom(ldb);
104         }
105
106         data->acl_search = lpcfg_parm_bool(ldb_get_opaque(ldb, "loadparm"),
107                                         NULL, "acl", "search", true);
108         ldb_module_set_private(module, data);
109
110         mem_ctx = talloc_new(module);
111         if (!mem_ctx) {
112                 return ldb_oom(ldb);
113         }
114
115         ret = dsdb_module_search_dn(module, mem_ctx, &res,
116                                     ldb_dn_new(mem_ctx, ldb, "@KLUDGEACL"),
117                                     attrs,
118                                     DSDB_FLAG_NEXT_MODULE |
119                                     DSDB_FLAG_AS_SYSTEM,
120                                     NULL);
121         if (ret != LDB_SUCCESS) {
122                 goto done;
123         }
124         if (res->count == 0) {
125                 goto done;
126         }
127
128         if (res->count > 1) {
129                 talloc_free(mem_ctx);
130                 return LDB_ERR_CONSTRAINT_VIOLATION;
131         }
132
133         msg = res->msgs[0];
134
135         password_attributes = ldb_msg_find_element(msg, "passwordAttribute");
136         if (!password_attributes) {
137                 goto done;
138         }
139         data->password_attrs = talloc_array(data, const char *,
140                         password_attributes->num_values +
141                         ARRAY_SIZE(secret_attrs) + 1);
142         if (!data->password_attrs) {
143                 talloc_free(mem_ctx);
144                 return ldb_oom(ldb);
145         }
146
147         n = 0;
148         for (i=0; i < password_attributes->num_values; i++) {
149                 data->password_attrs[n] = (const char *)password_attributes->values[i].data;
150                 talloc_steal(data->password_attrs, password_attributes->values[i].data);
151                 n++;
152         }
153
154         for (i=0; i < ARRAY_SIZE(secret_attrs); i++) {
155                 bool found = false;
156
157                 for (j=0; j < n; j++) {
158                         if (strcasecmp(data->password_attrs[j], secret_attrs[i]) == 0) {
159                                 found = true;
160                                 break;
161                         }
162                 }
163
164                 if (found) {
165                         continue;
166                 }
167
168                 data->password_attrs[n] = talloc_strdup(data->password_attrs,
169                                                         secret_attrs[i]);
170                 if (data->password_attrs[n] == NULL) {
171                         talloc_free(mem_ctx);
172                         return ldb_oom(ldb);
173                 }
174                 n++;
175         }
176         data->password_attrs[n] = NULL;
177
178 done:
179         talloc_free(mem_ctx);
180         return ldb_next_init(module);
181 }
182
183 static int acl_allowedAttributes(struct ldb_module *module,
184                                  const struct dsdb_schema *schema,
185                                  struct ldb_message *sd_msg,
186                                  struct ldb_message *msg,
187                                  struct acl_context *ac)
188 {
189         struct ldb_message_element *oc_el;
190         struct ldb_context *ldb = ldb_module_get_ctx(module);
191         TALLOC_CTX *mem_ctx;
192         const char **attr_list;
193         int i, ret;
194         const struct dsdb_class *objectclass;
195
196         /* If we don't have a schema yet, we can't do anything... */
197         if (schema == NULL) {
198                 ldb_asprintf_errstring(ldb, "cannot add allowedAttributes to %s because no schema is loaded", ldb_dn_get_linearized(msg->dn));
199                 return LDB_ERR_OPERATIONS_ERROR;
200         }
201
202         /* Must remove any existing attribute */
203         if (ac->allowedAttributes) {
204                 ldb_msg_remove_attr(msg, "allowedAttributes");
205         }
206
207         mem_ctx = talloc_new(msg);
208         if (!mem_ctx) {
209                 return ldb_oom(ldb);
210         }
211
212         oc_el = ldb_msg_find_element(sd_msg, "objectClass");
213         attr_list = dsdb_full_attribute_list(mem_ctx, schema, oc_el, DSDB_SCHEMA_ALL);
214         if (!attr_list) {
215                 ldb_asprintf_errstring(ldb, "acl: Failed to get list of attributes");
216                 talloc_free(mem_ctx);
217                 return LDB_ERR_OPERATIONS_ERROR;
218         }
219
220         /*
221          * Get the top-most structural object class for the ACL check
222          */
223         objectclass = dsdb_get_last_structural_class(ac->schema,
224                                                      oc_el);
225         if (objectclass == NULL) {
226                 ldb_asprintf_errstring(ldb, "acl_read: Failed to find a structural class for %s",
227                                        ldb_dn_get_linearized(sd_msg->dn));
228                 talloc_free(mem_ctx);
229                 return LDB_ERR_OPERATIONS_ERROR;
230         }
231
232         if (ac->allowedAttributes) {
233                 for (i=0; attr_list && attr_list[i]; i++) {
234                         ldb_msg_add_string(msg, "allowedAttributes", attr_list[i]);
235                 }
236         }
237         if (ac->allowedAttributesEffective) {
238                 struct security_descriptor *sd;
239                 struct dom_sid *sid = NULL;
240                 struct ldb_control *as_system = ldb_request_get_control(ac->req,
241                                                                         LDB_CONTROL_AS_SYSTEM_OID);
242
243                 if (as_system != NULL) {
244                         as_system->critical = 0;
245                 }
246
247                 ldb_msg_remove_attr(msg, "allowedAttributesEffective");
248                 if (ac->am_system || as_system) {
249                         for (i=0; attr_list && attr_list[i]; i++) {
250                                 ldb_msg_add_string(msg, "allowedAttributesEffective", attr_list[i]);
251                         }
252                         return LDB_SUCCESS;
253                 }
254
255                 ret = dsdb_get_sd_from_ldb_message(ldb_module_get_ctx(module), mem_ctx, sd_msg, &sd);
256
257                 if (ret != LDB_SUCCESS) {
258                         return ret;
259                 }
260
261                 sid = samdb_result_dom_sid(mem_ctx, sd_msg, "objectSid");
262                 for (i=0; attr_list && attr_list[i]; i++) {
263                         const struct dsdb_attribute *attr = dsdb_attribute_by_lDAPDisplayName(schema,
264                                                                                         attr_list[i]);
265                         if (!attr) {
266                                 return ldb_operr(ldb);
267                         }
268                         /* remove constructed attributes */
269                         if (attr->systemFlags & DS_FLAG_ATTR_IS_CONSTRUCTED
270                             || attr->systemOnly
271                             || (attr->linkID != 0 && attr->linkID % 2 != 0 )) {
272                                 continue;
273                         }
274                         ret = acl_check_access_on_attribute(module,
275                                                             msg,
276                                                             sd,
277                                                             sid,
278                                                             SEC_ADS_WRITE_PROP,
279                                                             attr,
280                                                             objectclass);
281                         if (ret == LDB_SUCCESS) {
282                                 ldb_msg_add_string(msg, "allowedAttributesEffective", attr_list[i]);
283                         }
284                 }
285         }
286         return LDB_SUCCESS;
287 }
288
289 static int acl_childClasses(struct ldb_module *module,
290                             const struct dsdb_schema *schema,
291                             struct ldb_message *sd_msg,
292                             struct ldb_message *msg,
293                             const char *attrName)
294 {
295         struct ldb_message_element *oc_el;
296         struct ldb_message_element *allowedClasses;
297         const struct dsdb_class *sclass;
298         unsigned int i, j;
299         int ret;
300
301         /* If we don't have a schema yet, we can't do anything... */
302         if (schema == NULL) {
303                 ldb_asprintf_errstring(ldb_module_get_ctx(module), "cannot add childClassesEffective to %s because no schema is loaded", ldb_dn_get_linearized(msg->dn));
304                 return LDB_ERR_OPERATIONS_ERROR;
305         }
306
307         /* Must remove any existing attribute, or else confusion reins */
308         ldb_msg_remove_attr(msg, attrName);
309         ret = ldb_msg_add_empty(msg, attrName, 0, &allowedClasses);
310         if (ret != LDB_SUCCESS) {
311                 return ret;
312         }
313
314         oc_el = ldb_msg_find_element(sd_msg, "objectClass");
315
316         for (i=0; oc_el && i < oc_el->num_values; i++) {
317                 sclass = dsdb_class_by_lDAPDisplayName_ldb_val(schema, &oc_el->values[i]);
318                 if (!sclass) {
319                         /* We don't know this class?  what is going on? */
320                         continue;
321                 }
322
323                 for (j=0; sclass->possibleInferiors && sclass->possibleInferiors[j]; j++) {
324                         ldb_msg_add_string(msg, attrName, sclass->possibleInferiors[j]);
325                 }
326         }
327         if (allowedClasses->num_values > 1) {
328                 TYPESAFE_QSORT(allowedClasses->values, allowedClasses->num_values, data_blob_cmp);
329                 for (i=1 ; i < allowedClasses->num_values; i++) {
330                         struct ldb_val *val1 = &allowedClasses->values[i-1];
331                         struct ldb_val *val2 = &allowedClasses->values[i];
332                         if (data_blob_cmp(val1, val2) == 0) {
333                                 memmove(val1, val2, (allowedClasses->num_values - i) * sizeof(struct ldb_val));
334                                 allowedClasses->num_values--;
335                                 i--;
336                         }
337                 }
338         }
339
340         return LDB_SUCCESS;
341 }
342
343 static int acl_check_access_on_class(struct ldb_module *module,
344                                      const struct dsdb_schema *schema,
345                                      TALLOC_CTX *mem_ctx,
346                                      struct security_descriptor *sd,
347                                      struct security_token *token,
348                                      struct dom_sid *rp_sid,
349                                      uint32_t access_mask,
350                                      const char *class_name)
351 {
352         int ret;
353         NTSTATUS status;
354         uint32_t access_granted;
355         struct object_tree *root = NULL;
356         struct object_tree *new_node = NULL;
357         const struct GUID *guid;
358
359         if (class_name != NULL) {
360                 guid = class_schemaid_guid_by_lDAPDisplayName(schema, class_name);
361                 if (!guid) {
362                         DEBUG(10, ("acl_search: cannot find class %s\n",
363                                    class_name));
364                         goto fail;
365                 }
366                 if (!insert_in_object_tree(mem_ctx,
367                                            guid, access_mask,
368                                            &root, &new_node)) {
369                         DEBUG(10, ("acl_search: cannot add to object tree guid\n"));
370                         goto fail;
371                 }
372         }
373
374         status = sec_access_check_ds(sd, token,
375                                      access_mask,
376                                      &access_granted,
377                                      root,
378                                      rp_sid);
379         if (!NT_STATUS_IS_OK(status)) {
380                 ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
381         } else {
382                 ret = LDB_SUCCESS;
383         }
384         return ret;
385 fail:
386         return ldb_operr(ldb_module_get_ctx(module));
387 }
388
389 static int acl_childClassesEffective(struct ldb_module *module,
390                                      const struct dsdb_schema *schema,
391                                      struct ldb_message *sd_msg,
392                                      struct ldb_message *msg,
393                                      struct acl_context *ac)
394 {
395         struct ldb_message_element *oc_el;
396         struct ldb_message_element *allowedClasses = NULL;
397         const struct dsdb_class *sclass;
398         struct security_descriptor *sd;
399         struct ldb_control *as_system = ldb_request_get_control(ac->req,
400                                                                 LDB_CONTROL_AS_SYSTEM_OID);
401         struct dom_sid *sid = NULL;
402         unsigned int i, j;
403         int ret;
404
405         if (as_system != NULL) {
406                 as_system->critical = 0;
407         }
408
409         if (ac->am_system || as_system) {
410                 return acl_childClasses(module, schema, sd_msg, msg, "allowedChildClassesEffective");
411         }
412
413         /* If we don't have a schema yet, we can't do anything... */
414         if (schema == NULL) {
415                 ldb_asprintf_errstring(ldb_module_get_ctx(module), "cannot add allowedChildClassesEffective to %s because no schema is loaded", ldb_dn_get_linearized(msg->dn));
416                 return LDB_ERR_OPERATIONS_ERROR;
417         }
418
419         /* Must remove any existing attribute, or else confusion reins */
420         ldb_msg_remove_attr(msg, "allowedChildClassesEffective");
421
422         oc_el = ldb_msg_find_element(sd_msg, "objectClass");
423         ret = dsdb_get_sd_from_ldb_message(ldb_module_get_ctx(module), msg, sd_msg, &sd);
424         if (ret != LDB_SUCCESS) {
425                 return ret;
426         }
427
428         sid = samdb_result_dom_sid(msg, sd_msg, "objectSid");
429         for (i=0; oc_el && i < oc_el->num_values; i++) {
430                 sclass = dsdb_class_by_lDAPDisplayName_ldb_val(schema, &oc_el->values[i]);
431                 if (!sclass) {
432                         /* We don't know this class?  what is going on? */
433                         continue;
434                 }
435
436                 for (j=0; sclass->possibleInferiors && sclass->possibleInferiors[j]; j++) {
437                         const struct dsdb_class *sc;
438
439                         sc = dsdb_class_by_lDAPDisplayName(schema,
440                                                            sclass->possibleInferiors[j]);
441                         if (!sc) {
442                                 /* We don't know this class?  what is going on? */
443                                 continue;
444                         }
445
446                         ret = acl_check_access_on_objectclass(module, ac,
447                                                               sd, sid,
448                                                               SEC_ADS_CREATE_CHILD,
449                                                               sc);
450                         if (ret == LDB_SUCCESS) {
451                                 ldb_msg_add_string(msg, "allowedChildClassesEffective",
452                                                    sclass->possibleInferiors[j]);
453                         }
454                 }
455         }
456         allowedClasses = ldb_msg_find_element(msg, "allowedChildClassesEffective");
457         if (!allowedClasses) {
458                 return LDB_SUCCESS;
459         }
460
461         if (allowedClasses->num_values > 1) {
462                 TYPESAFE_QSORT(allowedClasses->values, allowedClasses->num_values, data_blob_cmp);
463                 for (i=1 ; i < allowedClasses->num_values; i++) {
464                         struct ldb_val *val1 = &allowedClasses->values[i-1];
465                         struct ldb_val *val2 = &allowedClasses->values[i];
466                         if (data_blob_cmp(val1, val2) == 0) {
467                                 memmove(val1, val2, (allowedClasses->num_values - i) * sizeof( struct ldb_val));
468                                 allowedClasses->num_values--;
469                                 i--;
470                         }
471                 }
472         }
473         return LDB_SUCCESS;
474 }
475
476 static int acl_sDRightsEffective(struct ldb_module *module,
477                                  struct ldb_message *sd_msg,
478                                  struct ldb_message *msg,
479                                  struct acl_context *ac)
480 {
481         struct ldb_context *ldb = ldb_module_get_ctx(module);
482         struct ldb_message_element *rightsEffective;
483         int ret;
484         struct security_descriptor *sd;
485         struct ldb_control *as_system = ldb_request_get_control(ac->req,
486                                                                 LDB_CONTROL_AS_SYSTEM_OID);
487         struct dom_sid *sid = NULL;
488         uint32_t flags = 0;
489
490         if (as_system != NULL) {
491                 as_system->critical = 0;
492         }
493
494         /* Must remove any existing attribute, or else confusion reins */
495         ldb_msg_remove_attr(msg, "sDRightsEffective");
496         ret = ldb_msg_add_empty(msg, "sDRightsEffective", 0, &rightsEffective);
497         if (ret != LDB_SUCCESS) {
498                 return ret;
499         }
500         if (ac->am_system || as_system) {
501                 flags = SECINFO_OWNER | SECINFO_GROUP |  SECINFO_SACL |  SECINFO_DACL;
502         } else {
503                 const struct dsdb_class *objectclass;
504                 const struct dsdb_attribute *attr;
505
506                 objectclass = dsdb_get_structural_oc_from_msg(ac->schema, sd_msg);
507                 if (objectclass == NULL) {
508                         return ldb_operr(ldb);
509                 }
510
511                 attr = dsdb_attribute_by_lDAPDisplayName(ac->schema,
512                                                          "nTSecurityDescriptor");
513                 if (attr == NULL) {
514                         return ldb_operr(ldb);
515                 }
516
517                 /* Get the security descriptor from the message */
518                 ret = dsdb_get_sd_from_ldb_message(ldb, msg, sd_msg, &sd);
519                 if (ret != LDB_SUCCESS) {
520                         return ret;
521                 }
522                 sid = samdb_result_dom_sid(msg, sd_msg, "objectSid");
523                 ret = acl_check_access_on_attribute(module,
524                                                     msg,
525                                                     sd,
526                                                     sid,
527                                                     SEC_STD_WRITE_OWNER,
528                                                     attr,
529                                                     objectclass);
530                 if (ret == LDB_SUCCESS) {
531                         flags |= SECINFO_OWNER | SECINFO_GROUP;
532                 }
533                 ret = acl_check_access_on_attribute(module,
534                                                     msg,
535                                                     sd,
536                                                     sid,
537                                                     SEC_STD_WRITE_DAC,
538                                                     attr,
539                                                     objectclass);
540                 if (ret == LDB_SUCCESS) {
541                         flags |= SECINFO_DACL;
542                 }
543                 ret = acl_check_access_on_attribute(module,
544                                                     msg,
545                                                     sd,
546                                                     sid,
547                                                     SEC_FLAG_SYSTEM_SECURITY,
548                                                     attr,
549                                                     objectclass);
550                 if (ret == LDB_SUCCESS) {
551                         flags |= SECINFO_SACL;
552                 }
553         }
554         return samdb_msg_add_uint(ldb_module_get_ctx(module), msg, msg,
555                                   "sDRightsEffective", flags);
556 }
557
558 static int acl_validate_spn_value(TALLOC_CTX *mem_ctx,
559                                   struct ldb_context *ldb,
560                                   const char *spn_value,
561                                   uint32_t userAccountControl,
562                                   const char *samAccountName,
563                                   const char *dnsHostName,
564                                   const char *netbios_name,
565                                   const char *ntds_guid)
566 {
567         int ret;
568         krb5_context krb_ctx;
569         krb5_error_code kerr;
570         krb5_principal principal;
571         char *instanceName;
572         char *serviceType;
573         char *serviceName;
574         const char *forest_name = samdb_forest_name(ldb, mem_ctx);
575         const char *base_domain = samdb_default_domain_name(ldb, mem_ctx);
576         struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
577                                                           struct loadparm_context);
578         bool is_dc = (userAccountControl & UF_SERVER_TRUST_ACCOUNT) ||
579                 (userAccountControl & UF_PARTIAL_SECRETS_ACCOUNT);
580
581         if (strcasecmp_m(spn_value, samAccountName) == 0) {
582                 /* MacOS X sets this value, and setting an SPN of your
583                  * own samAccountName is both pointless and safe */
584                 return LDB_SUCCESS;
585         }
586
587         kerr = smb_krb5_init_context_basic(mem_ctx,
588                                            lp_ctx,
589                                            &krb_ctx);
590         if (kerr != 0) {
591                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
592                                  "Could not initialize kerberos context.");
593         }
594
595         ret = krb5_parse_name(krb_ctx, spn_value, &principal);
596         if (ret) {
597                 krb5_free_context(krb_ctx);
598                 return LDB_ERR_CONSTRAINT_VIOLATION;
599         }
600
601         if (principal->name.name_string.len < 2) {
602                 goto fail;
603         }
604
605         instanceName = principal->name.name_string.val[1];
606         serviceType = principal->name.name_string.val[0];
607         if (principal->name.name_string.len == 3) {
608                 serviceName = principal->name.name_string.val[2];
609         } else {
610                 serviceName = NULL;
611         }
612
613         if (serviceName) {
614                 if (!is_dc) {
615                         goto fail;
616                 }
617                 if (strcasecmp(serviceType, "ldap") == 0) {
618                         if (strcasecmp(serviceName, netbios_name) != 0 &&
619                             strcasecmp(serviceName, forest_name) != 0) {
620                                 goto fail;
621                         }
622
623                 } else if (strcasecmp(serviceType, "gc") == 0) {
624                         if (strcasecmp(serviceName, forest_name) != 0) {
625                                 goto fail;
626                         }
627                 } else {
628                         if (strcasecmp(serviceName, base_domain) != 0 &&
629                             strcasecmp(serviceName, netbios_name) != 0) {
630                                 goto fail;
631                         }
632                 }
633         }
634         /* instanceName can be samAccountName without $ or dnsHostName
635          * or "ntds_guid._msdcs.forest_domain for DC objects */
636         if (strlen(instanceName) == (strlen(samAccountName) - 1)
637             && strncasecmp(instanceName, samAccountName, strlen(samAccountName) - 1) == 0) {
638                 goto success;
639         } else if (dnsHostName != NULL && strcasecmp(instanceName, dnsHostName) == 0) {
640                 goto success;
641         } else if (is_dc) {
642                 const char *guid_str;
643                 guid_str = talloc_asprintf(mem_ctx,"%s._msdcs.%s",
644                                            ntds_guid,
645                                            forest_name);
646                 if (strcasecmp(instanceName, guid_str) == 0) {
647                         goto success;
648                 }
649         }
650
651 fail:
652         krb5_free_principal(krb_ctx, principal);
653         krb5_free_context(krb_ctx);
654         return LDB_ERR_CONSTRAINT_VIOLATION;
655
656 success:
657         krb5_free_principal(krb_ctx, principal);
658         krb5_free_context(krb_ctx);
659         return LDB_SUCCESS;
660 }
661
662 static int acl_check_spn(TALLOC_CTX *mem_ctx,
663                          struct ldb_module *module,
664                          struct ldb_request *req,
665                          struct security_descriptor *sd,
666                          struct dom_sid *sid,
667                          const struct dsdb_attribute *attr,
668                          const struct dsdb_class *objectclass)
669 {
670         int ret;
671         unsigned int i;
672         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
673         struct ldb_context *ldb = ldb_module_get_ctx(module);
674         struct ldb_result *acl_res;
675         struct ldb_result *netbios_res;
676         struct ldb_message_element *el;
677         struct ldb_dn *partitions_dn = samdb_partitions_dn(ldb, tmp_ctx);
678         uint32_t userAccountControl;
679         const char *samAccountName;
680         const char *dnsHostName;
681         const char *netbios_name;
682         struct GUID ntds;
683         char *ntds_guid = NULL;
684
685         static const char *acl_attrs[] = {
686                 "samAccountName",
687                 "dnsHostName",
688                 "userAccountControl",
689                 NULL
690         };
691         static const char *netbios_attrs[] = {
692                 "nETBIOSName",
693                 NULL
694         };
695
696         /* if we have wp, we can do whatever we like */
697         if (acl_check_access_on_attribute(module,
698                                           tmp_ctx,
699                                           sd,
700                                           sid,
701                                           SEC_ADS_WRITE_PROP,
702                                           attr, objectclass) == LDB_SUCCESS) {
703                 talloc_free(tmp_ctx);
704                 return LDB_SUCCESS;
705         }
706
707         ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
708                                        GUID_DRS_VALIDATE_SPN,
709                                        SEC_ADS_SELF_WRITE,
710                                        sid);
711
712         if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
713                 dsdb_acl_debug(sd, acl_user_token(module),
714                                req->op.mod.message->dn,
715                                true,
716                                10);
717                 talloc_free(tmp_ctx);
718                 return ret;
719         }
720
721         ret = dsdb_module_search_dn(module, tmp_ctx,
722                                     &acl_res, req->op.mod.message->dn,
723                                     acl_attrs,
724                                     DSDB_FLAG_NEXT_MODULE |
725                                     DSDB_FLAG_AS_SYSTEM |
726                                     DSDB_SEARCH_SHOW_RECYCLED,
727                                     req);
728         if (ret != LDB_SUCCESS) {
729                 talloc_free(tmp_ctx);
730                 return ret;
731         }
732
733         userAccountControl = ldb_msg_find_attr_as_uint(acl_res->msgs[0], "userAccountControl", 0);
734         dnsHostName = ldb_msg_find_attr_as_string(acl_res->msgs[0], "dnsHostName", NULL);
735         samAccountName = ldb_msg_find_attr_as_string(acl_res->msgs[0], "samAccountName", NULL);
736
737         ret = dsdb_module_search(module, tmp_ctx,
738                                  &netbios_res, partitions_dn,
739                                  LDB_SCOPE_ONELEVEL,
740                                  netbios_attrs,
741                                  DSDB_FLAG_NEXT_MODULE |
742                                  DSDB_FLAG_AS_SYSTEM,
743                                  req,
744                                  "(ncName=%s)",
745                                  ldb_dn_get_linearized(ldb_get_default_basedn(ldb)));
746
747         netbios_name = ldb_msg_find_attr_as_string(netbios_res->msgs[0], "nETBIOSName", NULL);
748
749         el = ldb_msg_find_element(req->op.mod.message, "servicePrincipalName");
750         if (!el) {
751                 talloc_free(tmp_ctx);
752                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
753                                          "Error finding element for servicePrincipalName.");
754         }
755
756         /* NTDSDSA objectGuid of object we are checking SPN for */
757         if (userAccountControl & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
758                 ret = dsdb_module_find_ntdsguid_for_computer(module, tmp_ctx,
759                                                              req->op.mod.message->dn, &ntds, req);
760                 if (ret != LDB_SUCCESS) {
761                         ldb_asprintf_errstring(ldb, "Failed to find NTDSDSA objectGuid for %s: %s",
762                                                ldb_dn_get_linearized(req->op.mod.message->dn),
763                                                ldb_strerror(ret));
764                         talloc_free(tmp_ctx);
765                         return LDB_ERR_OPERATIONS_ERROR;
766                 }
767                 ntds_guid = GUID_string(tmp_ctx, &ntds);
768         }
769
770         for (i=0; i < el->num_values; i++) {
771                 ret = acl_validate_spn_value(tmp_ctx,
772                                              ldb,
773                                              (char *)el->values[i].data,
774                                              userAccountControl,
775                                              samAccountName,
776                                              dnsHostName,
777                                              netbios_name,
778                                              ntds_guid);
779                 if (ret != LDB_SUCCESS) {
780                         talloc_free(tmp_ctx);
781                         return ret;
782                 }
783         }
784         talloc_free(tmp_ctx);
785         return LDB_SUCCESS;
786 }
787
788 static int acl_add(struct ldb_module *module, struct ldb_request *req)
789 {
790         int ret;
791         struct ldb_dn *parent;
792         struct ldb_context *ldb;
793         const struct dsdb_schema *schema;
794         const struct dsdb_class *objectclass;
795         struct ldb_dn *nc_root;
796         struct ldb_control *as_system;
797
798         if (ldb_dn_is_special(req->op.add.message->dn)) {
799                 return ldb_next_request(module, req);
800         }
801
802         as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
803         if (as_system != NULL) {
804                 as_system->critical = 0;
805         }
806
807         if (dsdb_module_am_system(module) || as_system) {
808                 return ldb_next_request(module, req);
809         }
810
811         ldb = ldb_module_get_ctx(module);
812
813         parent = ldb_dn_get_parent(req, req->op.add.message->dn);
814         if (parent == NULL) {
815                 return ldb_oom(ldb);
816         }
817
818         /* Creating an NC. There is probably something we should do here,
819          * but we will establish that later */
820
821         ret = dsdb_find_nc_root(ldb, req, req->op.add.message->dn, &nc_root);
822         if (ret != LDB_SUCCESS) {
823                 return ret;
824         }
825         if (ldb_dn_compare(nc_root, req->op.add.message->dn) == 0) {
826                 talloc_free(nc_root);
827                 return ldb_next_request(module, req);
828         }
829         talloc_free(nc_root);
830
831         schema = dsdb_get_schema(ldb, req);
832         if (!schema) {
833                 return ldb_operr(ldb);
834         }
835
836         objectclass = dsdb_get_structural_oc_from_msg(schema, req->op.add.message);
837         if (!objectclass) {
838                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
839                                        "acl: unable to find or validate structrual objectClass on %s\n",
840                                        ldb_dn_get_linearized(req->op.add.message->dn));
841                 return ldb_module_done(req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
842         }
843
844         ret = dsdb_module_check_access_on_dn(module, req, parent,
845                                              SEC_ADS_CREATE_CHILD,
846                                              &objectclass->schemaIDGUID, req);
847         if (ret != LDB_SUCCESS) {
848                 return ret;
849         }
850         return ldb_next_request(module, req);
851 }
852
853 /* ckecks if modifications are allowed on "Member" attribute */
854 static int acl_check_self_membership(TALLOC_CTX *mem_ctx,
855                                      struct ldb_module *module,
856                                      struct ldb_request *req,
857                                      struct security_descriptor *sd,
858                                      struct dom_sid *sid,
859                                      const struct dsdb_attribute *attr,
860                                      const struct dsdb_class *objectclass)
861 {
862         int ret;
863         unsigned int i;
864         struct ldb_context *ldb = ldb_module_get_ctx(module);
865         struct ldb_dn *user_dn;
866         struct ldb_message_element *member_el;
867         /* if we have wp, we can do whatever we like */
868         if (acl_check_access_on_attribute(module,
869                                           mem_ctx,
870                                           sd,
871                                           sid,
872                                           SEC_ADS_WRITE_PROP,
873                                           attr, objectclass) == LDB_SUCCESS) {
874                 return LDB_SUCCESS;
875         }
876         /* if we are adding/deleting ourselves, check for self membership */
877         ret = dsdb_find_dn_by_sid(ldb, mem_ctx, 
878                                   &acl_user_token(module)->sids[PRIMARY_USER_SID_INDEX], 
879                                   &user_dn);
880         if (ret != LDB_SUCCESS) {
881                 return ret;
882         }
883         member_el = ldb_msg_find_element(req->op.mod.message, "member");
884         if (!member_el) {
885                 return ldb_operr(ldb);
886         }
887         /* user can only remove oneself */
888         if (member_el->num_values == 0) {
889                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
890         }
891         for (i = 0; i < member_el->num_values; i++) {
892                 if (strcasecmp((const char *)member_el->values[i].data,
893                                ldb_dn_get_extended_linearized(mem_ctx, user_dn, 1)) != 0) {
894                         return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
895                 }
896         }
897         ret = acl_check_extended_right(mem_ctx, sd, acl_user_token(module),
898                                        GUID_DRS_SELF_MEMBERSHIP,
899                                        SEC_ADS_SELF_WRITE,
900                                        sid);
901         if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
902                 dsdb_acl_debug(sd, acl_user_token(module),
903                                req->op.mod.message->dn,
904                                true,
905                                10);
906         }
907         return ret;
908 }
909
910 static int acl_check_password_rights(TALLOC_CTX *mem_ctx,
911                                      struct ldb_module *module,
912                                      struct ldb_request *req,
913                                      struct security_descriptor *sd,
914                                      struct dom_sid *sid,
915                                      const struct dsdb_class *objectclass,
916                                      bool userPassword)
917 {
918         int ret = LDB_SUCCESS;
919         unsigned int del_attr_cnt = 0, add_attr_cnt = 0, rep_attr_cnt = 0;
920         struct ldb_message_element *el;
921         struct ldb_message *msg;
922         const char *passwordAttrs[] = { "userPassword", "clearTextPassword",
923                                         "unicodePwd", "dBCSPwd", NULL }, **l;
924         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
925
926         msg = ldb_msg_copy_shallow(tmp_ctx, req->op.mod.message);
927         if (msg == NULL) {
928                 return ldb_module_oom(module);
929         }
930         for (l = passwordAttrs; *l != NULL; l++) {
931                 if ((!userPassword) && (ldb_attr_cmp(*l, "userPassword") == 0)) {
932                         continue;
933                 }
934
935                 while ((el = ldb_msg_find_element(msg, *l)) != NULL) {
936                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE) {
937                                 ++del_attr_cnt;
938                         }
939                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD) {
940                                 ++add_attr_cnt;
941                         }
942                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) {
943                                 ++rep_attr_cnt;
944                         }
945                         ldb_msg_remove_element(msg, el);
946                 }
947         }
948
949         /* single deletes will be handled by the "password_hash" LDB module
950          * later in the stack, so we let it though here */
951         if ((del_attr_cnt > 0) && (add_attr_cnt == 0) && (rep_attr_cnt == 0)) {
952                 talloc_free(tmp_ctx);
953                 return LDB_SUCCESS;
954         }
955
956         if (ldb_request_get_control(req,
957                                     DSDB_CONTROL_PASSWORD_CHANGE_OID) != NULL) {
958                 /* The "DSDB_CONTROL_PASSWORD_CHANGE_OID" control means that we
959                  * have a user password change and not a set as the message
960                  * looks like. In it's value blob it contains the NT and/or LM
961                  * hash of the old password specified by the user.
962                  * This control is used by the SAMR and "kpasswd" password
963                  * change mechanisms. */
964                 ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
965                                                GUID_DRS_USER_CHANGE_PASSWORD,
966                                                SEC_ADS_CONTROL_ACCESS,
967                                                sid);
968         }
969         else if (rep_attr_cnt > 0 || (add_attr_cnt != del_attr_cnt)) {
970                 ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
971                                                GUID_DRS_FORCE_CHANGE_PASSWORD,
972                                                SEC_ADS_CONTROL_ACCESS,
973                                                sid);
974         }
975         else if (add_attr_cnt == 1 && del_attr_cnt == 1) {
976                 ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
977                                                GUID_DRS_USER_CHANGE_PASSWORD,
978                                                SEC_ADS_CONTROL_ACCESS,
979                                                sid);
980                 /* Very strange, but we get constraint violation in this case */
981                 if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
982                         ret = LDB_ERR_CONSTRAINT_VIOLATION;
983                 }
984         }
985         if (ret != LDB_SUCCESS) {
986                 dsdb_acl_debug(sd, acl_user_token(module),
987                                req->op.mod.message->dn,
988                                true,
989                                10);
990         }
991         talloc_free(tmp_ctx);
992         return ret;
993 }
994
995
996 static int acl_modify(struct ldb_module *module, struct ldb_request *req)
997 {
998         int ret;
999         struct ldb_context *ldb = ldb_module_get_ctx(module);
1000         const struct dsdb_schema *schema;
1001         unsigned int i;
1002         const struct dsdb_class *objectclass;
1003         uint32_t access_granted;
1004         NTSTATUS status;
1005         struct ldb_result *acl_res;
1006         struct security_descriptor *sd;
1007         struct dom_sid *sid = NULL;
1008         struct ldb_control *as_system;
1009         bool userPassword;
1010         TALLOC_CTX *tmp_ctx;
1011         const struct ldb_message *msg = req->op.mod.message;
1012         static const char *acl_attrs[] = {
1013                 "nTSecurityDescriptor",
1014                 "objectClass",
1015                 "objectSid",
1016                 NULL
1017         };
1018
1019         if (ldb_dn_is_special(msg->dn)) {
1020                 return ldb_next_request(module, req);
1021         }
1022
1023         as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1024         if (as_system != NULL) {
1025                 as_system->critical = 0;
1026         }
1027
1028         /* Don't print this debug statement if elements[0].name is going to be NULL */
1029         if (msg->num_elements > 0) {
1030                 DEBUG(10, ("ldb:acl_modify: %s\n", msg->elements[0].name));
1031         }
1032         if (dsdb_module_am_system(module) || as_system) {
1033                 return ldb_next_request(module, req);
1034         }
1035
1036         tmp_ctx = talloc_new(req);
1037         if (tmp_ctx == NULL) {
1038                 return ldb_oom(ldb);
1039         }
1040
1041         ret = dsdb_module_search_dn(module, tmp_ctx, &acl_res, msg->dn,
1042                                     acl_attrs,
1043                                     DSDB_FLAG_NEXT_MODULE |
1044                                     DSDB_FLAG_AS_SYSTEM |
1045                                     DSDB_SEARCH_SHOW_RECYCLED,
1046                                     req);
1047
1048         if (ret != LDB_SUCCESS) {
1049                 goto fail;
1050         }
1051
1052         userPassword = dsdb_user_password_support(module, req, req);
1053
1054         schema = dsdb_get_schema(ldb, tmp_ctx);
1055         if (!schema) {
1056                 talloc_free(tmp_ctx);
1057                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1058                                  "acl_modify: Error obtaining schema.");
1059         }
1060
1061         ret = dsdb_get_sd_from_ldb_message(ldb, tmp_ctx, acl_res->msgs[0], &sd);
1062         if (ret != LDB_SUCCESS) {
1063                 talloc_free(tmp_ctx);
1064                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1065                                  "acl_modify: Error retrieving security descriptor.");
1066         }
1067         /* Theoretically we pass the check if the object has no sd */
1068         if (!sd) {
1069                 goto success;
1070         }
1071
1072         objectclass = dsdb_get_structural_oc_from_msg(schema, acl_res->msgs[0]);
1073         if (!objectclass) {
1074                 talloc_free(tmp_ctx);
1075                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1076                                  "acl_modify: Error retrieving object class for GUID.");
1077         }
1078         sid = samdb_result_dom_sid(req, acl_res->msgs[0], "objectSid");
1079         for (i=0; i < msg->num_elements; i++) {
1080                 const struct ldb_message_element *el = &msg->elements[i];
1081                 const struct dsdb_attribute *attr;
1082
1083                 /*
1084                  * This basic attribute existence check with the right errorcode
1085                  * is needed since this module is the first one which requests
1086                  * schema attribute information.
1087                  * The complete attribute checking is done in the
1088                  * "objectclass_attrs" module behind this one.
1089                  *
1090                  * NOTE: "clearTextPassword" is not defined in the schema.
1091                  */
1092                 attr = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
1093                 if (!attr && ldb_attr_cmp("clearTextPassword", el->name) != 0) {
1094                         ldb_asprintf_errstring(ldb, "acl_modify: attribute '%s' "
1095                                                "on entry '%s' was not found in the schema!",
1096                                                req->op.mod.message->elements[i].name,
1097                                        ldb_dn_get_linearized(req->op.mod.message->dn));
1098                         ret =  LDB_ERR_NO_SUCH_ATTRIBUTE;
1099                         goto fail;
1100                 }
1101
1102                 if (ldb_attr_cmp("nTSecurityDescriptor", el->name) == 0) {
1103                         uint32_t sd_flags = dsdb_request_sd_flags(req, NULL);
1104                         uint32_t access_mask = 0;
1105
1106                         if (sd_flags & (SECINFO_OWNER|SECINFO_GROUP)) {
1107                                 access_mask |= SEC_STD_WRITE_OWNER;
1108                         }
1109                         if (sd_flags & SECINFO_DACL) {
1110                                 access_mask |= SEC_STD_WRITE_DAC;
1111                         }
1112                         if (sd_flags & SECINFO_SACL) {
1113                                 access_mask |= SEC_FLAG_SYSTEM_SECURITY;
1114                         }
1115
1116                         status = sec_access_check_ds(sd, acl_user_token(module),
1117                                              access_mask,
1118                                              &access_granted,
1119                                              NULL,
1120                                              sid);
1121
1122                         if (!NT_STATUS_IS_OK(status)) {
1123                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1124                                                        "Object %s has no write dacl access\n",
1125                                                        ldb_dn_get_linearized(msg->dn));
1126                                 dsdb_acl_debug(sd,
1127                                                acl_user_token(module),
1128                                                msg->dn,
1129                                                true,
1130                                                10);
1131                                 ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1132                                 goto fail;
1133                         }
1134                 } else if (ldb_attr_cmp("member", el->name) == 0) {
1135                         ret = acl_check_self_membership(tmp_ctx,
1136                                                         module,
1137                                                         req,
1138                                                         sd,
1139                                                         sid,
1140                                                         attr,
1141                                                         objectclass);
1142                         if (ret != LDB_SUCCESS) {
1143                                 goto fail;
1144                         }
1145                 } else if (ldb_attr_cmp("dBCSPwd", el->name) == 0) {
1146                         /* this one is not affected by any rights, we should let it through
1147                            so that passwords_hash returns the correct error */
1148                         continue;
1149                 } else if (ldb_attr_cmp("unicodePwd", el->name) == 0 ||
1150                            (userPassword && ldb_attr_cmp("userPassword", el->name) == 0) ||
1151                            ldb_attr_cmp("clearTextPassword", el->name) == 0) {
1152                         ret = acl_check_password_rights(tmp_ctx,
1153                                                         module,
1154                                                         req,
1155                                                         sd,
1156                                                         sid,
1157                                                         objectclass,
1158                                                         userPassword);
1159                         if (ret != LDB_SUCCESS) {
1160                                 goto fail;
1161                         }
1162                 } else if (ldb_attr_cmp("servicePrincipalName", el->name) == 0) {
1163                         ret = acl_check_spn(tmp_ctx,
1164                                             module,
1165                                             req,
1166                                             sd,
1167                                             sid,
1168                                             attr,
1169                                             objectclass);
1170                         if (ret != LDB_SUCCESS) {
1171                                 goto fail;
1172                         }
1173                 } else {
1174                         struct object_tree *root = NULL;
1175                         struct object_tree *new_node = NULL;
1176
1177                         if (!insert_in_object_tree(tmp_ctx,
1178                                                    &objectclass->schemaIDGUID,
1179                                                    SEC_ADS_WRITE_PROP,
1180                                                    &root, &new_node)) {
1181                                 talloc_free(tmp_ctx);
1182                                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1183                                                  "acl_modify: Error adding new node in object tree.");
1184                         }
1185
1186                         if (!insert_in_object_tree(tmp_ctx,
1187                                                    &attr->attributeSecurityGUID, SEC_ADS_WRITE_PROP,
1188                                                    &new_node, &new_node)) {
1189                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1190                                                        "acl_modify: cannot add to object tree securityGUID\n");
1191                                 ret = LDB_ERR_OPERATIONS_ERROR;
1192                                 goto fail;
1193                         }
1194
1195                         if (!insert_in_object_tree(tmp_ctx,
1196                                                    &attr->schemaIDGUID, SEC_ADS_WRITE_PROP, &new_node, &new_node)) {
1197                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1198                                                        "acl_modify: cannot add to object tree attributeGUID\n");
1199                                 ret = LDB_ERR_OPERATIONS_ERROR;
1200                                 goto fail;
1201                         }
1202
1203                         status = sec_access_check_ds(sd, acl_user_token(module),
1204                                                      SEC_ADS_WRITE_PROP,
1205                                                      &access_granted,
1206                                                      root,
1207                                                      sid);
1208                         if (!NT_STATUS_IS_OK(status)) {
1209                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1210                                                        "Object %s has no write property access\n",
1211                                                        ldb_dn_get_linearized(msg->dn));
1212                                 dsdb_acl_debug(sd,
1213                                                acl_user_token(module),
1214                                                msg->dn,
1215                                                true,
1216                                                10);
1217                                 ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1218                                 goto fail;
1219                         }
1220                 }
1221         }
1222
1223 success:
1224         talloc_free(tmp_ctx);
1225         return ldb_next_request(module, req);
1226 fail:
1227         talloc_free(tmp_ctx);
1228         return ret;
1229 }
1230
1231 /* similar to the modify for the time being.
1232  * We need to consider the special delete tree case, though - TODO */
1233 static int acl_delete(struct ldb_module *module, struct ldb_request *req)
1234 {
1235         int ret;
1236         struct ldb_dn *parent;
1237         struct ldb_context *ldb;
1238         struct ldb_dn *nc_root;
1239         struct ldb_control *as_system;
1240
1241         if (ldb_dn_is_special(req->op.del.dn)) {
1242                 return ldb_next_request(module, req);
1243         }
1244
1245         as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1246         if (as_system != NULL) {
1247                 as_system->critical = 0;
1248         }
1249
1250         if (dsdb_module_am_system(module) || as_system) {
1251                 return ldb_next_request(module, req);
1252         }
1253
1254         DEBUG(10, ("ldb:acl_delete: %s\n", ldb_dn_get_linearized(req->op.del.dn)));
1255
1256         ldb = ldb_module_get_ctx(module);
1257
1258         parent = ldb_dn_get_parent(req, req->op.del.dn);
1259         if (parent == NULL) {
1260                 return ldb_oom(ldb);
1261         }
1262
1263         /* Make sure we aren't deleting a NC */
1264
1265         ret = dsdb_find_nc_root(ldb, req, req->op.del.dn, &nc_root);
1266         if (ret != LDB_SUCCESS) {
1267                 return ret;
1268         }
1269         if (ldb_dn_compare(nc_root, req->op.del.dn) == 0) {
1270                 talloc_free(nc_root);
1271                 DEBUG(10,("acl:deleting a NC\n"));
1272                 /* Windows returns "ERR_UNWILLING_TO_PERFORM */
1273                 return ldb_module_done(req, NULL, NULL,
1274                                        LDB_ERR_UNWILLING_TO_PERFORM);
1275         }
1276         talloc_free(nc_root);
1277
1278         if (ldb_request_get_control(req, LDB_CONTROL_TREE_DELETE_OID)) {
1279                 ret = dsdb_module_check_access_on_dn(module, req,
1280                                                      req->op.del.dn,
1281                                                      SEC_ADS_DELETE_TREE, NULL,
1282                                                      req);
1283                 if (ret != LDB_SUCCESS) {
1284                         return ret;
1285                 }
1286
1287                 return ldb_next_request(module, req);
1288         }
1289
1290         /* First check if we have delete object right */
1291         ret = dsdb_module_check_access_on_dn(module, req, req->op.del.dn,
1292                                              SEC_STD_DELETE, NULL, req);
1293         if (ret == LDB_SUCCESS) {
1294                 return ldb_next_request(module, req);
1295         }
1296
1297         /* Nope, we don't have delete object. Lets check if we have delete
1298          * child on the parent */
1299         ret = dsdb_module_check_access_on_dn(module, req, parent,
1300                                              SEC_ADS_DELETE_CHILD, NULL, req);
1301         if (ret != LDB_SUCCESS) {
1302                 return ret;
1303         }
1304
1305         return ldb_next_request(module, req);
1306 }
1307
1308 static int acl_rename(struct ldb_module *module, struct ldb_request *req)
1309 {
1310         int ret;
1311         struct ldb_dn *oldparent;
1312         struct ldb_dn *newparent;
1313         const struct dsdb_schema *schema;
1314         const struct dsdb_class *objectclass;
1315         struct ldb_context *ldb;
1316         struct security_descriptor *sd = NULL;
1317         struct dom_sid *sid = NULL;
1318         struct ldb_result *acl_res;
1319         const struct GUID *guid;
1320         struct ldb_dn *nc_root;
1321         struct object_tree *root = NULL;
1322         struct object_tree *new_node = NULL;
1323         struct ldb_control *as_system;
1324         TALLOC_CTX *tmp_ctx;
1325         NTSTATUS status;
1326         uint32_t access_granted;
1327         const char *rdn_name;
1328         static const char *acl_attrs[] = {
1329                 "nTSecurityDescriptor",
1330                 "objectClass",
1331                 "objectSid",
1332                 NULL
1333         };
1334
1335         if (ldb_dn_is_special(req->op.rename.olddn)) {
1336                 return ldb_next_request(module, req);
1337         }
1338
1339         as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1340         if (as_system != NULL) {
1341                 as_system->critical = 0;
1342         }
1343
1344         DEBUG(10, ("ldb:acl_rename: %s\n", ldb_dn_get_linearized(req->op.rename.olddn)));
1345         if (dsdb_module_am_system(module) || as_system) {
1346                 return ldb_next_request(module, req);
1347         }
1348
1349         ldb = ldb_module_get_ctx(module);
1350
1351         tmp_ctx = talloc_new(req);
1352         if (tmp_ctx == NULL) {
1353                 return ldb_oom(ldb);
1354         }
1355
1356         oldparent = ldb_dn_get_parent(tmp_ctx, req->op.rename.olddn);
1357         if (oldparent == NULL) {
1358                 return ldb_oom(ldb);
1359         }
1360         newparent = ldb_dn_get_parent(tmp_ctx, req->op.rename.newdn);
1361         if (newparent == NULL) {
1362                 return ldb_oom(ldb);
1363         }
1364
1365         /* Make sure we aren't renaming/moving a NC */
1366
1367         ret = dsdb_find_nc_root(ldb, req, req->op.rename.olddn, &nc_root);
1368         if (ret != LDB_SUCCESS) {
1369                 return ret;
1370         }
1371         if (ldb_dn_compare(nc_root, req->op.rename.olddn) == 0) {
1372                 talloc_free(nc_root);
1373                 DEBUG(10,("acl:renaming/moving a NC\n"));
1374                 /* Windows returns "ERR_UNWILLING_TO_PERFORM */
1375                 return ldb_module_done(req, NULL, NULL,
1376                                        LDB_ERR_UNWILLING_TO_PERFORM);
1377         }
1378         talloc_free(nc_root);
1379
1380         /* Look for the parent */
1381
1382         ret = dsdb_module_search_dn(module, tmp_ctx, &acl_res,
1383                                     req->op.rename.olddn, acl_attrs,
1384                                     DSDB_FLAG_NEXT_MODULE |
1385                                     DSDB_FLAG_AS_SYSTEM |
1386                                     DSDB_SEARCH_SHOW_RECYCLED, req);
1387         /* we sould be able to find the parent */
1388         if (ret != LDB_SUCCESS) {
1389                 DEBUG(10,("acl: failed to find object %s\n",
1390                           ldb_dn_get_linearized(req->op.rename.olddn)));
1391                 talloc_free(tmp_ctx);
1392                 return ret;
1393         }
1394
1395         schema = dsdb_get_schema(ldb, acl_res);
1396         if (!schema) {
1397                 talloc_free(tmp_ctx);
1398                 return ldb_operr(ldb);
1399         }
1400
1401         objectclass = dsdb_get_structural_oc_from_msg(schema, acl_res->msgs[0]);
1402         if (!objectclass) {
1403                 talloc_free(tmp_ctx);
1404                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1405                                  "acl_modify: Error retrieving object class for GUID.");
1406         }
1407
1408         if (!insert_in_object_tree(tmp_ctx, &objectclass->schemaIDGUID, SEC_ADS_WRITE_PROP,
1409                                    &root, &new_node)) {
1410                 talloc_free(tmp_ctx);
1411                 return ldb_operr(ldb);
1412         }
1413
1414         guid = attribute_schemaid_guid_by_lDAPDisplayName(schema,
1415                                                           "name");
1416         if (!insert_in_object_tree(tmp_ctx, guid, SEC_ADS_WRITE_PROP,
1417                                    &new_node, &new_node)) {
1418                 talloc_free(tmp_ctx);
1419                 return ldb_operr(ldb);
1420         }
1421
1422         rdn_name = ldb_dn_get_rdn_name(req->op.rename.olddn);
1423         if (rdn_name == NULL) {
1424                 talloc_free(tmp_ctx);
1425                 return ldb_operr(ldb);
1426         }
1427         guid = attribute_schemaid_guid_by_lDAPDisplayName(schema,
1428                                                           rdn_name);
1429         if (!insert_in_object_tree(tmp_ctx, guid, SEC_ADS_WRITE_PROP,
1430                                    &new_node, &new_node)) {
1431                 talloc_free(tmp_ctx);
1432                 return ldb_operr(ldb);
1433         };
1434
1435         ret = dsdb_get_sd_from_ldb_message(ldb, req, acl_res->msgs[0], &sd);
1436
1437         if (ret != LDB_SUCCESS) {
1438                 talloc_free(tmp_ctx);
1439                 return ldb_operr(ldb);
1440         }
1441         /* Theoretically we pass the check if the object has no sd */
1442         if (!sd) {
1443                 talloc_free(tmp_ctx);
1444                 return LDB_SUCCESS;
1445         }
1446         sid = samdb_result_dom_sid(req, acl_res->msgs[0], "objectSid");
1447         status = sec_access_check_ds(sd, acl_user_token(module),
1448                                      SEC_ADS_WRITE_PROP,
1449                                      &access_granted,
1450                                      root,
1451                                      sid);
1452
1453         if (!NT_STATUS_IS_OK(status)) {
1454                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1455                                        "Object %s has no wp on name\n",
1456                                        ldb_dn_get_linearized(req->op.rename.olddn));
1457                 dsdb_acl_debug(sd,
1458                           acl_user_token(module),
1459                           req->op.rename.olddn,
1460                           true,
1461                           10);
1462                 talloc_free(tmp_ctx);
1463                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1464         }
1465
1466         if (ldb_dn_compare(oldparent, newparent) == 0) {
1467                 /* regular rename, not move, nothing more to do */
1468                 talloc_free(tmp_ctx);
1469                 return ldb_next_request(module, req);
1470         }
1471
1472         /* new parent should have create child */
1473         root = NULL;
1474         new_node = NULL;
1475
1476         ret = dsdb_module_check_access_on_dn(module, req, newparent,
1477                                              SEC_ADS_CREATE_CHILD,
1478                                              &objectclass->schemaIDGUID, req);
1479         if (ret != LDB_SUCCESS) {
1480                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1481                                        "acl:access_denied renaming %s",
1482                                        ldb_dn_get_linearized(req->op.rename.olddn));
1483                 talloc_free(tmp_ctx);
1484                 return ret;
1485         }
1486         /* do we have delete object on the object? */
1487
1488         status = sec_access_check_ds(sd, acl_user_token(module),
1489                                      SEC_STD_DELETE,
1490                                      &access_granted,
1491                                      NULL,
1492                                      sid);
1493
1494         if (NT_STATUS_IS_OK(status)) {
1495                 talloc_free(tmp_ctx);
1496                 return ldb_next_request(module, req);
1497         }
1498         /* what about delete child on the current parent */
1499         ret = dsdb_module_check_access_on_dn(module, req, oldparent, SEC_ADS_DELETE_CHILD, NULL, req);
1500         if (ret != LDB_SUCCESS) {
1501                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1502                                        "acl:access_denied renaming %s", ldb_dn_get_linearized(req->op.rename.olddn));
1503                 talloc_free(tmp_ctx);
1504                 return ldb_module_done(req, NULL, NULL, ret);
1505         }
1506
1507         talloc_free(tmp_ctx);
1508
1509         return ldb_next_request(module, req);
1510 }
1511
1512 static int acl_search_update_confidential_attrs(struct acl_context *ac,
1513                                                 struct acl_private *data)
1514 {
1515         struct dsdb_attribute *a;
1516         uint32_t n = 0;
1517
1518         if (data->acl_search) {
1519                 /*
1520                  * If acl:search is activated, the acl_read module
1521                  * protects confidential attributes.
1522                  */
1523                 return LDB_SUCCESS;
1524         }
1525
1526         if ((ac->schema == data->cached_schema_ptr) &&
1527             (ac->schema->loaded_usn == data->cached_schema_loaded_usn) &&
1528             (ac->schema->metadata_usn == data->cached_schema_metadata_usn))
1529         {
1530                 return LDB_SUCCESS;
1531         }
1532
1533         data->cached_schema_ptr = NULL;
1534         data->cached_schema_loaded_usn = 0;
1535         data->cached_schema_metadata_usn = 0;
1536         TALLOC_FREE(data->confidential_attrs);
1537
1538         if (ac->schema == NULL) {
1539                 return LDB_SUCCESS;
1540         }
1541
1542         for (a = ac->schema->attributes; a; a = a->next) {
1543                 const char **attrs = data->confidential_attrs;
1544
1545                 if (!(a->searchFlags & SEARCH_FLAG_CONFIDENTIAL)) {
1546                         continue;
1547                 }
1548
1549                 attrs = talloc_realloc(data, attrs, const char *, n + 2);
1550                 if (attrs == NULL) {
1551                         TALLOC_FREE(data->confidential_attrs);
1552                         return ldb_module_oom(ac->module);
1553                 }
1554
1555                 attrs[n] = a->lDAPDisplayName;
1556                 attrs[n+1] = NULL;
1557                 n++;
1558
1559                 data->confidential_attrs = attrs;
1560         }
1561
1562         data->cached_schema_ptr = ac->schema;
1563         data->cached_schema_loaded_usn = ac->schema->loaded_usn;
1564         data->cached_schema_metadata_usn = ac->schema->metadata_usn;
1565
1566         return LDB_SUCCESS;
1567 }
1568
1569 static int acl_search_callback(struct ldb_request *req, struct ldb_reply *ares)
1570 {
1571         struct acl_context *ac;
1572         struct acl_private *data;
1573         struct ldb_result *acl_res;
1574         static const char *acl_attrs[] = {
1575                 "objectClass",
1576                 "nTSecurityDescriptor",
1577                 "objectSid",
1578                 NULL
1579         };
1580         int ret;
1581         unsigned int i;
1582
1583         ac = talloc_get_type(req->context, struct acl_context);
1584         data = talloc_get_type(ldb_module_get_private(ac->module), struct acl_private);
1585         if (!ares) {
1586                 return ldb_module_done(ac->req, NULL, NULL,
1587                                        LDB_ERR_OPERATIONS_ERROR);
1588         }
1589         if (ares->error != LDB_SUCCESS) {
1590                 return ldb_module_done(ac->req, ares->controls,
1591                                        ares->response, ares->error);
1592         }
1593
1594         switch (ares->type) {
1595         case LDB_REPLY_ENTRY:
1596                 if (ac->constructed_attrs) {
1597                         ret = dsdb_module_search_dn(ac->module, ac, &acl_res, ares->message->dn, 
1598                                                     acl_attrs,
1599                                                     DSDB_FLAG_NEXT_MODULE |
1600                                                     DSDB_FLAG_AS_SYSTEM |
1601                                                     DSDB_SEARCH_SHOW_RECYCLED,
1602                                                     req);
1603                         if (ret != LDB_SUCCESS) {
1604                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1605                         }
1606                 }
1607
1608                 if (ac->allowedAttributes || ac->allowedAttributesEffective) {
1609                         ret = acl_allowedAttributes(ac->module, ac->schema,
1610                                                     acl_res->msgs[0],
1611                                                     ares->message, ac);
1612                         if (ret != LDB_SUCCESS) {
1613                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1614                         }
1615                 }
1616
1617                 if (ac->allowedChildClasses) {
1618                         ret = acl_childClasses(ac->module, ac->schema,
1619                                                acl_res->msgs[0],
1620                                                ares->message,
1621                                                "allowedChildClasses");
1622                         if (ret != LDB_SUCCESS) {
1623                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1624                         }
1625                 }
1626
1627                 if (ac->allowedChildClassesEffective) {
1628                         ret = acl_childClassesEffective(ac->module, ac->schema,
1629                                                         acl_res->msgs[0],
1630                                                         ares->message, ac);
1631                         if (ret != LDB_SUCCESS) {
1632                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1633                         }
1634                 }
1635
1636                 if (ac->sDRightsEffective) {
1637                         ret = acl_sDRightsEffective(ac->module,
1638                                                     acl_res->msgs[0],
1639                                                     ares->message, ac);
1640                         if (ret != LDB_SUCCESS) {
1641                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1642                         }
1643                 }
1644
1645                 if (data == NULL) {
1646                         return ldb_module_send_entry(ac->req, ares->message,
1647                                                      ares->controls);
1648                 }
1649
1650                 if (ac->am_system) {
1651                         return ldb_module_send_entry(ac->req, ares->message,
1652                                                      ares->controls);
1653                 }
1654
1655                 if (data->password_attrs != NULL) {
1656                         for (i = 0; data->password_attrs[i]; i++) {
1657                                 if ((!ac->userPassword) &&
1658                                     (ldb_attr_cmp(data->password_attrs[i],
1659                                                   "userPassword") == 0))
1660                                 {
1661                                                 continue;
1662                                 }
1663
1664                                 ldb_msg_remove_attr(ares->message, data->password_attrs[i]);
1665                         }
1666                 }
1667
1668                 if (ac->am_administrator) {
1669                         return ldb_module_send_entry(ac->req, ares->message,
1670                                                      ares->controls);
1671                 }
1672
1673                 ret = acl_search_update_confidential_attrs(ac, data);
1674                 if (ret != LDB_SUCCESS) {
1675                         return ret;
1676                 }
1677
1678                 if (data->confidential_attrs != NULL) {
1679                         for (i = 0; data->confidential_attrs[i]; i++) {
1680                                 ldb_msg_remove_attr(ares->message,
1681                                                     data->confidential_attrs[i]);
1682                         }
1683                 }
1684
1685                 return ldb_module_send_entry(ac->req, ares->message, ares->controls);
1686
1687         case LDB_REPLY_REFERRAL:
1688                 return ldb_module_send_referral(ac->req, ares->referral);
1689
1690         case LDB_REPLY_DONE:
1691                 return ldb_module_done(ac->req, ares->controls,
1692                                        ares->response, LDB_SUCCESS);
1693
1694         }
1695         return LDB_SUCCESS;
1696 }
1697
1698 static int acl_search(struct ldb_module *module, struct ldb_request *req)
1699 {
1700         struct ldb_context *ldb;
1701         struct acl_context *ac;
1702         struct ldb_parse_tree *down_tree;
1703         struct ldb_request *down_req;
1704         struct acl_private *data;
1705         int ret;
1706         unsigned int i;
1707
1708         if (ldb_dn_is_special(req->op.search.base)) {
1709                 return ldb_next_request(module, req);
1710         }
1711
1712         ldb = ldb_module_get_ctx(module);
1713
1714         ac = talloc_zero(req, struct acl_context);
1715         if (ac == NULL) {
1716                 return ldb_oom(ldb);
1717         }
1718         data = talloc_get_type(ldb_module_get_private(module), struct acl_private);
1719
1720         ac->module = module;
1721         ac->req = req;
1722         ac->am_system = dsdb_module_am_system(module);
1723         ac->am_administrator = dsdb_module_am_administrator(module);
1724         ac->constructed_attrs = false;
1725         ac->modify_search = true;
1726         ac->allowedAttributes = ldb_attr_in_list(req->op.search.attrs, "allowedAttributes");
1727         ac->allowedAttributesEffective = ldb_attr_in_list(req->op.search.attrs, "allowedAttributesEffective");
1728         ac->allowedChildClasses = ldb_attr_in_list(req->op.search.attrs, "allowedChildClasses");
1729         ac->allowedChildClassesEffective = ldb_attr_in_list(req->op.search.attrs, "allowedChildClassesEffective");
1730         ac->sDRightsEffective = ldb_attr_in_list(req->op.search.attrs, "sDRightsEffective");
1731         ac->userPassword = true;
1732         ac->schema = dsdb_get_schema(ldb, ac);
1733
1734         ac->constructed_attrs |= ac->allowedAttributes;
1735         ac->constructed_attrs |= ac->allowedChildClasses;
1736         ac->constructed_attrs |= ac->allowedChildClassesEffective;
1737         ac->constructed_attrs |= ac->allowedAttributesEffective;
1738         ac->constructed_attrs |= ac->sDRightsEffective;
1739
1740         if (data == NULL) {
1741                 ac->modify_search = false;
1742         }
1743         if (ac->am_system) {
1744                 ac->modify_search = false;
1745         }
1746
1747         if (!ac->constructed_attrs && !ac->modify_search) {
1748                 talloc_free(ac);
1749                 return ldb_next_request(module, req);
1750         }
1751
1752         if (!ac->am_system) {
1753                 ac->userPassword = dsdb_user_password_support(module, ac, req);
1754         }
1755
1756         ret = acl_search_update_confidential_attrs(ac, data);
1757         if (ret != LDB_SUCCESS) {
1758                 return ret;
1759         }
1760
1761         down_tree = ldb_parse_tree_copy_shallow(ac, req->op.search.tree);
1762         if (down_tree == NULL) {
1763                 return ldb_oom(ldb);
1764         }
1765
1766         if (!ac->am_system && data->password_attrs) {
1767                 for (i = 0; data->password_attrs[i]; i++) {
1768                         if ((!ac->userPassword) &&
1769                             (ldb_attr_cmp(data->password_attrs[i],
1770                                           "userPassword") == 0))
1771                         {
1772                                 continue;
1773                         }
1774
1775                         ldb_parse_tree_attr_replace(down_tree,
1776                                                     data->password_attrs[i],
1777                                                     "kludgeACLredactedattribute");
1778                 }
1779         }
1780
1781         if (!ac->am_system && !ac->am_administrator && data->confidential_attrs) {
1782                 for (i = 0; data->confidential_attrs[i]; i++) {
1783                         ldb_parse_tree_attr_replace(down_tree,
1784                                                     data->confidential_attrs[i],
1785                                                     "kludgeACLredactedattribute");
1786                 }
1787         }
1788
1789         ret = ldb_build_search_req_ex(&down_req,
1790                                       ldb, ac,
1791                                       req->op.search.base,
1792                                       req->op.search.scope,
1793                                       down_tree,
1794                                       req->op.search.attrs,
1795                                       req->controls,
1796                                       ac, acl_search_callback,
1797                                       req);
1798         LDB_REQ_SET_LOCATION(down_req);
1799         if (ret != LDB_SUCCESS) {
1800                 return ret;
1801         }
1802         /* perform the search */
1803         return ldb_next_request(module, down_req);
1804 }
1805
1806 static int acl_extended(struct ldb_module *module, struct ldb_request *req)
1807 {
1808         struct ldb_context *ldb = ldb_module_get_ctx(module);
1809         struct ldb_control *as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1810
1811         /* allow everybody to read the sequence number */
1812         if (strcmp(req->op.extended.oid,
1813                    LDB_EXTENDED_SEQUENCE_NUMBER) == 0) {
1814                 return ldb_next_request(module, req);
1815         }
1816
1817         if (dsdb_module_am_system(module) ||
1818             dsdb_module_am_administrator(module) || as_system) {
1819                 return ldb_next_request(module, req);
1820         } else {
1821                 ldb_asprintf_errstring(ldb,
1822                                        "acl_extended: "
1823                                        "attempted database modify not permitted. "
1824                                        "User %s is not SYSTEM or an administrator",
1825                                        acl_user_name(req, module));
1826                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1827         }
1828 }
1829
1830 static const struct ldb_module_ops ldb_acl_module_ops = {
1831         .name              = "acl",
1832         .search            = acl_search,
1833         .add               = acl_add,
1834         .modify            = acl_modify,
1835         .del               = acl_delete,
1836         .rename            = acl_rename,
1837         .extended          = acl_extended,
1838         .init_context      = acl_module_init
1839 };
1840
1841 int ldb_acl_module_init(const char *version)
1842 {
1843         LDB_MODULE_CHECK_VERSION(version);
1844         return ldb_register_module(&ldb_acl_module_ops);
1845 }