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