dsdb-acl: Pass the structural objectClass into acl_check_access_on_attribute
[metze/samba/wip.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                         ret = acl_check_access_on_class(module,
438                                                         schema,
439                                                         msg,
440                                                         sd,
441                                                         acl_user_token(module),
442                                                         sid,
443                                                         SEC_ADS_CREATE_CHILD,
444                                                         sclass->possibleInferiors[j]);
445                         if (ret == LDB_SUCCESS) {
446                                 ldb_msg_add_string(msg, "allowedChildClassesEffective",
447                                                    sclass->possibleInferiors[j]);
448                         }
449                 }
450         }
451         allowedClasses = ldb_msg_find_element(msg, "allowedChildClassesEffective");
452         if (!allowedClasses) {
453                 return LDB_SUCCESS;
454         }
455
456         if (allowedClasses->num_values > 1) {
457                 TYPESAFE_QSORT(allowedClasses->values, allowedClasses->num_values, data_blob_cmp);
458                 for (i=1 ; i < allowedClasses->num_values; i++) {
459                         struct ldb_val *val1 = &allowedClasses->values[i-1];
460                         struct ldb_val *val2 = &allowedClasses->values[i];
461                         if (data_blob_cmp(val1, val2) == 0) {
462                                 memmove(val1, val2, (allowedClasses->num_values - i) * sizeof( struct ldb_val));
463                                 allowedClasses->num_values--;
464                                 i--;
465                         }
466                 }
467         }
468         return LDB_SUCCESS;
469 }
470
471 static int acl_sDRightsEffective(struct ldb_module *module,
472                                  struct ldb_message *sd_msg,
473                                  struct ldb_message *msg,
474                                  struct acl_context *ac)
475 {
476         struct ldb_context *ldb = ldb_module_get_ctx(module);
477         struct ldb_message_element *rightsEffective;
478         int ret;
479         struct security_descriptor *sd;
480         struct ldb_control *as_system = ldb_request_get_control(ac->req,
481                                                                 LDB_CONTROL_AS_SYSTEM_OID);
482         struct dom_sid *sid = NULL;
483         uint32_t flags = 0;
484
485         if (as_system != NULL) {
486                 as_system->critical = 0;
487         }
488
489         /* Must remove any existing attribute, or else confusion reins */
490         ldb_msg_remove_attr(msg, "sDRightsEffective");
491         ret = ldb_msg_add_empty(msg, "sDRightsEffective", 0, &rightsEffective);
492         if (ret != LDB_SUCCESS) {
493                 return ret;
494         }
495         if (ac->am_system || as_system) {
496                 flags = SECINFO_OWNER | SECINFO_GROUP |  SECINFO_SACL |  SECINFO_DACL;
497         } else {
498                 const struct dsdb_class *objectclass;
499                 const struct dsdb_attribute *attr;
500
501                 objectclass = dsdb_get_structural_oc_from_msg(ac->schema, sd_msg);
502                 if (objectclass == NULL) {
503                         return ldb_operr(ldb);
504                 }
505
506                 attr = dsdb_attribute_by_lDAPDisplayName(ac->schema,
507                                                          "nTSecurityDescriptor");
508                 if (attr == NULL) {
509                         return ldb_operr(ldb);
510                 }
511
512                 /* Get the security descriptor from the message */
513                 ret = dsdb_get_sd_from_ldb_message(ldb, msg, sd_msg, &sd);
514                 if (ret != LDB_SUCCESS) {
515                         return ret;
516                 }
517                 sid = samdb_result_dom_sid(msg, sd_msg, "objectSid");
518                 ret = acl_check_access_on_attribute(module,
519                                                     msg,
520                                                     sd,
521                                                     sid,
522                                                     SEC_STD_WRITE_OWNER,
523                                                     attr,
524                                                     objectclass);
525                 if (ret == LDB_SUCCESS) {
526                         flags |= SECINFO_OWNER | SECINFO_GROUP;
527                 }
528                 ret = acl_check_access_on_attribute(module,
529                                                     msg,
530                                                     sd,
531                                                     sid,
532                                                     SEC_STD_WRITE_DAC,
533                                                     attr,
534                                                     objectclass);
535                 if (ret == LDB_SUCCESS) {
536                         flags |= SECINFO_DACL;
537                 }
538                 ret = acl_check_access_on_attribute(module,
539                                                     msg,
540                                                     sd,
541                                                     sid,
542                                                     SEC_FLAG_SYSTEM_SECURITY,
543                                                     attr,
544                                                     objectclass);
545                 if (ret == LDB_SUCCESS) {
546                         flags |= SECINFO_SACL;
547                 }
548         }
549         return samdb_msg_add_uint(ldb_module_get_ctx(module), msg, msg,
550                                   "sDRightsEffective", flags);
551 }
552
553 static int acl_validate_spn_value(TALLOC_CTX *mem_ctx,
554                                   struct ldb_context *ldb,
555                                   const char *spn_value,
556                                   uint32_t userAccountControl,
557                                   const char *samAccountName,
558                                   const char *dnsHostName,
559                                   const char *netbios_name,
560                                   const char *ntds_guid)
561 {
562         int ret;
563         krb5_context krb_ctx;
564         krb5_error_code kerr;
565         krb5_principal principal;
566         char *instanceName;
567         char *serviceType;
568         char *serviceName;
569         const char *forest_name = samdb_forest_name(ldb, mem_ctx);
570         const char *base_domain = samdb_default_domain_name(ldb, mem_ctx);
571         struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
572                                                           struct loadparm_context);
573         bool is_dc = (userAccountControl & UF_SERVER_TRUST_ACCOUNT) ||
574                 (userAccountControl & UF_PARTIAL_SECRETS_ACCOUNT);
575
576         if (strcasecmp_m(spn_value, samAccountName) == 0) {
577                 /* MacOS X sets this value, and setting an SPN of your
578                  * own samAccountName is both pointless and safe */
579                 return LDB_SUCCESS;
580         }
581
582         kerr = smb_krb5_init_context_basic(mem_ctx,
583                                            lp_ctx,
584                                            &krb_ctx);
585         if (kerr != 0) {
586                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
587                                  "Could not initialize kerberos context.");
588         }
589
590         ret = krb5_parse_name(krb_ctx, spn_value, &principal);
591         if (ret) {
592                 krb5_free_context(krb_ctx);
593                 return LDB_ERR_CONSTRAINT_VIOLATION;
594         }
595
596         if (principal->name.name_string.len < 2) {
597                 goto fail;
598         }
599
600         instanceName = principal->name.name_string.val[1];
601         serviceType = principal->name.name_string.val[0];
602         if (principal->name.name_string.len == 3) {
603                 serviceName = principal->name.name_string.val[2];
604         } else {
605                 serviceName = NULL;
606         }
607
608         if (serviceName) {
609                 if (!is_dc) {
610                         goto fail;
611                 }
612                 if (strcasecmp(serviceType, "ldap") == 0) {
613                         if (strcasecmp(serviceName, netbios_name) != 0 &&
614                             strcasecmp(serviceName, forest_name) != 0) {
615                                 goto fail;
616                         }
617
618                 } else if (strcasecmp(serviceType, "gc") == 0) {
619                         if (strcasecmp(serviceName, forest_name) != 0) {
620                                 goto fail;
621                         }
622                 } else {
623                         if (strcasecmp(serviceName, base_domain) != 0 &&
624                             strcasecmp(serviceName, netbios_name) != 0) {
625                                 goto fail;
626                         }
627                 }
628         }
629         /* instanceName can be samAccountName without $ or dnsHostName
630          * or "ntds_guid._msdcs.forest_domain for DC objects */
631         if (strlen(instanceName) == (strlen(samAccountName) - 1)
632             && strncasecmp(instanceName, samAccountName, strlen(samAccountName) - 1) == 0) {
633                 goto success;
634         } else if (dnsHostName != NULL && strcasecmp(instanceName, dnsHostName) == 0) {
635                 goto success;
636         } else if (is_dc) {
637                 const char *guid_str;
638                 guid_str = talloc_asprintf(mem_ctx,"%s._msdcs.%s",
639                                            ntds_guid,
640                                            forest_name);
641                 if (strcasecmp(instanceName, guid_str) == 0) {
642                         goto success;
643                 }
644         }
645
646 fail:
647         krb5_free_principal(krb_ctx, principal);
648         krb5_free_context(krb_ctx);
649         return LDB_ERR_CONSTRAINT_VIOLATION;
650
651 success:
652         krb5_free_principal(krb_ctx, principal);
653         krb5_free_context(krb_ctx);
654         return LDB_SUCCESS;
655 }
656
657 static int acl_check_spn(TALLOC_CTX *mem_ctx,
658                          struct ldb_module *module,
659                          struct ldb_request *req,
660                          struct security_descriptor *sd,
661                          struct dom_sid *sid,
662                          const struct dsdb_attribute *attr,
663                          const struct dsdb_class *objectclass)
664 {
665         int ret;
666         unsigned int i;
667         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
668         struct ldb_context *ldb = ldb_module_get_ctx(module);
669         struct ldb_result *acl_res;
670         struct ldb_result *netbios_res;
671         struct ldb_message_element *el;
672         struct ldb_dn *partitions_dn = samdb_partitions_dn(ldb, tmp_ctx);
673         uint32_t userAccountControl;
674         const char *samAccountName;
675         const char *dnsHostName;
676         const char *netbios_name;
677         struct GUID ntds;
678         char *ntds_guid = NULL;
679
680         static const char *acl_attrs[] = {
681                 "samAccountName",
682                 "dnsHostName",
683                 "userAccountControl",
684                 NULL
685         };
686         static const char *netbios_attrs[] = {
687                 "nETBIOSName",
688                 NULL
689         };
690
691         /* if we have wp, we can do whatever we like */
692         if (acl_check_access_on_attribute(module,
693                                           tmp_ctx,
694                                           sd,
695                                           sid,
696                                           SEC_ADS_WRITE_PROP,
697                                           attr, objectclass) == LDB_SUCCESS) {
698                 talloc_free(tmp_ctx);
699                 return LDB_SUCCESS;
700         }
701
702         ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
703                                        GUID_DRS_VALIDATE_SPN,
704                                        SEC_ADS_SELF_WRITE,
705                                        sid);
706
707         if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
708                 dsdb_acl_debug(sd, acl_user_token(module),
709                                req->op.mod.message->dn,
710                                true,
711                                10);
712                 talloc_free(tmp_ctx);
713                 return ret;
714         }
715
716         ret = dsdb_module_search_dn(module, tmp_ctx,
717                                     &acl_res, req->op.mod.message->dn,
718                                     acl_attrs,
719                                     DSDB_FLAG_NEXT_MODULE |
720                                     DSDB_FLAG_AS_SYSTEM |
721                                     DSDB_SEARCH_SHOW_RECYCLED,
722                                     req);
723         if (ret != LDB_SUCCESS) {
724                 talloc_free(tmp_ctx);
725                 return ret;
726         }
727
728         userAccountControl = ldb_msg_find_attr_as_uint(acl_res->msgs[0], "userAccountControl", 0);
729         dnsHostName = ldb_msg_find_attr_as_string(acl_res->msgs[0], "dnsHostName", NULL);
730         samAccountName = ldb_msg_find_attr_as_string(acl_res->msgs[0], "samAccountName", NULL);
731
732         ret = dsdb_module_search(module, tmp_ctx,
733                                  &netbios_res, partitions_dn,
734                                  LDB_SCOPE_ONELEVEL,
735                                  netbios_attrs,
736                                  DSDB_FLAG_NEXT_MODULE |
737                                  DSDB_FLAG_AS_SYSTEM,
738                                  req,
739                                  "(ncName=%s)",
740                                  ldb_dn_get_linearized(ldb_get_default_basedn(ldb)));
741
742         netbios_name = ldb_msg_find_attr_as_string(netbios_res->msgs[0], "nETBIOSName", NULL);
743
744         el = ldb_msg_find_element(req->op.mod.message, "servicePrincipalName");
745         if (!el) {
746                 talloc_free(tmp_ctx);
747                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
748                                          "Error finding element for servicePrincipalName.");
749         }
750
751         /* NTDSDSA objectGuid of object we are checking SPN for */
752         if (userAccountControl & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
753                 ret = dsdb_module_find_ntdsguid_for_computer(module, tmp_ctx,
754                                                              req->op.mod.message->dn, &ntds, req);
755                 if (ret != LDB_SUCCESS) {
756                         ldb_asprintf_errstring(ldb, "Failed to find NTDSDSA objectGuid for %s: %s",
757                                                ldb_dn_get_linearized(req->op.mod.message->dn),
758                                                ldb_strerror(ret));
759                         talloc_free(tmp_ctx);
760                         return LDB_ERR_OPERATIONS_ERROR;
761                 }
762                 ntds_guid = GUID_string(tmp_ctx, &ntds);
763         }
764
765         for (i=0; i < el->num_values; i++) {
766                 ret = acl_validate_spn_value(tmp_ctx,
767                                              ldb,
768                                              (char *)el->values[i].data,
769                                              userAccountControl,
770                                              samAccountName,
771                                              dnsHostName,
772                                              netbios_name,
773                                              ntds_guid);
774                 if (ret != LDB_SUCCESS) {
775                         talloc_free(tmp_ctx);
776                         return ret;
777                 }
778         }
779         talloc_free(tmp_ctx);
780         return LDB_SUCCESS;
781 }
782
783 static int acl_add(struct ldb_module *module, struct ldb_request *req)
784 {
785         int ret;
786         struct ldb_dn *parent;
787         struct ldb_context *ldb;
788         const struct dsdb_schema *schema;
789         const struct dsdb_class *objectclass;
790         struct ldb_dn *nc_root;
791         struct ldb_control *as_system;
792
793         if (ldb_dn_is_special(req->op.add.message->dn)) {
794                 return ldb_next_request(module, req);
795         }
796
797         as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
798         if (as_system != NULL) {
799                 as_system->critical = 0;
800         }
801
802         if (dsdb_module_am_system(module) || as_system) {
803                 return ldb_next_request(module, req);
804         }
805
806         ldb = ldb_module_get_ctx(module);
807
808         parent = ldb_dn_get_parent(req, req->op.add.message->dn);
809         if (parent == NULL) {
810                 return ldb_oom(ldb);
811         }
812
813         /* Creating an NC. There is probably something we should do here,
814          * but we will establish that later */
815
816         ret = dsdb_find_nc_root(ldb, req, req->op.add.message->dn, &nc_root);
817         if (ret != LDB_SUCCESS) {
818                 return ret;
819         }
820         if (ldb_dn_compare(nc_root, req->op.add.message->dn) == 0) {
821                 talloc_free(nc_root);
822                 return ldb_next_request(module, req);
823         }
824         talloc_free(nc_root);
825
826         schema = dsdb_get_schema(ldb, req);
827         if (!schema) {
828                 return ldb_operr(ldb);
829         }
830
831         objectclass = dsdb_get_structural_oc_from_msg(schema, req->op.add.message);
832         if (!objectclass) {
833                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
834                                        "acl: unable to find or validate structrual objectClass on %s\n",
835                                        ldb_dn_get_linearized(req->op.add.message->dn));
836                 return ldb_module_done(req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
837         }
838
839         ret = dsdb_module_check_access_on_dn(module, req, parent,
840                                              SEC_ADS_CREATE_CHILD,
841                                              &objectclass->schemaIDGUID, req);
842         if (ret != LDB_SUCCESS) {
843                 return ret;
844         }
845         return ldb_next_request(module, req);
846 }
847
848 /* ckecks if modifications are allowed on "Member" attribute */
849 static int acl_check_self_membership(TALLOC_CTX *mem_ctx,
850                                      struct ldb_module *module,
851                                      struct ldb_request *req,
852                                      struct security_descriptor *sd,
853                                      struct dom_sid *sid,
854                                      const struct dsdb_attribute *attr,
855                                      const struct dsdb_class *objectclass)
856 {
857         int ret;
858         unsigned int i;
859         struct ldb_context *ldb = ldb_module_get_ctx(module);
860         struct ldb_dn *user_dn;
861         struct ldb_message_element *member_el;
862         /* if we have wp, we can do whatever we like */
863         if (acl_check_access_on_attribute(module,
864                                           mem_ctx,
865                                           sd,
866                                           sid,
867                                           SEC_ADS_WRITE_PROP,
868                                           attr, objectclass) == LDB_SUCCESS) {
869                 return LDB_SUCCESS;
870         }
871         /* if we are adding/deleting ourselves, check for self membership */
872         ret = dsdb_find_dn_by_sid(ldb, mem_ctx, 
873                                   &acl_user_token(module)->sids[PRIMARY_USER_SID_INDEX], 
874                                   &user_dn);
875         if (ret != LDB_SUCCESS) {
876                 return ret;
877         }
878         member_el = ldb_msg_find_element(req->op.mod.message, "member");
879         if (!member_el) {
880                 return ldb_operr(ldb);
881         }
882         /* user can only remove oneself */
883         if (member_el->num_values == 0) {
884                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
885         }
886         for (i = 0; i < member_el->num_values; i++) {
887                 if (strcasecmp((const char *)member_el->values[i].data,
888                                ldb_dn_get_extended_linearized(mem_ctx, user_dn, 1)) != 0) {
889                         return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
890                 }
891         }
892         ret = acl_check_extended_right(mem_ctx, sd, acl_user_token(module),
893                                        GUID_DRS_SELF_MEMBERSHIP,
894                                        SEC_ADS_SELF_WRITE,
895                                        sid);
896         if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
897                 dsdb_acl_debug(sd, acl_user_token(module),
898                                req->op.mod.message->dn,
899                                true,
900                                10);
901         }
902         return ret;
903 }
904
905 static int acl_check_password_rights(TALLOC_CTX *mem_ctx,
906                                      struct ldb_module *module,
907                                      struct ldb_request *req,
908                                      struct security_descriptor *sd,
909                                      struct dom_sid *sid,
910                                      const struct dsdb_class *objectclass,
911                                      bool userPassword)
912 {
913         int ret = LDB_SUCCESS;
914         unsigned int del_attr_cnt = 0, add_attr_cnt = 0, rep_attr_cnt = 0;
915         struct ldb_message_element *el;
916         struct ldb_message *msg;
917         const char *passwordAttrs[] = { "userPassword", "clearTextPassword",
918                                         "unicodePwd", "dBCSPwd", NULL }, **l;
919         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
920
921         msg = ldb_msg_copy_shallow(tmp_ctx, req->op.mod.message);
922         if (msg == NULL) {
923                 return ldb_module_oom(module);
924         }
925         for (l = passwordAttrs; *l != NULL; l++) {
926                 if ((!userPassword) && (ldb_attr_cmp(*l, "userPassword") == 0)) {
927                         continue;
928                 }
929
930                 while ((el = ldb_msg_find_element(msg, *l)) != NULL) {
931                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE) {
932                                 ++del_attr_cnt;
933                         }
934                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD) {
935                                 ++add_attr_cnt;
936                         }
937                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) {
938                                 ++rep_attr_cnt;
939                         }
940                         ldb_msg_remove_element(msg, el);
941                 }
942         }
943
944         /* single deletes will be handled by the "password_hash" LDB module
945          * later in the stack, so we let it though here */
946         if ((del_attr_cnt > 0) && (add_attr_cnt == 0) && (rep_attr_cnt == 0)) {
947                 talloc_free(tmp_ctx);
948                 return LDB_SUCCESS;
949         }
950
951         if (ldb_request_get_control(req,
952                                     DSDB_CONTROL_PASSWORD_CHANGE_OID) != NULL) {
953                 /* The "DSDB_CONTROL_PASSWORD_CHANGE_OID" control means that we
954                  * have a user password change and not a set as the message
955                  * looks like. In it's value blob it contains the NT and/or LM
956                  * hash of the old password specified by the user.
957                  * This control is used by the SAMR and "kpasswd" password
958                  * change mechanisms. */
959                 ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
960                                                GUID_DRS_USER_CHANGE_PASSWORD,
961                                                SEC_ADS_CONTROL_ACCESS,
962                                                sid);
963         }
964         else if (rep_attr_cnt > 0 || (add_attr_cnt != del_attr_cnt)) {
965                 ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
966                                                GUID_DRS_FORCE_CHANGE_PASSWORD,
967                                                SEC_ADS_CONTROL_ACCESS,
968                                                sid);
969         }
970         else if (add_attr_cnt == 1 && del_attr_cnt == 1) {
971                 ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
972                                                GUID_DRS_USER_CHANGE_PASSWORD,
973                                                SEC_ADS_CONTROL_ACCESS,
974                                                sid);
975                 /* Very strange, but we get constraint violation in this case */
976                 if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
977                         ret = LDB_ERR_CONSTRAINT_VIOLATION;
978                 }
979         }
980         if (ret != LDB_SUCCESS) {
981                 dsdb_acl_debug(sd, acl_user_token(module),
982                                req->op.mod.message->dn,
983                                true,
984                                10);
985         }
986         talloc_free(tmp_ctx);
987         return ret;
988 }
989
990
991 static int acl_modify(struct ldb_module *module, struct ldb_request *req)
992 {
993         int ret;
994         struct ldb_context *ldb = ldb_module_get_ctx(module);
995         const struct dsdb_schema *schema;
996         unsigned int i;
997         const struct dsdb_class *objectclass;
998         uint32_t access_granted;
999         NTSTATUS status;
1000         struct ldb_result *acl_res;
1001         struct security_descriptor *sd;
1002         struct dom_sid *sid = NULL;
1003         struct ldb_control *as_system;
1004         bool userPassword;
1005         TALLOC_CTX *tmp_ctx;
1006         const struct ldb_message *msg = req->op.mod.message;
1007         static const char *acl_attrs[] = {
1008                 "nTSecurityDescriptor",
1009                 "objectClass",
1010                 "objectSid",
1011                 NULL
1012         };
1013
1014         if (ldb_dn_is_special(msg->dn)) {
1015                 return ldb_next_request(module, req);
1016         }
1017
1018         as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1019         if (as_system != NULL) {
1020                 as_system->critical = 0;
1021         }
1022
1023         /* Don't print this debug statement if elements[0].name is going to be NULL */
1024         if (msg->num_elements > 0) {
1025                 DEBUG(10, ("ldb:acl_modify: %s\n", msg->elements[0].name));
1026         }
1027         if (dsdb_module_am_system(module) || as_system) {
1028                 return ldb_next_request(module, req);
1029         }
1030
1031         tmp_ctx = talloc_new(req);
1032         if (tmp_ctx == NULL) {
1033                 return ldb_oom(ldb);
1034         }
1035
1036         ret = dsdb_module_search_dn(module, tmp_ctx, &acl_res, msg->dn,
1037                                     acl_attrs,
1038                                     DSDB_FLAG_NEXT_MODULE |
1039                                     DSDB_FLAG_AS_SYSTEM |
1040                                     DSDB_SEARCH_SHOW_RECYCLED,
1041                                     req);
1042
1043         if (ret != LDB_SUCCESS) {
1044                 goto fail;
1045         }
1046
1047         userPassword = dsdb_user_password_support(module, req, req);
1048
1049         schema = dsdb_get_schema(ldb, tmp_ctx);
1050         if (!schema) {
1051                 talloc_free(tmp_ctx);
1052                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1053                                  "acl_modify: Error obtaining schema.");
1054         }
1055
1056         ret = dsdb_get_sd_from_ldb_message(ldb, tmp_ctx, acl_res->msgs[0], &sd);
1057         if (ret != LDB_SUCCESS) {
1058                 talloc_free(tmp_ctx);
1059                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1060                                  "acl_modify: Error retrieving security descriptor.");
1061         }
1062         /* Theoretically we pass the check if the object has no sd */
1063         if (!sd) {
1064                 goto success;
1065         }
1066
1067         objectclass = dsdb_get_structural_oc_from_msg(schema, acl_res->msgs[0]);
1068         if (!objectclass) {
1069                 talloc_free(tmp_ctx);
1070                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1071                                  "acl_modify: Error retrieving object class for GUID.");
1072         }
1073         sid = samdb_result_dom_sid(req, acl_res->msgs[0], "objectSid");
1074         for (i=0; i < msg->num_elements; i++) {
1075                 const struct ldb_message_element *el = &msg->elements[i];
1076                 const struct dsdb_attribute *attr;
1077
1078                 /*
1079                  * This basic attribute existence check with the right errorcode
1080                  * is needed since this module is the first one which requests
1081                  * schema attribute information.
1082                  * The complete attribute checking is done in the
1083                  * "objectclass_attrs" module behind this one.
1084                  *
1085                  * NOTE: "clearTextPassword" is not defined in the schema.
1086                  */
1087                 attr = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
1088                 if (!attr && ldb_attr_cmp("clearTextPassword", el->name) != 0) {
1089                         ldb_asprintf_errstring(ldb, "acl_modify: attribute '%s' "
1090                                                "on entry '%s' was not found in the schema!",
1091                                                req->op.mod.message->elements[i].name,
1092                                        ldb_dn_get_linearized(req->op.mod.message->dn));
1093                         ret =  LDB_ERR_NO_SUCH_ATTRIBUTE;
1094                         goto fail;
1095                 }
1096
1097                 if (ldb_attr_cmp("nTSecurityDescriptor", el->name) == 0) {
1098                         uint32_t sd_flags = dsdb_request_sd_flags(req, NULL);
1099                         uint32_t access_mask = 0;
1100
1101                         if (sd_flags & (SECINFO_OWNER|SECINFO_GROUP)) {
1102                                 access_mask |= SEC_STD_WRITE_OWNER;
1103                         }
1104                         if (sd_flags & SECINFO_DACL) {
1105                                 access_mask |= SEC_STD_WRITE_DAC;
1106                         }
1107                         if (sd_flags & SECINFO_SACL) {
1108                                 access_mask |= SEC_FLAG_SYSTEM_SECURITY;
1109                         }
1110
1111                         status = sec_access_check_ds(sd, acl_user_token(module),
1112                                              access_mask,
1113                                              &access_granted,
1114                                              NULL,
1115                                              sid);
1116
1117                         if (!NT_STATUS_IS_OK(status)) {
1118                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1119                                                        "Object %s has no write dacl access\n",
1120                                                        ldb_dn_get_linearized(msg->dn));
1121                                 dsdb_acl_debug(sd,
1122                                                acl_user_token(module),
1123                                                msg->dn,
1124                                                true,
1125                                                10);
1126                                 ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1127                                 goto fail;
1128                         }
1129                 } else if (ldb_attr_cmp("member", el->name) == 0) {
1130                         ret = acl_check_self_membership(tmp_ctx,
1131                                                         module,
1132                                                         req,
1133                                                         sd,
1134                                                         sid,
1135                                                         attr,
1136                                                         objectclass);
1137                         if (ret != LDB_SUCCESS) {
1138                                 goto fail;
1139                         }
1140                 } else if (ldb_attr_cmp("dBCSPwd", el->name) == 0) {
1141                         /* this one is not affected by any rights, we should let it through
1142                            so that passwords_hash returns the correct error */
1143                         continue;
1144                 } else if (ldb_attr_cmp("unicodePwd", el->name) == 0 ||
1145                            (userPassword && ldb_attr_cmp("userPassword", el->name) == 0) ||
1146                            ldb_attr_cmp("clearTextPassword", el->name) == 0) {
1147                         ret = acl_check_password_rights(tmp_ctx,
1148                                                         module,
1149                                                         req,
1150                                                         sd,
1151                                                         sid,
1152                                                         objectclass,
1153                                                         userPassword);
1154                         if (ret != LDB_SUCCESS) {
1155                                 goto fail;
1156                         }
1157                 } else if (ldb_attr_cmp("servicePrincipalName", el->name) == 0) {
1158                         ret = acl_check_spn(tmp_ctx,
1159                                             module,
1160                                             req,
1161                                             sd,
1162                                             sid,
1163                                             attr,
1164                                             objectclass);
1165                         if (ret != LDB_SUCCESS) {
1166                                 goto fail;
1167                         }
1168                 } else {
1169                         struct object_tree *root = NULL;
1170                         struct object_tree *new_node = NULL;
1171
1172                         if (!insert_in_object_tree(tmp_ctx,
1173                                                    &objectclass->schemaIDGUID,
1174                                                    SEC_ADS_WRITE_PROP,
1175                                                    &root, &new_node)) {
1176                                 talloc_free(tmp_ctx);
1177                                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1178                                                  "acl_modify: Error adding new node in object tree.");
1179                         }
1180
1181                         if (!insert_in_object_tree(tmp_ctx,
1182                                                    &attr->attributeSecurityGUID, SEC_ADS_WRITE_PROP,
1183                                                    &new_node, &new_node)) {
1184                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1185                                                        "acl_modify: cannot add to object tree securityGUID\n");
1186                                 ret = LDB_ERR_OPERATIONS_ERROR;
1187                                 goto fail;
1188                         }
1189
1190                         if (!insert_in_object_tree(tmp_ctx,
1191                                                    &attr->schemaIDGUID, SEC_ADS_WRITE_PROP, &new_node, &new_node)) {
1192                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1193                                                        "acl_modify: cannot add to object tree attributeGUID\n");
1194                                 ret = LDB_ERR_OPERATIONS_ERROR;
1195                                 goto fail;
1196                         }
1197
1198                         status = sec_access_check_ds(sd, acl_user_token(module),
1199                                                      SEC_ADS_WRITE_PROP,
1200                                                      &access_granted,
1201                                                      root,
1202                                                      sid);
1203                         if (!NT_STATUS_IS_OK(status)) {
1204                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1205                                                        "Object %s has no write property access\n",
1206                                                        ldb_dn_get_linearized(msg->dn));
1207                                 dsdb_acl_debug(sd,
1208                                                acl_user_token(module),
1209                                                msg->dn,
1210                                                true,
1211                                                10);
1212                                 ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1213                                 goto fail;
1214                         }
1215                 }
1216         }
1217
1218 success:
1219         talloc_free(tmp_ctx);
1220         return ldb_next_request(module, req);
1221 fail:
1222         talloc_free(tmp_ctx);
1223         return ret;
1224 }
1225
1226 /* similar to the modify for the time being.
1227  * We need to consider the special delete tree case, though - TODO */
1228 static int acl_delete(struct ldb_module *module, struct ldb_request *req)
1229 {
1230         int ret;
1231         struct ldb_dn *parent;
1232         struct ldb_context *ldb;
1233         struct ldb_dn *nc_root;
1234         struct ldb_control *as_system;
1235
1236         if (ldb_dn_is_special(req->op.del.dn)) {
1237                 return ldb_next_request(module, req);
1238         }
1239
1240         as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1241         if (as_system != NULL) {
1242                 as_system->critical = 0;
1243         }
1244
1245         if (dsdb_module_am_system(module) || as_system) {
1246                 return ldb_next_request(module, req);
1247         }
1248
1249         DEBUG(10, ("ldb:acl_delete: %s\n", ldb_dn_get_linearized(req->op.del.dn)));
1250
1251         ldb = ldb_module_get_ctx(module);
1252
1253         parent = ldb_dn_get_parent(req, req->op.del.dn);
1254         if (parent == NULL) {
1255                 return ldb_oom(ldb);
1256         }
1257
1258         /* Make sure we aren't deleting a NC */
1259
1260         ret = dsdb_find_nc_root(ldb, req, req->op.del.dn, &nc_root);
1261         if (ret != LDB_SUCCESS) {
1262                 return ret;
1263         }
1264         if (ldb_dn_compare(nc_root, req->op.del.dn) == 0) {
1265                 talloc_free(nc_root);
1266                 DEBUG(10,("acl:deleting a NC\n"));
1267                 /* Windows returns "ERR_UNWILLING_TO_PERFORM */
1268                 return ldb_module_done(req, NULL, NULL,
1269                                        LDB_ERR_UNWILLING_TO_PERFORM);
1270         }
1271         talloc_free(nc_root);
1272
1273         if (ldb_request_get_control(req, LDB_CONTROL_TREE_DELETE_OID)) {
1274                 ret = dsdb_module_check_access_on_dn(module, req,
1275                                                      req->op.del.dn,
1276                                                      SEC_ADS_DELETE_TREE, NULL,
1277                                                      req);
1278                 if (ret != LDB_SUCCESS) {
1279                         return ret;
1280                 }
1281
1282                 return ldb_next_request(module, req);
1283         }
1284
1285         /* First check if we have delete object right */
1286         ret = dsdb_module_check_access_on_dn(module, req, req->op.del.dn,
1287                                              SEC_STD_DELETE, NULL, req);
1288         if (ret == LDB_SUCCESS) {
1289                 return ldb_next_request(module, req);
1290         }
1291
1292         /* Nope, we don't have delete object. Lets check if we have delete
1293          * child on the parent */
1294         ret = dsdb_module_check_access_on_dn(module, req, parent,
1295                                              SEC_ADS_DELETE_CHILD, NULL, req);
1296         if (ret != LDB_SUCCESS) {
1297                 return ret;
1298         }
1299
1300         return ldb_next_request(module, req);
1301 }
1302
1303 static int acl_rename(struct ldb_module *module, struct ldb_request *req)
1304 {
1305         int ret;
1306         struct ldb_dn *oldparent;
1307         struct ldb_dn *newparent;
1308         const struct dsdb_schema *schema;
1309         const struct dsdb_class *objectclass;
1310         struct ldb_context *ldb;
1311         struct security_descriptor *sd = NULL;
1312         struct dom_sid *sid = NULL;
1313         struct ldb_result *acl_res;
1314         const struct GUID *guid;
1315         struct ldb_dn *nc_root;
1316         struct object_tree *root = NULL;
1317         struct object_tree *new_node = NULL;
1318         struct ldb_control *as_system;
1319         TALLOC_CTX *tmp_ctx;
1320         NTSTATUS status;
1321         uint32_t access_granted;
1322         const char *rdn_name;
1323         static const char *acl_attrs[] = {
1324                 "nTSecurityDescriptor",
1325                 "objectClass",
1326                 "objectSid",
1327                 NULL
1328         };
1329
1330         if (ldb_dn_is_special(req->op.rename.olddn)) {
1331                 return ldb_next_request(module, req);
1332         }
1333
1334         as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1335         if (as_system != NULL) {
1336                 as_system->critical = 0;
1337         }
1338
1339         DEBUG(10, ("ldb:acl_rename: %s\n", ldb_dn_get_linearized(req->op.rename.olddn)));
1340         if (dsdb_module_am_system(module) || as_system) {
1341                 return ldb_next_request(module, req);
1342         }
1343
1344         ldb = ldb_module_get_ctx(module);
1345
1346         tmp_ctx = talloc_new(req);
1347         if (tmp_ctx == NULL) {
1348                 return ldb_oom(ldb);
1349         }
1350
1351         oldparent = ldb_dn_get_parent(tmp_ctx, req->op.rename.olddn);
1352         if (oldparent == NULL) {
1353                 return ldb_oom(ldb);
1354         }
1355         newparent = ldb_dn_get_parent(tmp_ctx, req->op.rename.newdn);
1356         if (newparent == NULL) {
1357                 return ldb_oom(ldb);
1358         }
1359
1360         /* Make sure we aren't renaming/moving a NC */
1361
1362         ret = dsdb_find_nc_root(ldb, req, req->op.rename.olddn, &nc_root);
1363         if (ret != LDB_SUCCESS) {
1364                 return ret;
1365         }
1366         if (ldb_dn_compare(nc_root, req->op.rename.olddn) == 0) {
1367                 talloc_free(nc_root);
1368                 DEBUG(10,("acl:renaming/moving a NC\n"));
1369                 /* Windows returns "ERR_UNWILLING_TO_PERFORM */
1370                 return ldb_module_done(req, NULL, NULL,
1371                                        LDB_ERR_UNWILLING_TO_PERFORM);
1372         }
1373         talloc_free(nc_root);
1374
1375         /* Look for the parent */
1376
1377         ret = dsdb_module_search_dn(module, tmp_ctx, &acl_res,
1378                                     req->op.rename.olddn, acl_attrs,
1379                                     DSDB_FLAG_NEXT_MODULE |
1380                                     DSDB_FLAG_AS_SYSTEM |
1381                                     DSDB_SEARCH_SHOW_RECYCLED, req);
1382         /* we sould be able to find the parent */
1383         if (ret != LDB_SUCCESS) {
1384                 DEBUG(10,("acl: failed to find object %s\n",
1385                           ldb_dn_get_linearized(req->op.rename.olddn)));
1386                 talloc_free(tmp_ctx);
1387                 return ret;
1388         }
1389
1390         schema = dsdb_get_schema(ldb, acl_res);
1391         if (!schema) {
1392                 talloc_free(tmp_ctx);
1393                 return ldb_operr(ldb);
1394         }
1395
1396         objectclass = dsdb_get_structural_oc_from_msg(schema, acl_res->msgs[0]);
1397         if (!objectclass) {
1398                 talloc_free(tmp_ctx);
1399                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1400                                  "acl_modify: Error retrieving object class for GUID.");
1401         }
1402
1403         if (!insert_in_object_tree(tmp_ctx, &objectclass->schemaIDGUID, SEC_ADS_WRITE_PROP,
1404                                    &root, &new_node)) {
1405                 talloc_free(tmp_ctx);
1406                 return ldb_operr(ldb);
1407         }
1408
1409         guid = attribute_schemaid_guid_by_lDAPDisplayName(schema,
1410                                                           "name");
1411         if (!insert_in_object_tree(tmp_ctx, guid, SEC_ADS_WRITE_PROP,
1412                                    &new_node, &new_node)) {
1413                 talloc_free(tmp_ctx);
1414                 return ldb_operr(ldb);
1415         }
1416
1417         rdn_name = ldb_dn_get_rdn_name(req->op.rename.olddn);
1418         if (rdn_name == NULL) {
1419                 talloc_free(tmp_ctx);
1420                 return ldb_operr(ldb);
1421         }
1422         guid = attribute_schemaid_guid_by_lDAPDisplayName(schema,
1423                                                           rdn_name);
1424         if (!insert_in_object_tree(tmp_ctx, guid, SEC_ADS_WRITE_PROP,
1425                                    &new_node, &new_node)) {
1426                 talloc_free(tmp_ctx);
1427                 return ldb_operr(ldb);
1428         };
1429
1430         ret = dsdb_get_sd_from_ldb_message(ldb, req, acl_res->msgs[0], &sd);
1431
1432         if (ret != LDB_SUCCESS) {
1433                 talloc_free(tmp_ctx);
1434                 return ldb_operr(ldb);
1435         }
1436         /* Theoretically we pass the check if the object has no sd */
1437         if (!sd) {
1438                 talloc_free(tmp_ctx);
1439                 return LDB_SUCCESS;
1440         }
1441         sid = samdb_result_dom_sid(req, acl_res->msgs[0], "objectSid");
1442         status = sec_access_check_ds(sd, acl_user_token(module),
1443                                      SEC_ADS_WRITE_PROP,
1444                                      &access_granted,
1445                                      root,
1446                                      sid);
1447
1448         if (!NT_STATUS_IS_OK(status)) {
1449                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1450                                        "Object %s has no wp on name\n",
1451                                        ldb_dn_get_linearized(req->op.rename.olddn));
1452                 dsdb_acl_debug(sd,
1453                           acl_user_token(module),
1454                           req->op.rename.olddn,
1455                           true,
1456                           10);
1457                 talloc_free(tmp_ctx);
1458                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1459         }
1460
1461         if (ldb_dn_compare(oldparent, newparent) == 0) {
1462                 /* regular rename, not move, nothing more to do */
1463                 talloc_free(tmp_ctx);
1464                 return ldb_next_request(module, req);
1465         }
1466
1467         /* new parent should have create child */
1468         root = NULL;
1469         new_node = NULL;
1470
1471         ret = dsdb_module_check_access_on_dn(module, req, newparent,
1472                                              SEC_ADS_CREATE_CHILD,
1473                                              &objectclass->schemaIDGUID, req);
1474         if (ret != LDB_SUCCESS) {
1475                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1476                                        "acl:access_denied renaming %s",
1477                                        ldb_dn_get_linearized(req->op.rename.olddn));
1478                 talloc_free(tmp_ctx);
1479                 return ret;
1480         }
1481         /* do we have delete object on the object? */
1482
1483         status = sec_access_check_ds(sd, acl_user_token(module),
1484                                      SEC_STD_DELETE,
1485                                      &access_granted,
1486                                      NULL,
1487                                      sid);
1488
1489         if (NT_STATUS_IS_OK(status)) {
1490                 talloc_free(tmp_ctx);
1491                 return ldb_next_request(module, req);
1492         }
1493         /* what about delete child on the current parent */
1494         ret = dsdb_module_check_access_on_dn(module, req, oldparent, SEC_ADS_DELETE_CHILD, NULL, req);
1495         if (ret != LDB_SUCCESS) {
1496                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1497                                        "acl:access_denied renaming %s", ldb_dn_get_linearized(req->op.rename.olddn));
1498                 talloc_free(tmp_ctx);
1499                 return ldb_module_done(req, NULL, NULL, ret);
1500         }
1501
1502         talloc_free(tmp_ctx);
1503
1504         return ldb_next_request(module, req);
1505 }
1506
1507 static int acl_search_update_confidential_attrs(struct acl_context *ac,
1508                                                 struct acl_private *data)
1509 {
1510         struct dsdb_attribute *a;
1511         uint32_t n = 0;
1512
1513         if (data->acl_search) {
1514                 /*
1515                  * If acl:search is activated, the acl_read module
1516                  * protects confidential attributes.
1517                  */
1518                 return LDB_SUCCESS;
1519         }
1520
1521         if ((ac->schema == data->cached_schema_ptr) &&
1522             (ac->schema->loaded_usn == data->cached_schema_loaded_usn) &&
1523             (ac->schema->metadata_usn == data->cached_schema_metadata_usn))
1524         {
1525                 return LDB_SUCCESS;
1526         }
1527
1528         data->cached_schema_ptr = NULL;
1529         data->cached_schema_loaded_usn = 0;
1530         data->cached_schema_metadata_usn = 0;
1531         TALLOC_FREE(data->confidential_attrs);
1532
1533         if (ac->schema == NULL) {
1534                 return LDB_SUCCESS;
1535         }
1536
1537         for (a = ac->schema->attributes; a; a = a->next) {
1538                 const char **attrs = data->confidential_attrs;
1539
1540                 if (!(a->searchFlags & SEARCH_FLAG_CONFIDENTIAL)) {
1541                         continue;
1542                 }
1543
1544                 attrs = talloc_realloc(data, attrs, const char *, n + 2);
1545                 if (attrs == NULL) {
1546                         TALLOC_FREE(data->confidential_attrs);
1547                         return ldb_module_oom(ac->module);
1548                 }
1549
1550                 attrs[n] = a->lDAPDisplayName;
1551                 attrs[n+1] = NULL;
1552                 n++;
1553
1554                 data->confidential_attrs = attrs;
1555         }
1556
1557         data->cached_schema_ptr = ac->schema;
1558         data->cached_schema_loaded_usn = ac->schema->loaded_usn;
1559         data->cached_schema_metadata_usn = ac->schema->metadata_usn;
1560
1561         return LDB_SUCCESS;
1562 }
1563
1564 static int acl_search_callback(struct ldb_request *req, struct ldb_reply *ares)
1565 {
1566         struct acl_context *ac;
1567         struct acl_private *data;
1568         struct ldb_result *acl_res;
1569         static const char *acl_attrs[] = {
1570                 "objectClass",
1571                 "nTSecurityDescriptor",
1572                 "objectSid",
1573                 NULL
1574         };
1575         int ret;
1576         unsigned int i;
1577
1578         ac = talloc_get_type(req->context, struct acl_context);
1579         data = talloc_get_type(ldb_module_get_private(ac->module), struct acl_private);
1580         if (!ares) {
1581                 return ldb_module_done(ac->req, NULL, NULL,
1582                                        LDB_ERR_OPERATIONS_ERROR);
1583         }
1584         if (ares->error != LDB_SUCCESS) {
1585                 return ldb_module_done(ac->req, ares->controls,
1586                                        ares->response, ares->error);
1587         }
1588
1589         switch (ares->type) {
1590         case LDB_REPLY_ENTRY:
1591                 if (ac->constructed_attrs) {
1592                         ret = dsdb_module_search_dn(ac->module, ac, &acl_res, ares->message->dn, 
1593                                                     acl_attrs,
1594                                                     DSDB_FLAG_NEXT_MODULE |
1595                                                     DSDB_FLAG_AS_SYSTEM |
1596                                                     DSDB_SEARCH_SHOW_RECYCLED,
1597                                                     req);
1598                         if (ret != LDB_SUCCESS) {
1599                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1600                         }
1601                 }
1602
1603                 if (ac->allowedAttributes || ac->allowedAttributesEffective) {
1604                         ret = acl_allowedAttributes(ac->module, ac->schema,
1605                                                     acl_res->msgs[0],
1606                                                     ares->message, ac);
1607                         if (ret != LDB_SUCCESS) {
1608                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1609                         }
1610                 }
1611
1612                 if (ac->allowedChildClasses) {
1613                         ret = acl_childClasses(ac->module, ac->schema,
1614                                                acl_res->msgs[0],
1615                                                ares->message,
1616                                                "allowedChildClasses");
1617                         if (ret != LDB_SUCCESS) {
1618                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1619                         }
1620                 }
1621
1622                 if (ac->allowedChildClassesEffective) {
1623                         ret = acl_childClassesEffective(ac->module, ac->schema,
1624                                                         acl_res->msgs[0],
1625                                                         ares->message, ac);
1626                         if (ret != LDB_SUCCESS) {
1627                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1628                         }
1629                 }
1630
1631                 if (ac->sDRightsEffective) {
1632                         ret = acl_sDRightsEffective(ac->module,
1633                                                     acl_res->msgs[0],
1634                                                     ares->message, ac);
1635                         if (ret != LDB_SUCCESS) {
1636                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1637                         }
1638                 }
1639
1640                 if (data == NULL) {
1641                         return ldb_module_send_entry(ac->req, ares->message,
1642                                                      ares->controls);
1643                 }
1644
1645                 if (ac->am_system) {
1646                         return ldb_module_send_entry(ac->req, ares->message,
1647                                                      ares->controls);
1648                 }
1649
1650                 if (data->password_attrs != NULL) {
1651                         for (i = 0; data->password_attrs[i]; i++) {
1652                                 if ((!ac->userPassword) &&
1653                                     (ldb_attr_cmp(data->password_attrs[i],
1654                                                   "userPassword") == 0))
1655                                 {
1656                                                 continue;
1657                                 }
1658
1659                                 ldb_msg_remove_attr(ares->message, data->password_attrs[i]);
1660                         }
1661                 }
1662
1663                 if (ac->am_administrator) {
1664                         return ldb_module_send_entry(ac->req, ares->message,
1665                                                      ares->controls);
1666                 }
1667
1668                 ret = acl_search_update_confidential_attrs(ac, data);
1669                 if (ret != LDB_SUCCESS) {
1670                         return ret;
1671                 }
1672
1673                 if (data->confidential_attrs != NULL) {
1674                         for (i = 0; data->confidential_attrs[i]; i++) {
1675                                 ldb_msg_remove_attr(ares->message,
1676                                                     data->confidential_attrs[i]);
1677                         }
1678                 }
1679
1680                 return ldb_module_send_entry(ac->req, ares->message, ares->controls);
1681
1682         case LDB_REPLY_REFERRAL:
1683                 return ldb_module_send_referral(ac->req, ares->referral);
1684
1685         case LDB_REPLY_DONE:
1686                 return ldb_module_done(ac->req, ares->controls,
1687                                        ares->response, LDB_SUCCESS);
1688
1689         }
1690         return LDB_SUCCESS;
1691 }
1692
1693 static int acl_search(struct ldb_module *module, struct ldb_request *req)
1694 {
1695         struct ldb_context *ldb;
1696         struct acl_context *ac;
1697         struct ldb_parse_tree *down_tree;
1698         struct ldb_request *down_req;
1699         struct acl_private *data;
1700         int ret;
1701         unsigned int i;
1702
1703         if (ldb_dn_is_special(req->op.search.base)) {
1704                 return ldb_next_request(module, req);
1705         }
1706
1707         ldb = ldb_module_get_ctx(module);
1708
1709         ac = talloc_zero(req, struct acl_context);
1710         if (ac == NULL) {
1711                 return ldb_oom(ldb);
1712         }
1713         data = talloc_get_type(ldb_module_get_private(module), struct acl_private);
1714
1715         ac->module = module;
1716         ac->req = req;
1717         ac->am_system = dsdb_module_am_system(module);
1718         ac->am_administrator = dsdb_module_am_administrator(module);
1719         ac->constructed_attrs = false;
1720         ac->modify_search = true;
1721         ac->allowedAttributes = ldb_attr_in_list(req->op.search.attrs, "allowedAttributes");
1722         ac->allowedAttributesEffective = ldb_attr_in_list(req->op.search.attrs, "allowedAttributesEffective");
1723         ac->allowedChildClasses = ldb_attr_in_list(req->op.search.attrs, "allowedChildClasses");
1724         ac->allowedChildClassesEffective = ldb_attr_in_list(req->op.search.attrs, "allowedChildClassesEffective");
1725         ac->sDRightsEffective = ldb_attr_in_list(req->op.search.attrs, "sDRightsEffective");
1726         ac->userPassword = true;
1727         ac->schema = dsdb_get_schema(ldb, ac);
1728
1729         ac->constructed_attrs |= ac->allowedAttributes;
1730         ac->constructed_attrs |= ac->allowedChildClasses;
1731         ac->constructed_attrs |= ac->allowedChildClassesEffective;
1732         ac->constructed_attrs |= ac->allowedAttributesEffective;
1733         ac->constructed_attrs |= ac->sDRightsEffective;
1734
1735         if (data == NULL) {
1736                 ac->modify_search = false;
1737         }
1738         if (ac->am_system) {
1739                 ac->modify_search = false;
1740         }
1741
1742         if (!ac->constructed_attrs && !ac->modify_search) {
1743                 talloc_free(ac);
1744                 return ldb_next_request(module, req);
1745         }
1746
1747         if (!ac->am_system) {
1748                 ac->userPassword = dsdb_user_password_support(module, ac, req);
1749         }
1750
1751         ret = acl_search_update_confidential_attrs(ac, data);
1752         if (ret != LDB_SUCCESS) {
1753                 return ret;
1754         }
1755
1756         down_tree = ldb_parse_tree_copy_shallow(ac, req->op.search.tree);
1757         if (down_tree == NULL) {
1758                 return ldb_oom(ldb);
1759         }
1760
1761         if (!ac->am_system && data->password_attrs) {
1762                 for (i = 0; data->password_attrs[i]; i++) {
1763                         if ((!ac->userPassword) &&
1764                             (ldb_attr_cmp(data->password_attrs[i],
1765                                           "userPassword") == 0))
1766                         {
1767                                 continue;
1768                         }
1769
1770                         ldb_parse_tree_attr_replace(down_tree,
1771                                                     data->password_attrs[i],
1772                                                     "kludgeACLredactedattribute");
1773                 }
1774         }
1775
1776         if (!ac->am_system && !ac->am_administrator && data->confidential_attrs) {
1777                 for (i = 0; data->confidential_attrs[i]; i++) {
1778                         ldb_parse_tree_attr_replace(down_tree,
1779                                                     data->confidential_attrs[i],
1780                                                     "kludgeACLredactedattribute");
1781                 }
1782         }
1783
1784         ret = ldb_build_search_req_ex(&down_req,
1785                                       ldb, ac,
1786                                       req->op.search.base,
1787                                       req->op.search.scope,
1788                                       down_tree,
1789                                       req->op.search.attrs,
1790                                       req->controls,
1791                                       ac, acl_search_callback,
1792                                       req);
1793         LDB_REQ_SET_LOCATION(down_req);
1794         if (ret != LDB_SUCCESS) {
1795                 return ret;
1796         }
1797         /* perform the search */
1798         return ldb_next_request(module, down_req);
1799 }
1800
1801 static int acl_extended(struct ldb_module *module, struct ldb_request *req)
1802 {
1803         struct ldb_context *ldb = ldb_module_get_ctx(module);
1804         struct ldb_control *as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1805
1806         /* allow everybody to read the sequence number */
1807         if (strcmp(req->op.extended.oid,
1808                    LDB_EXTENDED_SEQUENCE_NUMBER) == 0) {
1809                 return ldb_next_request(module, req);
1810         }
1811
1812         if (dsdb_module_am_system(module) ||
1813             dsdb_module_am_administrator(module) || as_system) {
1814                 return ldb_next_request(module, req);
1815         } else {
1816                 ldb_asprintf_errstring(ldb,
1817                                        "acl_extended: "
1818                                        "attempted database modify not permitted. "
1819                                        "User %s is not SYSTEM or an administrator",
1820                                        acl_user_name(req, module));
1821                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1822         }
1823 }
1824
1825 static const struct ldb_module_ops ldb_acl_module_ops = {
1826         .name              = "acl",
1827         .search            = acl_search,
1828         .add               = acl_add,
1829         .modify            = acl_modify,
1830         .del               = acl_delete,
1831         .rename            = acl_rename,
1832         .extended          = acl_extended,
1833         .init_context      = acl_module_init
1834 };
1835
1836 int ldb_acl_module_init(const char *version)
1837 {
1838         LDB_MODULE_CHECK_VERSION(version);
1839         return ldb_register_module(&ldb_acl_module_ops);
1840 }