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