TODO pass DSDB_FLAG_AS_SYSTEM...
[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_perform;
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_perform = lpcfg_parm_bool(ldb_get_opaque(ldb, "loadparm"),
104                                          NULL, "acl", "perform", 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_DELETED, req);
659         if (ret != LDB_SUCCESS) {
660                 talloc_free(tmp_ctx);
661                 return ret;
662         }
663
664         userAccountControl = ldb_msg_find_attr_as_uint(acl_res->msgs[0], "userAccountControl", 0);
665         dnsHostName = ldb_msg_find_attr_as_string(acl_res->msgs[0], "dnsHostName", NULL);
666         samAccountName = ldb_msg_find_attr_as_string(acl_res->msgs[0], "samAccountName", NULL);
667
668         ret = dsdb_module_search(module, tmp_ctx,
669                                  &netbios_res, partitions_dn,
670                                  LDB_SCOPE_ONELEVEL,
671                                  netbios_attrs,
672                                  DSDB_FLAG_NEXT_MODULE |
673                                  DSDB_FLAG_AS_SYSTEM,
674                                  req,
675                                  "(ncName=%s)",
676                                  ldb_dn_get_linearized(ldb_get_default_basedn(ldb)));
677
678         netbios_name = ldb_msg_find_attr_as_string(netbios_res->msgs[0], "nETBIOSName", NULL);
679
680         el = ldb_msg_find_element(req->op.mod.message, "servicePrincipalName");
681         if (!el) {
682                 talloc_free(tmp_ctx);
683                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
684                                          "Error finding element for servicePrincipalName.");
685         }
686
687         /* NTDSDSA objectGuid of object we are checking SPN for */
688         if (userAccountControl & (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT)) {
689                 ret = dsdb_module_find_ntdsguid_for_computer(module, tmp_ctx,
690                                                              req->op.mod.message->dn, &ntds, req);
691                 if (ret != LDB_SUCCESS) {
692                         ldb_asprintf_errstring(ldb, "Failed to find NTDSDSA objectGuid for %s: %s",
693                                                ldb_dn_get_linearized(req->op.mod.message->dn),
694                                                ldb_strerror(ret));
695                         talloc_free(tmp_ctx);
696                         return LDB_ERR_OPERATIONS_ERROR;
697                 }
698                 ntds_guid = GUID_string(tmp_ctx, &ntds);
699         }
700
701         for (i=0; i < el->num_values; i++) {
702                 ret = acl_validate_spn_value(tmp_ctx,
703                                              ldb,
704                                              (char *)el->values[i].data,
705                                              userAccountControl,
706                                              samAccountName,
707                                              dnsHostName,
708                                              netbios_name,
709                                              ntds_guid);
710                 if (ret != LDB_SUCCESS) {
711                         talloc_free(tmp_ctx);
712                         return ret;
713                 }
714         }
715         talloc_free(tmp_ctx);
716         return LDB_SUCCESS;
717 }
718
719 static int acl_add(struct ldb_module *module, struct ldb_request *req)
720 {
721         int ret;
722         struct ldb_dn *parent = ldb_dn_get_parent(req, req->op.add.message->dn);
723         struct ldb_context *ldb;
724         const struct dsdb_schema *schema;
725         struct ldb_message_element *oc_el;
726         const struct GUID *guid;
727         struct ldb_dn *nc_root;
728         struct ldb_control *as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
729
730         if (as_system != NULL) {
731                 as_system->critical = 0;
732         }
733
734         if (dsdb_module_am_system(module) || as_system) {
735                 return ldb_next_request(module, req);
736         }
737         if (ldb_dn_is_special(req->op.add.message->dn)) {
738                 return ldb_next_request(module, req);
739         }
740
741         ldb = ldb_module_get_ctx(module);
742
743         /* Creating an NC. There is probably something we should do here,
744          * but we will establish that later */
745
746         ret = dsdb_find_nc_root(ldb, req, req->op.add.message->dn, &nc_root);
747         if (ret != LDB_SUCCESS) {
748                 return ret;
749         }
750         if (ldb_dn_compare(nc_root, req->op.add.message->dn) == 0) {
751                 talloc_free(nc_root);
752                 return ldb_next_request(module, req);
753         }
754         talloc_free(nc_root);
755
756         schema = dsdb_get_schema(ldb, req);
757         if (!schema) {
758                 return ldb_operr(ldb);
759         }
760
761         oc_el = ldb_msg_find_element(req->op.add.message, "objectClass");
762         if (!oc_el || oc_el->num_values == 0) {
763                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
764                                        "acl: unable to find objectClass on %s\n",
765                                        ldb_dn_get_linearized(req->op.add.message->dn));
766                 return ldb_module_done(req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
767         }
768
769         guid = class_schemaid_guid_by_lDAPDisplayName(schema,
770                                                       (char *)oc_el->values[oc_el->num_values-1].data);
771         ret = dsdb_module_check_access_on_dn(module, req, parent, SEC_ADS_CREATE_CHILD, guid, req);
772         if (ret != LDB_SUCCESS) {
773                 return ret;
774         }
775         return ldb_next_request(module, req);
776 }
777
778 /* ckecks if modifications are allowed on "Member" attribute */
779 static int acl_check_self_membership(TALLOC_CTX *mem_ctx,
780                                      struct ldb_module *module,
781                                      struct ldb_request *req,
782                                      struct security_descriptor *sd,
783                                      struct dom_sid *sid,
784                                      const struct GUID *oc_guid,
785                                      const struct dsdb_attribute *attr)
786 {
787         int ret;
788         unsigned int i;
789         struct ldb_context *ldb = ldb_module_get_ctx(module);
790         struct ldb_dn *user_dn;
791         struct ldb_message_element *member_el;
792         /* if we have wp, we can do whatever we like */
793         if (acl_check_access_on_attribute(module,
794                                           mem_ctx,
795                                           sd,
796                                           sid,
797                                           SEC_ADS_WRITE_PROP,
798                                           attr) == LDB_SUCCESS) {
799                 return LDB_SUCCESS;
800         }
801         /* if we are adding/deleting ourselves, check for self membership */
802         ret = dsdb_find_dn_by_sid(ldb, mem_ctx, 
803                                   &acl_user_token(module)->sids[PRIMARY_USER_SID_INDEX], 
804                                   &user_dn);
805         if (ret != LDB_SUCCESS) {
806                 return ret;
807         }
808         member_el = ldb_msg_find_element(req->op.mod.message, "member");
809         if (!member_el) {
810                 return ldb_operr(ldb);
811         }
812         /* user can only remove oneself */
813         if (member_el->num_values == 0) {
814                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
815         }
816         for (i = 0; i < member_el->num_values; i++) {
817                 if (strcasecmp((const char *)member_el->values[i].data,
818                                ldb_dn_get_extended_linearized(mem_ctx, user_dn, 1)) != 0) {
819                         return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
820                 }
821         }
822         ret = acl_check_extended_right(mem_ctx, sd, acl_user_token(module),
823                                        GUID_DRS_SELF_MEMBERSHIP,
824                                        SEC_ADS_SELF_WRITE,
825                                        sid);
826         if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
827                 dsdb_acl_debug(sd, acl_user_token(module),
828                                req->op.mod.message->dn,
829                                true,
830                                10);
831         }
832         return ret;
833 }
834
835 static int acl_check_password_rights(TALLOC_CTX *mem_ctx,
836                                      struct ldb_module *module,
837                                      struct ldb_request *req,
838                                      struct security_descriptor *sd,
839                                      struct dom_sid *sid,
840                                      const struct GUID *oc_guid,
841                                      bool userPassword)
842 {
843         int ret = LDB_SUCCESS;
844         unsigned int del_attr_cnt = 0, add_attr_cnt = 0, rep_attr_cnt = 0;
845         struct ldb_message_element *el;
846         struct ldb_message *msg;
847         const char *passwordAttrs[] = { "userPassword", "clearTextPassword",
848                                         "unicodePwd", "dBCSPwd", NULL }, **l;
849         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
850
851         msg = ldb_msg_copy_shallow(tmp_ctx, req->op.mod.message);
852         if (msg == NULL) {
853                 return ldb_module_oom(module);
854         }
855         for (l = passwordAttrs; *l != NULL; l++) {
856                 if ((!userPassword) && (ldb_attr_cmp(*l, "userPassword") == 0)) {
857                         continue;
858                 }
859
860                 while ((el = ldb_msg_find_element(msg, *l)) != NULL) {
861                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE) {
862                                 ++del_attr_cnt;
863                         }
864                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD) {
865                                 ++add_attr_cnt;
866                         }
867                         if (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_REPLACE) {
868                                 ++rep_attr_cnt;
869                         }
870                         ldb_msg_remove_element(msg, el);
871                 }
872         }
873
874         /* single deletes will be handled by the "password_hash" LDB module
875          * later in the stack, so we let it though here */
876         if ((del_attr_cnt > 0) && (add_attr_cnt == 0) && (rep_attr_cnt == 0)) {
877                 talloc_free(tmp_ctx);
878                 return LDB_SUCCESS;
879         }
880
881         if (ldb_request_get_control(req,
882                                     DSDB_CONTROL_PASSWORD_CHANGE_OID) != NULL) {
883                 /* The "DSDB_CONTROL_PASSWORD_CHANGE_OID" control means that we
884                  * have a user password change and not a set as the message
885                  * looks like. In it's value blob it contains the NT and/or LM
886                  * hash of the old password specified by the user.
887                  * This control is used by the SAMR and "kpasswd" password
888                  * change mechanisms. */
889                 ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
890                                                GUID_DRS_USER_CHANGE_PASSWORD,
891                                                SEC_ADS_CONTROL_ACCESS,
892                                                sid);
893         }
894         else if (rep_attr_cnt > 0 || (add_attr_cnt != del_attr_cnt)) {
895                 ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
896                                                GUID_DRS_FORCE_CHANGE_PASSWORD,
897                                                SEC_ADS_CONTROL_ACCESS,
898                                                sid);
899         }
900         else if (add_attr_cnt == 1 && del_attr_cnt == 1) {
901                 ret = acl_check_extended_right(tmp_ctx, sd, acl_user_token(module),
902                                                GUID_DRS_USER_CHANGE_PASSWORD,
903                                                SEC_ADS_CONTROL_ACCESS,
904                                                sid);
905                 /* Very strange, but we get constraint violation in this case */
906                 if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) {
907                         ret = LDB_ERR_CONSTRAINT_VIOLATION;
908                 }
909         }
910         if (ret != LDB_SUCCESS) {
911                 dsdb_acl_debug(sd, acl_user_token(module),
912                                req->op.mod.message->dn,
913                                true,
914                                10);
915         }
916         talloc_free(tmp_ctx);
917         return ret;
918 }
919
920 static const struct GUID *get_oc_guid_from_message(const struct dsdb_schema *schema,
921                                                    struct ldb_message *msg)
922 {
923         struct ldb_message_element *oc_el;
924         const struct dsdb_class *object_class;
925
926         oc_el = ldb_msg_find_element(msg, "objectClass");
927         if (!oc_el) {
928                 return NULL;
929         }
930
931         object_class = dsdb_get_last_structural_class(schema, oc_el);
932         if (object_class == NULL) {
933                 return NULL;
934         }
935
936         return &object_class->schemaIDGUID;
937 }
938
939
940 static int acl_modify(struct ldb_module *module, struct ldb_request *req)
941 {
942         int ret;
943         struct ldb_context *ldb = ldb_module_get_ctx(module);
944         const struct dsdb_schema *schema;
945         unsigned int i;
946         const struct GUID *guid;
947         uint32_t access_granted;
948         struct object_tree *root = NULL;
949         struct object_tree *new_node = NULL;
950         NTSTATUS status;
951         struct ldb_result *acl_res;
952         struct security_descriptor *sd;
953         struct dom_sid *sid = NULL;
954         struct ldb_control *as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
955         bool userPassword = dsdb_user_password_support(module, req, req);
956         TALLOC_CTX *tmp_ctx = talloc_new(req);
957         static const char *acl_attrs[] = {
958                 "nTSecurityDescriptor",
959                 "objectClass",
960                 "objectSid",
961                 NULL
962         };
963
964         if (as_system != NULL) {
965                 as_system->critical = 0;
966         }
967
968         /* Don't print this debug statement if elements[0].name is going to be NULL */
969         if(req->op.mod.message->num_elements > 0)
970         {
971                 DEBUG(10, ("ldb:acl_modify: %s\n", req->op.mod.message->elements[0].name));
972         }
973         if (dsdb_module_am_system(module) || as_system) {
974                 return ldb_next_request(module, req);
975         }
976         if (ldb_dn_is_special(req->op.mod.message->dn)) {
977                 return ldb_next_request(module, req);
978         }
979         ret = dsdb_module_search_dn(module, tmp_ctx, &acl_res, req->op.mod.message->dn,
980                                     acl_attrs,
981                                     DSDB_FLAG_NEXT_MODULE |
982                                     DSDB_FLAG_AS_SYSTEM |
983                                     DSDB_SEARCH_SHOW_DELETED,
984                                     req);
985
986         if (ret != LDB_SUCCESS) {
987                 goto fail;
988         }
989
990         schema = dsdb_get_schema(ldb, tmp_ctx);
991         if (!schema) {
992                 ret = LDB_ERR_OPERATIONS_ERROR;
993                 goto fail;
994         }
995
996         ret = dsdb_get_sd_from_ldb_message(ldb, tmp_ctx, acl_res->msgs[0], &sd);
997         if (ret != LDB_SUCCESS) {
998                 talloc_free(tmp_ctx);
999                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1000                                  "acl_modify: Error retrieving security descriptor.");
1001         }
1002         /* Theoretically we pass the check if the object has no sd */
1003         if (!sd) {
1004                 goto success;
1005         }
1006
1007         guid = get_oc_guid_from_message(schema, acl_res->msgs[0]);
1008         if (!guid) {
1009                 talloc_free(tmp_ctx);
1010                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1011                                  "acl_modify: Error retrieving object class GUID.");
1012         }
1013         sid = samdb_result_dom_sid(req, acl_res->msgs[0], "objectSid");
1014         if (!insert_in_object_tree(tmp_ctx, guid, SEC_ADS_WRITE_PROP,
1015                                    &root, &new_node)) {
1016                 talloc_free(tmp_ctx);
1017                 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1018                                  "acl_modify: Error adding new node in object tree.");
1019         }
1020         for (i=0; i < req->op.mod.message->num_elements; i++){
1021                 const struct dsdb_attribute *attr;
1022                 attr = dsdb_attribute_by_lDAPDisplayName(schema,
1023                                                          req->op.mod.message->elements[i].name);
1024
1025                 if (ldb_attr_cmp("nTSecurityDescriptor", req->op.mod.message->elements[i].name) == 0) {
1026                         status = sec_access_check_ds(sd, acl_user_token(module),
1027                                              SEC_STD_WRITE_DAC,
1028                                              &access_granted,
1029                                              NULL,
1030                                              sid);
1031
1032                         if (!NT_STATUS_IS_OK(status)) {
1033                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1034                                                        "Object %s has no write dacl access\n",
1035                                                        ldb_dn_get_linearized(req->op.mod.message->dn));
1036                                 dsdb_acl_debug(sd,
1037                                                acl_user_token(module),
1038                                                req->op.mod.message->dn,
1039                                                true,
1040                                                10);
1041                                 ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1042                                 goto fail;
1043                         }
1044                 }
1045                 else if (ldb_attr_cmp("member", req->op.mod.message->elements[i].name) == 0) {
1046                         ret = acl_check_self_membership(tmp_ctx,
1047                                                         module,
1048                                                         req,
1049                                                         sd,
1050                                                         sid,
1051                                                         guid,
1052                                                         attr);
1053                         if (ret != LDB_SUCCESS) {
1054                                 goto fail;
1055                         }
1056                 }
1057                 else if (ldb_attr_cmp("dBCSPwd", req->op.mod.message->elements[i].name) == 0) {
1058                         /* this one is not affected by any rights, we should let it through
1059                            so that passwords_hash returns the correct error */
1060                         continue;
1061                 }
1062                 else if (ldb_attr_cmp("unicodePwd", req->op.mod.message->elements[i].name) == 0 ||
1063                          (userPassword && ldb_attr_cmp("userPassword", req->op.mod.message->elements[i].name) == 0) ||
1064                          ldb_attr_cmp("clearTextPassword", req->op.mod.message->elements[i].name) == 0) {
1065                         ret = acl_check_password_rights(tmp_ctx,
1066                                                         module,
1067                                                         req,
1068                                                         sd,
1069                                                         sid,
1070                                                         guid,
1071                                                         userPassword);
1072                         if (ret != LDB_SUCCESS) {
1073                                 goto fail;
1074                         }
1075                 } else if (ldb_attr_cmp("servicePrincipalName", req->op.mod.message->elements[i].name) == 0) {
1076                         ret = acl_check_spn(tmp_ctx,
1077                                             module,
1078                                             req,
1079                                             sd,
1080                                             sid,
1081                                             guid,
1082                                             attr);
1083                         if (ret != LDB_SUCCESS) {
1084                                 goto fail;
1085                         }
1086                 } else {
1087
1088                 /* This basic attribute existence check with the right errorcode
1089                  * is needed since this module is the first one which requests
1090                  * schema attribute information.
1091                  * The complete attribute checking is done in the
1092                  * "objectclass_attrs" module behind this one.
1093                  */
1094                         if (!attr) {
1095                                 ldb_asprintf_errstring(ldb, "acl_modify: attribute '%s' on entry '%s' was not found in the schema!",
1096                                                        req->op.mod.message->elements[i].name,
1097                                                ldb_dn_get_linearized(req->op.mod.message->dn));
1098                                 ret =  LDB_ERR_NO_SUCH_ATTRIBUTE;
1099                                 goto fail;
1100                         }
1101                         if (!insert_in_object_tree(tmp_ctx,
1102                                                    &attr->attributeSecurityGUID, SEC_ADS_WRITE_PROP,
1103                                                    &new_node, &new_node)) {
1104                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1105                                                        "acl_modify: cannot add to object tree securityGUID\n");
1106                                 ret = LDB_ERR_OPERATIONS_ERROR;
1107                                 goto fail;
1108                         }
1109
1110                         if (!insert_in_object_tree(tmp_ctx,
1111                                                    &attr->schemaIDGUID, SEC_ADS_WRITE_PROP, &new_node, &new_node)) {
1112                                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1113                                                        "acl_modify: cannot add to object tree attributeGUID\n");
1114                                 ret = LDB_ERR_OPERATIONS_ERROR;
1115                                 goto fail;
1116                         }
1117                 }
1118         }
1119
1120         if (root->num_of_children > 0) {
1121                 status = sec_access_check_ds(sd, acl_user_token(module),
1122                                              SEC_ADS_WRITE_PROP,
1123                                              &access_granted,
1124                                              root,
1125                                              sid);
1126
1127                 if (!NT_STATUS_IS_OK(status)) {
1128                         ldb_asprintf_errstring(ldb_module_get_ctx(module),
1129                                                "Object %s has no write property access\n",
1130                                                ldb_dn_get_linearized(req->op.mod.message->dn));
1131                         dsdb_acl_debug(sd,
1132                                        acl_user_token(module),
1133                                        req->op.mod.message->dn,
1134                                        true,
1135                                        10);
1136                         ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1137                         goto fail;
1138                 }
1139         }
1140
1141 success:
1142         talloc_free(tmp_ctx);
1143         return ldb_next_request(module, req);
1144 fail:
1145         talloc_free(tmp_ctx);
1146         return ret;
1147 }
1148
1149 /* similar to the modify for the time being.
1150  * We need to consider the special delete tree case, though - TODO */
1151 static int acl_delete(struct ldb_module *module, struct ldb_request *req)
1152 {
1153         int ret;
1154         struct ldb_dn *parent = ldb_dn_get_parent(req, req->op.del.dn);
1155         struct ldb_context *ldb;
1156         struct ldb_dn *nc_root;
1157         struct ldb_control *as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1158
1159         if (as_system != NULL) {
1160                 as_system->critical = 0;
1161         }
1162
1163         DEBUG(10, ("ldb:acl_delete: %s\n", ldb_dn_get_linearized(req->op.del.dn)));
1164         if (dsdb_module_am_system(module) || as_system) {
1165                 return ldb_next_request(module, req);
1166         }
1167         if (ldb_dn_is_special(req->op.del.dn)) {
1168                 return ldb_next_request(module, req);
1169         }
1170
1171         ldb = ldb_module_get_ctx(module);
1172
1173         /* Make sure we aren't deleting a NC */
1174
1175         ret = dsdb_find_nc_root(ldb, req, req->op.del.dn, &nc_root);
1176         if (ret != LDB_SUCCESS) {
1177                 return ret;
1178         }
1179         if (ldb_dn_compare(nc_root, req->op.del.dn) == 0) {
1180                 talloc_free(nc_root);
1181                 DEBUG(10,("acl:deleting a NC\n"));
1182                 /* Windows returns "ERR_UNWILLING_TO_PERFORM */
1183                 return ldb_module_done(req, NULL, NULL,
1184                                        LDB_ERR_UNWILLING_TO_PERFORM);
1185         }
1186         talloc_free(nc_root);
1187
1188         /* First check if we have delete object right */
1189         ret = dsdb_module_check_access_on_dn(module, req, req->op.del.dn,
1190                                              SEC_STD_DELETE, NULL, req);
1191         if (ret == LDB_SUCCESS) {
1192                 return ldb_next_request(module, req);
1193         }
1194
1195         /* Nope, we don't have delete object. Lets check if we have delete
1196          * child on the parent */
1197         ret = dsdb_module_check_access_on_dn(module, req, parent,
1198                                              SEC_ADS_DELETE_CHILD, NULL, req);
1199         if (ret != LDB_SUCCESS) {
1200                 return ret;
1201         }
1202
1203         return ldb_next_request(module, req);
1204 }
1205
1206 static int acl_rename(struct ldb_module *module, struct ldb_request *req)
1207 {
1208         int ret;
1209         struct ldb_dn *oldparent = ldb_dn_get_parent(req, req->op.rename.olddn);
1210         struct ldb_dn *newparent = ldb_dn_get_parent(req, req->op.rename.newdn);
1211         const struct dsdb_schema *schema;
1212         struct ldb_context *ldb;
1213         struct security_descriptor *sd = NULL;
1214         struct dom_sid *sid = NULL;
1215         struct ldb_result *acl_res;
1216         const struct GUID *guid;
1217         struct ldb_dn *nc_root;
1218         struct object_tree *root = NULL;
1219         struct object_tree *new_node = NULL;
1220         struct ldb_control *as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1221         TALLOC_CTX *tmp_ctx = talloc_new(req);
1222         NTSTATUS status;
1223         uint32_t access_granted;
1224         const char *rdn_name;
1225         static const char *acl_attrs[] = {
1226                 "nTSecurityDescriptor",
1227                 "objectClass",
1228                 "objectSid",
1229                 NULL
1230         };
1231
1232         if (as_system != NULL) {
1233                 as_system->critical = 0;
1234         }
1235
1236         DEBUG(10, ("ldb:acl_rename: %s\n", ldb_dn_get_linearized(req->op.rename.olddn)));
1237         if (dsdb_module_am_system(module) || as_system) {
1238                 return ldb_next_request(module, req);
1239         }
1240         if (ldb_dn_is_special(req->op.rename.olddn)) {
1241                 return ldb_next_request(module, req);
1242         }
1243
1244         ldb = ldb_module_get_ctx(module);
1245
1246         /* Make sure we aren't renaming/moving a NC */
1247
1248         ret = dsdb_find_nc_root(ldb, req, req->op.rename.olddn, &nc_root);
1249         if (ret != LDB_SUCCESS) {
1250                 return ret;
1251         }
1252         if (ldb_dn_compare(nc_root, req->op.rename.olddn) == 0) {
1253                 talloc_free(nc_root);
1254                 DEBUG(10,("acl:renaming/moving a NC\n"));
1255                 /* Windows returns "ERR_UNWILLING_TO_PERFORM */
1256                 return ldb_module_done(req, NULL, NULL,
1257                                        LDB_ERR_UNWILLING_TO_PERFORM);
1258         }
1259         talloc_free(nc_root);
1260
1261         /* Look for the parent */
1262
1263         ret = dsdb_module_search_dn(module, tmp_ctx, &acl_res,
1264                                     req->op.rename.olddn, acl_attrs,
1265                                     DSDB_FLAG_NEXT_MODULE |
1266                                     DSDB_FLAG_AS_SYSTEM |
1267                                     DSDB_SEARCH_SHOW_RECYCLED, req);
1268         /* we sould be able to find the parent */
1269         if (ret != LDB_SUCCESS) {
1270                 DEBUG(10,("acl: failed to find object %s\n",
1271                           ldb_dn_get_linearized(req->op.rename.olddn)));
1272                 talloc_free(tmp_ctx);
1273                 return ret;
1274         }
1275
1276         schema = dsdb_get_schema(ldb, acl_res);
1277         if (!schema) {
1278                 talloc_free(tmp_ctx);
1279                 return ldb_operr(ldb);
1280         }
1281
1282         guid = get_oc_guid_from_message(schema, acl_res->msgs[0]);
1283         if (!insert_in_object_tree(tmp_ctx, guid, SEC_ADS_WRITE_PROP,
1284                                    &root, &new_node)) {
1285                 talloc_free(tmp_ctx);
1286                 return ldb_operr(ldb);
1287         };
1288
1289         guid = attribute_schemaid_guid_by_lDAPDisplayName(schema,
1290                                                           "name");
1291         if (!insert_in_object_tree(tmp_ctx, guid, SEC_ADS_WRITE_PROP,
1292                                    &new_node, &new_node)) {
1293                 talloc_free(tmp_ctx);
1294                 return ldb_operr(ldb);
1295         };
1296
1297         rdn_name = ldb_dn_get_rdn_name(req->op.rename.olddn);
1298         if (rdn_name == NULL) {
1299                 talloc_free(tmp_ctx);
1300                 return ldb_operr(ldb);
1301         }
1302         guid = attribute_schemaid_guid_by_lDAPDisplayName(schema,
1303                                                           rdn_name);
1304         if (!insert_in_object_tree(tmp_ctx, guid, SEC_ADS_WRITE_PROP,
1305                                    &new_node, &new_node)) {
1306                 talloc_free(tmp_ctx);
1307                 return ldb_operr(ldb);
1308         };
1309
1310         ret = dsdb_get_sd_from_ldb_message(ldb, req, acl_res->msgs[0], &sd);
1311
1312         if (ret != LDB_SUCCESS) {
1313                 talloc_free(tmp_ctx);
1314                 return ldb_operr(ldb);
1315         }
1316         /* Theoretically we pass the check if the object has no sd */
1317         if (!sd) {
1318                 talloc_free(tmp_ctx);
1319                 return LDB_SUCCESS;
1320         }
1321         sid = samdb_result_dom_sid(req, acl_res->msgs[0], "objectSid");
1322         status = sec_access_check_ds(sd, acl_user_token(module),
1323                                      SEC_ADS_WRITE_PROP,
1324                                      &access_granted,
1325                                      root,
1326                                      sid);
1327
1328         if (!NT_STATUS_IS_OK(status)) {
1329                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1330                                        "Object %s has no wp on name\n",
1331                                        ldb_dn_get_linearized(req->op.rename.olddn));
1332                 dsdb_acl_debug(sd,
1333                           acl_user_token(module),
1334                           req->op.rename.olddn,
1335                           true,
1336                           10);
1337                 talloc_free(tmp_ctx);
1338                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1339         }
1340
1341         if (ldb_dn_compare(oldparent, newparent) == 0) {
1342                 /* regular rename, not move, nothing more to do */
1343                 talloc_free(tmp_ctx);
1344                 return ldb_next_request(module, req);
1345         }
1346
1347         /* new parent should have create child */
1348         root = NULL;
1349         new_node = NULL;
1350         guid = get_oc_guid_from_message(schema, acl_res->msgs[0]);
1351         if (!guid) {
1352                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1353                                        "acl:renamed object has no object class\n");
1354                 talloc_free(tmp_ctx);
1355                 return ldb_module_done(req, NULL, NULL,  LDB_ERR_OPERATIONS_ERROR);
1356         }
1357
1358         ret = dsdb_module_check_access_on_dn(module, req, newparent, SEC_ADS_CREATE_CHILD, guid, req);
1359         if (ret != LDB_SUCCESS) {
1360                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1361                                        "acl:access_denied renaming %s",
1362                                        ldb_dn_get_linearized(req->op.rename.olddn));
1363                 talloc_free(tmp_ctx);
1364                 return ret;
1365         }
1366         /* do we have delete object on the object? */
1367
1368         status = sec_access_check_ds(sd, acl_user_token(module),
1369                                      SEC_STD_DELETE,
1370                                      &access_granted,
1371                                      NULL,
1372                                      sid);
1373
1374         if (NT_STATUS_IS_OK(status)) {
1375                 talloc_free(tmp_ctx);
1376                 return ldb_next_request(module, req);
1377         }
1378         /* what about delete child on the current parent */
1379         ret = dsdb_module_check_access_on_dn(module, req, oldparent, SEC_ADS_DELETE_CHILD, NULL, req);
1380         if (ret != LDB_SUCCESS) {
1381                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1382                                        "acl:access_denied renaming %s", ldb_dn_get_linearized(req->op.rename.olddn));
1383                 talloc_free(tmp_ctx);
1384                 return ldb_module_done(req, NULL, NULL, ret);
1385         }
1386
1387         talloc_free(tmp_ctx);
1388
1389         return ldb_next_request(module, req);
1390 }
1391
1392 static int acl_search_update_confidential_attrs(struct acl_context *ac,
1393                                                 struct acl_private *data)
1394 {
1395         struct dsdb_attribute *a;
1396         uint32_t n = 0;
1397
1398         if ((ac->schema == data->cached_schema_ptr) &&
1399             (ac->schema->loaded_usn == data->cached_schema_loaded_usn) &&
1400             (ac->schema->metadata_usn == data->cached_schema_metadata_usn))
1401         {
1402                 return LDB_SUCCESS;
1403         }
1404
1405         data->cached_schema_ptr = NULL;
1406         data->cached_schema_loaded_usn = 0;
1407         data->cached_schema_metadata_usn = 0;
1408         TALLOC_FREE(data->confidential_attrs);
1409
1410         if (ac->schema == NULL) {
1411                 return LDB_SUCCESS;
1412         }
1413
1414         for (a = ac->schema->attributes; a; a = a->next) {
1415                 const char **attrs = data->confidential_attrs;
1416
1417                 if (!(a->searchFlags & SEARCH_FLAG_CONFIDENTIAL)) {
1418                         continue;
1419                 }
1420
1421                 attrs = talloc_realloc(data, attrs, const char *, n + 2);
1422                 if (attrs == NULL) {
1423                         TALLOC_FREE(data->confidential_attrs);
1424                         return ldb_module_oom(ac->module);
1425                 }
1426
1427                 attrs[n] = a->lDAPDisplayName;
1428                 attrs[n+1] = NULL;
1429                 n++;
1430
1431                 data->confidential_attrs = attrs;
1432         }
1433
1434         data->cached_schema_ptr = ac->schema;
1435         data->cached_schema_loaded_usn = ac->schema->loaded_usn;
1436         data->cached_schema_metadata_usn = ac->schema->metadata_usn;
1437
1438         return LDB_SUCCESS;
1439 }
1440
1441 static int acl_search_callback(struct ldb_request *req, struct ldb_reply *ares)
1442 {
1443         struct acl_context *ac;
1444         struct acl_private *data;
1445         struct ldb_result *acl_res;
1446         static const char *acl_attrs[] = {
1447                 "objectClass",
1448                 "nTSecurityDescriptor",
1449                 "objectSid",
1450                 NULL
1451         };
1452         int ret;
1453         unsigned int i;
1454
1455         ac = talloc_get_type(req->context, struct acl_context);
1456         data = talloc_get_type(ldb_module_get_private(ac->module), struct acl_private);
1457         if (!ares) {
1458                 return ldb_module_done(ac->req, NULL, NULL,
1459                                        LDB_ERR_OPERATIONS_ERROR);
1460         }
1461         if (ares->error != LDB_SUCCESS) {
1462                 return ldb_module_done(ac->req, ares->controls,
1463                                        ares->response, ares->error);
1464         }
1465
1466         switch (ares->type) {
1467         case LDB_REPLY_ENTRY:
1468                 if (ac->constructed_attrs) {
1469                         ret = dsdb_module_search_dn(ac->module, ac, &acl_res, ares->message->dn, 
1470                                                     acl_attrs,
1471                                                     DSDB_FLAG_NEXT_MODULE |
1472                                                     DSDB_FLAG_AS_SYSTEM |
1473                                                     DSDB_SEARCH_SHOW_DELETED, req);
1474                         if (ret != LDB_SUCCESS) {
1475                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1476                         }
1477                 }
1478
1479                 if (ac->allowedAttributes || ac->allowedAttributesEffective) {
1480                         ret = acl_allowedAttributes(ac->module, ac->schema,
1481                                                     acl_res->msgs[0],
1482                                                     ares->message, ac);
1483                         if (ret != LDB_SUCCESS) {
1484                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1485                         }
1486                 }
1487
1488                 if (ac->allowedChildClasses) {
1489                         ret = acl_childClasses(ac->module, ac->schema,
1490                                                acl_res->msgs[0],
1491                                                ares->message,
1492                                                "allowedChildClasses");
1493                         if (ret != LDB_SUCCESS) {
1494                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1495                         }
1496                 }
1497
1498                 if (ac->allowedChildClassesEffective) {
1499                         ret = acl_childClassesEffective(ac->module, ac->schema,
1500                                                         acl_res->msgs[0],
1501                                                         ares->message, ac);
1502                         if (ret != LDB_SUCCESS) {
1503                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1504                         }
1505                 }
1506
1507                 if (ac->sDRightsEffective) {
1508                         ret = acl_sDRightsEffective(ac->module,
1509                                                     acl_res->msgs[0],
1510                                                     ares->message, ac);
1511                         if (ret != LDB_SUCCESS) {
1512                                 return ldb_module_done(ac->req, NULL, NULL, ret);
1513                         }
1514                 }
1515
1516                 if (data == NULL) {
1517                         return ldb_module_send_entry(ac->req, ares->message,
1518                                                      ares->controls);
1519                 }
1520
1521                 if (ac->am_system) {
1522                         return ldb_module_send_entry(ac->req, ares->message,
1523                                                      ares->controls);
1524                 }
1525
1526                 if (data->password_attrs != NULL) {
1527                         for (i = 0; data->password_attrs[i]; i++) {
1528                                 if ((!ac->userPassword) &&
1529                                     (ldb_attr_cmp(data->password_attrs[i],
1530                                                   "userPassword") == 0))
1531                                 {
1532                                                 continue;
1533                                 }
1534
1535                                 ldb_msg_remove_attr(ares->message, data->password_attrs[i]);
1536                         }
1537                 }
1538
1539                 if (ac->am_administrator) {
1540                         return ldb_module_send_entry(ac->req, ares->message,
1541                                                      ares->controls);
1542                 }
1543
1544                 ret = acl_search_update_confidential_attrs(ac, data);
1545                 if (ret != LDB_SUCCESS) {
1546                         return ret;
1547                 }
1548
1549                 if (data->confidential_attrs != NULL) {
1550                         for (i = 0; data->confidential_attrs[i]; i++) {
1551                                 ldb_msg_remove_attr(ares->message,
1552                                                     data->confidential_attrs[i]);
1553                         }
1554                 }
1555
1556                 return ldb_module_send_entry(ac->req, ares->message, ares->controls);
1557
1558         case LDB_REPLY_REFERRAL:
1559                 return ldb_module_send_referral(ac->req, ares->referral);
1560
1561         case LDB_REPLY_DONE:
1562                 return ldb_module_done(ac->req, ares->controls,
1563                                        ares->response, LDB_SUCCESS);
1564
1565         }
1566         return LDB_SUCCESS;
1567 }
1568
1569 static int acl_search(struct ldb_module *module, struct ldb_request *req)
1570 {
1571         struct ldb_context *ldb;
1572         struct acl_context *ac;
1573         struct ldb_parse_tree *down_tree;
1574         struct ldb_request *down_req;
1575         struct acl_private *data;
1576         int ret;
1577         unsigned int i;
1578
1579         ldb = ldb_module_get_ctx(module);
1580
1581         ac = talloc_zero(req, struct acl_context);
1582         if (ac == NULL) {
1583                 return ldb_oom(ldb);
1584         }
1585         data = talloc_get_type(ldb_module_get_private(module), struct acl_private);
1586
1587         ac->module = module;
1588         ac->req = req;
1589         ac->am_system = dsdb_module_am_system(module);
1590         ac->am_administrator = dsdb_module_am_administrator(module);
1591         ac->constructed_attrs = false;
1592         ac->modify_search = true;
1593         ac->allowedAttributes = ldb_attr_in_list(req->op.search.attrs, "allowedAttributes");
1594         ac->allowedAttributesEffective = ldb_attr_in_list(req->op.search.attrs, "allowedAttributesEffective");
1595         ac->allowedChildClasses = ldb_attr_in_list(req->op.search.attrs, "allowedChildClasses");
1596         ac->allowedChildClassesEffective = ldb_attr_in_list(req->op.search.attrs, "allowedChildClassesEffective");
1597         ac->sDRightsEffective = ldb_attr_in_list(req->op.search.attrs, "sDRightsEffective");
1598         ac->userPassword = dsdb_user_password_support(module, ac, req);
1599         ac->schema = dsdb_get_schema(ldb, ac);
1600
1601         ac->constructed_attrs |= ac->allowedAttributes;
1602         ac->constructed_attrs |= ac->allowedChildClasses;
1603         ac->constructed_attrs |= ac->allowedChildClassesEffective;
1604         ac->constructed_attrs |= ac->allowedAttributesEffective;
1605         ac->constructed_attrs |= ac->sDRightsEffective;
1606
1607         if (data == NULL) {
1608                 ac->modify_search = false;
1609         }
1610         if (ac->am_system) {
1611                 ac->modify_search = false;
1612         }
1613
1614         if (!ac->constructed_attrs && !ac->modify_search) {
1615                 return ldb_next_request(module, req);
1616         }
1617
1618         ret = acl_search_update_confidential_attrs(ac, data);
1619         if (ret != LDB_SUCCESS) {
1620                 return ret;
1621         }
1622
1623         down_tree = ldb_parse_tree_copy_shallow(ac, req->op.search.tree);
1624         if (down_tree == NULL) {
1625                 return ldb_oom(ldb);
1626         }
1627
1628         if (!ac->am_system && data->password_attrs) {
1629                 for (i = 0; data->password_attrs[i]; i++) {
1630                         if ((!ac->userPassword) &&
1631                             (ldb_attr_cmp(data->password_attrs[i],
1632                                           "userPassword") == 0))
1633                         {
1634                                 continue;
1635                         }
1636
1637                         ldb_parse_tree_attr_replace(down_tree,
1638                                                     data->password_attrs[i],
1639                                                     "kludgeACLredactedattribute");
1640                 }
1641         }
1642
1643         if (!ac->am_system && !ac->am_administrator && data->confidential_attrs) {
1644                 for (i = 0; data->confidential_attrs[i]; i++) {
1645                         ldb_parse_tree_attr_replace(down_tree,
1646                                                     data->confidential_attrs[i],
1647                                                     "kludgeACLredactedattribute");
1648                 }
1649         }
1650
1651         ret = ldb_build_search_req_ex(&down_req,
1652                                       ldb, ac,
1653                                       req->op.search.base,
1654                                       req->op.search.scope,
1655                                       down_tree,
1656                                       req->op.search.attrs,
1657                                       req->controls,
1658                                       ac, acl_search_callback,
1659                                       req);
1660         LDB_REQ_SET_LOCATION(down_req);
1661         if (ret != LDB_SUCCESS) {
1662                 return ret;
1663         }
1664         /* perform the search */
1665         return ldb_next_request(module, down_req);
1666 }
1667
1668 static int acl_extended(struct ldb_module *module, struct ldb_request *req)
1669 {
1670         struct ldb_context *ldb = ldb_module_get_ctx(module);
1671         struct ldb_control *as_system = ldb_request_get_control(req, LDB_CONTROL_AS_SYSTEM_OID);
1672
1673         /* allow everybody to read the sequence number */
1674         if (strcmp(req->op.extended.oid,
1675                    LDB_EXTENDED_SEQUENCE_NUMBER) == 0) {
1676                 return ldb_next_request(module, req);
1677         }
1678
1679         if (dsdb_module_am_system(module) ||
1680             dsdb_module_am_administrator(module) || as_system) {
1681                 return ldb_next_request(module, req);
1682         } else {
1683                 ldb_asprintf_errstring(ldb,
1684                                        "acl_extended: "
1685                                        "attempted database modify not permitted. "
1686                                        "User %s is not SYSTEM or an administrator",
1687                                        acl_user_name(req, module));
1688                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1689         }
1690 }
1691
1692 static const struct ldb_module_ops ldb_acl_module_ops = {
1693         .name              = "acl",
1694         .search            = acl_search,
1695         .add               = acl_add,
1696         .modify            = acl_modify,
1697         .del               = acl_delete,
1698         .rename            = acl_rename,
1699         .extended          = acl_extended,
1700         .init_context      = acl_module_init
1701 };
1702
1703 int ldb_acl_module_init(const char *version)
1704 {
1705         LDB_MODULE_CHECK_VERSION(version);
1706         return ldb_register_module(&ldb_acl_module_ops);
1707 }