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