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