s4:dsdb/descriptor: skip duplicates in descriptor_extended_sec_desc_propagation()
[samba.git] / source4 / dsdb / samdb / ldb_modules / descriptor.c
1 /*
2    ldb database library
3
4    Copyright (C) Simo Sorce  2006-2008
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2007
6    Copyright (C) Nadezhda Ivanova  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: DS Security descriptor module
26  *
27  *  Description:
28  *  - Calculate the security descriptor of a newly created object
29  *  - Perform sd recalculation on a move operation
30  *  - Handle sd modification invariants
31  *
32  *  Author: Nadezhda Ivanova
33  */
34
35 #include "includes.h"
36 #include <ldb_module.h>
37 #include "util/dlinklist.h"
38 #include "dsdb/samdb/samdb.h"
39 #include "librpc/ndr/libndr.h"
40 #include "librpc/gen_ndr/ndr_security.h"
41 #include "libcli/security/security.h"
42 #include "auth/auth.h"
43 #include "param/param.h"
44 #include "dsdb/samdb/ldb_modules/util.h"
45 #include "lib/util/util_tdb.h"
46 #include "lib/dbwrap/dbwrap.h"
47 #include "lib/dbwrap/dbwrap_rbt.h"
48
49 struct descriptor_changes {
50         struct descriptor_changes *prev, *next;
51         struct ldb_dn *nc_root;
52         struct GUID guid;
53         bool force_self;
54         bool force_children;
55         struct ldb_dn *stopped_dn;
56         size_t ref_count;
57 };
58
59 struct descriptor_transaction {
60         TALLOC_CTX *mem;
61         struct {
62                 /*
63                  * We used to have a list of changes, appended with each
64                  * DSDB_EXTENDED_SEC_DESC_PROPAGATION_OID operation.
65                  *
66                  * But the main problem was that a replication
67                  * cycle (mainly the initial replication) calls
68                  * DSDB_EXTENDED_SEC_DESC_PROPAGATION_OID for the
69                  * same object[GUID] more than once. With
70                  * DRSUAPI_DRS_GET_TGT we'll get the naming
71                  * context head object and other top level
72                  * containers, every often.
73                  *
74                  * It means we'll process objects more
75                  * than once and waste a lot of time
76                  * doing the same work again and again.
77                  *
78                  * We use an objectGUID based map in order to
79                  * avoid registering objects more than once.
80                  * In an domain with 22000 object it can
81                  * reduce the work from 4 hours down to ~ 3.5 minutes.
82                  */
83                 struct descriptor_changes *list;
84                 struct db_context *map;
85                 size_t num_registrations;
86                 size_t num_registered;
87                 size_t num_processed;
88         } changes;
89         struct {
90                 size_t num_processed;
91         } objects;
92 };
93
94 struct descriptor_data {
95         struct descriptor_transaction transaction;
96 };
97
98 struct descriptor_context {
99         struct ldb_module *module;
100         struct ldb_request *req;
101         struct ldb_message *msg;
102         struct ldb_reply *search_res;
103         struct ldb_reply *search_oc_res;
104         struct ldb_val *parentsd_val;
105         struct ldb_message_element *sd_element;
106         struct ldb_val *sd_val;
107         uint32_t sd_flags;
108         int (*step_fn)(struct descriptor_context *);
109 };
110
111 static struct dom_sid *get_default_ag(TALLOC_CTX *mem_ctx,
112                                struct ldb_dn *dn,
113                                struct security_token *token,
114                                struct ldb_context *ldb)
115 {
116         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
117         const struct dom_sid *domain_sid = samdb_domain_sid(ldb);
118         struct dom_sid *da_sid = dom_sid_add_rid(tmp_ctx, domain_sid, DOMAIN_RID_ADMINS);
119         struct dom_sid *ea_sid = dom_sid_add_rid(tmp_ctx, domain_sid, DOMAIN_RID_ENTERPRISE_ADMINS);
120         struct dom_sid *sa_sid = dom_sid_add_rid(tmp_ctx, domain_sid, DOMAIN_RID_SCHEMA_ADMINS);
121         struct dom_sid *dag_sid;
122         struct ldb_dn *nc_root;
123         int ret;
124
125         ret = dsdb_find_nc_root(ldb, tmp_ctx, dn, &nc_root);
126         if (ret != LDB_SUCCESS) {
127                 talloc_free(tmp_ctx);
128                 return NULL;
129         }
130
131         if (ldb_dn_compare(nc_root, ldb_get_schema_basedn(ldb)) == 0) {
132                 if (security_token_has_sid(token, sa_sid)) {
133                         dag_sid = dom_sid_dup(mem_ctx, sa_sid);
134                 } else if (security_token_has_sid(token, ea_sid)) {
135                         dag_sid = dom_sid_dup(mem_ctx, ea_sid);
136                 } else if (security_token_has_sid(token, da_sid)) {
137                         dag_sid = dom_sid_dup(mem_ctx, da_sid);
138                 } else if (security_token_is_system(token)) {
139                         dag_sid = dom_sid_dup(mem_ctx, sa_sid);
140                 } else {
141                         dag_sid = NULL;
142                 }
143         } else if (ldb_dn_compare(nc_root, ldb_get_config_basedn(ldb)) == 0) {
144                 if (security_token_has_sid(token, ea_sid)) {
145                         dag_sid = dom_sid_dup(mem_ctx, ea_sid);
146                 } else if (security_token_has_sid(token, da_sid)) {
147                         dag_sid = dom_sid_dup(mem_ctx, da_sid);
148                 } else if (security_token_is_system(token)) {
149                         dag_sid = dom_sid_dup(mem_ctx, ea_sid);
150                 } else {
151                         dag_sid = NULL;
152                 }
153         } else if (ldb_dn_compare(nc_root, ldb_get_default_basedn(ldb)) == 0) {
154                 if (security_token_has_sid(token, da_sid)) {
155                         dag_sid = dom_sid_dup(mem_ctx, da_sid);
156                 } else if (security_token_has_sid(token, ea_sid)) {
157                                 dag_sid = dom_sid_dup(mem_ctx, ea_sid);
158                 } else if (security_token_is_system(token)) {
159                         dag_sid = dom_sid_dup(mem_ctx, da_sid);
160                 } else {
161                         dag_sid = NULL;
162                 }
163         } else {
164                 dag_sid = NULL;
165         }
166
167         talloc_free(tmp_ctx);
168         return dag_sid;
169 }
170
171 static struct security_descriptor *get_sd_unpacked(struct ldb_module *module, TALLOC_CTX *mem_ctx,
172                                             const struct dsdb_class *objectclass)
173 {
174         struct ldb_context *ldb = ldb_module_get_ctx(module);
175         struct security_descriptor *sd;
176         const struct dom_sid *domain_sid = samdb_domain_sid(ldb);
177
178         if (!objectclass->defaultSecurityDescriptor || !domain_sid) {
179                 return NULL;
180         }
181
182         sd = sddl_decode(mem_ctx,
183                          objectclass->defaultSecurityDescriptor,
184                          domain_sid);
185         return sd;
186 }
187
188 static struct dom_sid *get_default_group(TALLOC_CTX *mem_ctx,
189                                          struct ldb_context *ldb,
190                                          struct dom_sid *dag)
191 {
192         /*
193          * This depends on the function level of the DC
194          * which is 2008R2 in our case. Which means it is
195          * higher than 2003 and we should use the
196          * "default administrator group" also as owning group.
197          *
198          * This matches dcpromo for a 2003 domain
199          * on a Windows 2008R2 DC.
200          */
201         return dag;
202 }
203
204 static struct security_descriptor *descr_handle_sd_flags(TALLOC_CTX *mem_ctx,
205                                                          struct security_descriptor *new_sd,
206                                                          struct security_descriptor *old_sd,
207                                                          uint32_t sd_flags)
208 {
209         struct security_descriptor *final_sd; 
210         /* if there is no control or control == 0 modify everything */
211         if (!sd_flags) {
212                 return new_sd;
213         }
214
215         final_sd = talloc_zero(mem_ctx, struct security_descriptor);
216         final_sd->revision = SECURITY_DESCRIPTOR_REVISION_1;
217         final_sd->type = SEC_DESC_SELF_RELATIVE;
218
219         if (sd_flags & (SECINFO_OWNER)) {
220                 if (new_sd->owner_sid) {
221                         final_sd->owner_sid = talloc_memdup(mem_ctx, new_sd->owner_sid, sizeof(struct dom_sid));
222                 }
223                 final_sd->type |= new_sd->type & SEC_DESC_OWNER_DEFAULTED;
224         }
225         else if (old_sd) {
226                 if (old_sd->owner_sid) {
227                         final_sd->owner_sid = talloc_memdup(mem_ctx, old_sd->owner_sid, sizeof(struct dom_sid));
228                 }
229                 final_sd->type |= old_sd->type & SEC_DESC_OWNER_DEFAULTED;
230         }
231
232         if (sd_flags & (SECINFO_GROUP)) {
233                 if (new_sd->group_sid) {
234                         final_sd->group_sid = talloc_memdup(mem_ctx, new_sd->group_sid, sizeof(struct dom_sid));
235                 }
236                 final_sd->type |= new_sd->type & SEC_DESC_GROUP_DEFAULTED;
237         } 
238         else if (old_sd) {
239                 if (old_sd->group_sid) {
240                         final_sd->group_sid = talloc_memdup(mem_ctx, old_sd->group_sid, sizeof(struct dom_sid));
241                 }
242                 final_sd->type |= old_sd->type & SEC_DESC_GROUP_DEFAULTED;
243         }
244
245         if (sd_flags & (SECINFO_SACL)) {
246                 final_sd->sacl = security_acl_dup(mem_ctx,new_sd->sacl);
247                 final_sd->type |= new_sd->type & (SEC_DESC_SACL_PRESENT |
248                         SEC_DESC_SACL_DEFAULTED|SEC_DESC_SACL_AUTO_INHERIT_REQ |
249                         SEC_DESC_SACL_AUTO_INHERITED|SEC_DESC_SACL_PROTECTED |
250                         SEC_DESC_SERVER_SECURITY);
251         } 
252         else if (old_sd && old_sd->sacl) {
253                 final_sd->sacl = security_acl_dup(mem_ctx,old_sd->sacl);
254                 final_sd->type |= old_sd->type & (SEC_DESC_SACL_PRESENT |
255                         SEC_DESC_SACL_DEFAULTED|SEC_DESC_SACL_AUTO_INHERIT_REQ |
256                         SEC_DESC_SACL_AUTO_INHERITED|SEC_DESC_SACL_PROTECTED |
257                         SEC_DESC_SERVER_SECURITY);
258         }
259
260         if (sd_flags & (SECINFO_DACL)) {
261                 final_sd->dacl = security_acl_dup(mem_ctx,new_sd->dacl);
262                 final_sd->type |= new_sd->type & (SEC_DESC_DACL_PRESENT |
263                         SEC_DESC_DACL_DEFAULTED|SEC_DESC_DACL_AUTO_INHERIT_REQ |
264                         SEC_DESC_DACL_AUTO_INHERITED|SEC_DESC_DACL_PROTECTED |
265                         SEC_DESC_DACL_TRUSTED);
266         } 
267         else if (old_sd && old_sd->dacl) {
268                 final_sd->dacl = security_acl_dup(mem_ctx,old_sd->dacl);
269                 final_sd->type |= old_sd->type & (SEC_DESC_DACL_PRESENT |
270                         SEC_DESC_DACL_DEFAULTED|SEC_DESC_DACL_AUTO_INHERIT_REQ |
271                         SEC_DESC_DACL_AUTO_INHERITED|SEC_DESC_DACL_PROTECTED |
272                         SEC_DESC_DACL_TRUSTED);
273         }
274         /* not so sure about this */
275         final_sd->type |= new_sd->type & SEC_DESC_RM_CONTROL_VALID;
276         return final_sd;
277 }
278
279 static DATA_BLOB *get_new_descriptor(struct ldb_module *module,
280                                      struct ldb_dn *dn,
281                                      TALLOC_CTX *mem_ctx,
282                                      const struct dsdb_class *objectclass,
283                                      const struct ldb_val *parent,
284                                      const struct ldb_val *object,
285                                      const struct ldb_val *old_sd,
286                                      uint32_t sd_flags)
287 {
288         struct security_descriptor *user_descriptor = NULL, *parent_descriptor = NULL;
289         struct security_descriptor *old_descriptor = NULL;
290         struct security_descriptor *new_sd, *final_sd;
291         DATA_BLOB *linear_sd;
292         enum ndr_err_code ndr_err;
293         struct ldb_context *ldb = ldb_module_get_ctx(module);
294         struct auth_session_info *session_info
295                 = ldb_get_opaque(ldb, DSDB_SESSION_INFO);
296         const struct dom_sid *domain_sid = samdb_domain_sid(ldb);
297         struct dom_sid *default_owner;
298         struct dom_sid *default_group;
299         struct security_descriptor *default_descriptor = NULL;
300         struct GUID *object_list = NULL;
301
302         if (objectclass != NULL) {
303                 default_descriptor = get_sd_unpacked(module, mem_ctx, objectclass);
304                 object_list = talloc_zero_array(mem_ctx, struct GUID, 2);
305                 if (object_list == NULL) {
306                         return NULL;
307                 }
308                 object_list[0] = objectclass->schemaIDGUID;
309         }
310
311         if (object) {
312                 user_descriptor = talloc(mem_ctx, struct security_descriptor);
313                 if (!user_descriptor) {
314                         return NULL;
315                 }
316                 ndr_err = ndr_pull_struct_blob(object, user_descriptor, 
317                                                user_descriptor,
318                                                (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
319
320                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
321                         talloc_free(user_descriptor);
322                         return NULL;
323                 }
324         } else {
325                 user_descriptor = default_descriptor;
326         }
327
328         if (old_sd) {
329                 old_descriptor = talloc(mem_ctx, struct security_descriptor);
330                 if (!old_descriptor) {
331                         return NULL;
332                 }
333                 ndr_err = ndr_pull_struct_blob(old_sd, old_descriptor, 
334                                                old_descriptor,
335                                                (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
336
337                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
338                         talloc_free(old_descriptor);
339                         return NULL;
340                 }
341         }
342
343         if (parent) {
344                 parent_descriptor = talloc(mem_ctx, struct security_descriptor);
345                 if (!parent_descriptor) {
346                         return NULL;
347                 }
348                 ndr_err = ndr_pull_struct_blob(parent, parent_descriptor, 
349                                                parent_descriptor,
350                                                (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
351
352                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
353                         talloc_free(parent_descriptor);
354                         return NULL;
355                 }
356         }
357
358         if (user_descriptor && default_descriptor &&
359             (user_descriptor->dacl == NULL))
360         {
361                 user_descriptor->dacl = default_descriptor->dacl;
362                 user_descriptor->type |= default_descriptor->type & (
363                         SEC_DESC_DACL_PRESENT |
364                         SEC_DESC_DACL_DEFAULTED|SEC_DESC_DACL_AUTO_INHERIT_REQ |
365                         SEC_DESC_DACL_AUTO_INHERITED|SEC_DESC_DACL_PROTECTED |
366                         SEC_DESC_DACL_TRUSTED);
367         }
368
369         if (user_descriptor && default_descriptor &&
370             (user_descriptor->sacl == NULL))
371         {
372                 user_descriptor->sacl = default_descriptor->sacl;
373                 user_descriptor->type |= default_descriptor->type & (
374                         SEC_DESC_SACL_PRESENT |
375                         SEC_DESC_SACL_DEFAULTED|SEC_DESC_SACL_AUTO_INHERIT_REQ |
376                         SEC_DESC_SACL_AUTO_INHERITED|SEC_DESC_SACL_PROTECTED |
377                         SEC_DESC_SERVER_SECURITY);
378         }
379
380
381         if (!(sd_flags & SECINFO_OWNER) && user_descriptor) {
382                 user_descriptor->owner_sid = NULL;
383
384                 /*
385                  * We need the correct owner sid
386                  * when calculating the DACL or SACL
387                  */
388                 if (old_descriptor) {
389                         user_descriptor->owner_sid = old_descriptor->owner_sid;
390                 }
391         }
392         if (!(sd_flags & SECINFO_GROUP) && user_descriptor) {
393                 user_descriptor->group_sid = NULL;
394
395                 /*
396                  * We need the correct group sid
397                  * when calculating the DACL or SACL
398                  */
399                 if (old_descriptor) {
400                         user_descriptor->group_sid = old_descriptor->group_sid;
401                 }
402         }
403         if (!(sd_flags & SECINFO_DACL) && user_descriptor) {
404                 user_descriptor->dacl = NULL;
405
406                 /*
407                  * We add SEC_DESC_DACL_PROTECTED so that
408                  * create_security_descriptor() skips
409                  * the unused inheritance calculation
410                  */
411                 user_descriptor->type |= SEC_DESC_DACL_PROTECTED;
412         }
413         if (!(sd_flags & SECINFO_SACL) && user_descriptor) {
414                 user_descriptor->sacl = NULL;
415
416                 /*
417                  * We add SEC_DESC_SACL_PROTECTED so that
418                  * create_security_descriptor() skips
419                  * the unused inheritance calculation
420                  */
421                 user_descriptor->type |= SEC_DESC_SACL_PROTECTED;
422         }
423
424         default_owner = get_default_ag(mem_ctx, dn,
425                                        session_info->security_token, ldb);
426         default_group = get_default_group(mem_ctx, ldb, default_owner);
427         new_sd = create_security_descriptor(mem_ctx,
428                                             parent_descriptor,
429                                             user_descriptor,
430                                             true,
431                                             object_list,
432                                             SEC_DACL_AUTO_INHERIT |
433                                             SEC_SACL_AUTO_INHERIT,
434                                             session_info->security_token,
435                                             default_owner, default_group,
436                                             map_generic_rights_ds);
437         if (!new_sd) {
438                 return NULL;
439         }
440         final_sd = descr_handle_sd_flags(mem_ctx, new_sd, old_descriptor, sd_flags);
441
442         if (!final_sd) {
443                 return NULL;
444         }
445
446         if (final_sd->dacl) {
447                 final_sd->dacl->revision = SECURITY_ACL_REVISION_ADS;
448         }
449         if (final_sd->sacl) {
450                 final_sd->sacl->revision = SECURITY_ACL_REVISION_ADS;
451         }
452
453         {
454                 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
455                 DBG_DEBUG("Object %s created with descriptor %s\n\n",
456                           ldb_dn_get_linearized(dn),
457                           sddl_encode(tmp_ctx, final_sd, domain_sid));
458                 TALLOC_FREE(tmp_ctx);
459         }
460
461         linear_sd = talloc(mem_ctx, DATA_BLOB);
462         if (!linear_sd) {
463                 return NULL;
464         }
465
466         ndr_err = ndr_push_struct_blob(linear_sd, mem_ctx,
467                                        final_sd,
468                                        (ndr_push_flags_fn_t)ndr_push_security_descriptor);
469         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
470                 return NULL;
471         }
472
473         return linear_sd;
474 }
475
476 static DATA_BLOB *descr_get_descriptor_to_show(struct ldb_module *module,
477                                                TALLOC_CTX *mem_ctx,
478                                                struct ldb_val *sd,
479                                                uint32_t sd_flags)
480 {
481         struct security_descriptor *old_sd, *final_sd;
482         DATA_BLOB *linear_sd;
483         enum ndr_err_code ndr_err;
484
485         old_sd = talloc(mem_ctx, struct security_descriptor);
486         if (!old_sd) {
487                 return NULL;
488         }
489         ndr_err = ndr_pull_struct_blob(sd, old_sd, 
490                                        old_sd,
491                                        (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
492
493         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
494                 talloc_free(old_sd);
495                 return NULL;
496         }
497
498         final_sd = descr_handle_sd_flags(mem_ctx, old_sd, NULL, sd_flags);
499
500         if (!final_sd) {
501                 return NULL;
502         }
503
504         linear_sd = talloc(mem_ctx, DATA_BLOB);
505         if (!linear_sd) {
506                 return NULL;
507         }
508
509         ndr_err = ndr_push_struct_blob(linear_sd, mem_ctx,
510                                        final_sd,
511                                        (ndr_push_flags_fn_t)ndr_push_security_descriptor);
512         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
513                 return NULL;
514         }
515
516         return linear_sd;
517 }
518
519 static struct descriptor_context *descriptor_init_context(struct ldb_module *module,
520                                                           struct ldb_request *req)
521 {
522         struct ldb_context *ldb;
523         struct descriptor_context *ac;
524
525         ldb = ldb_module_get_ctx(module);
526
527         ac = talloc_zero(req, struct descriptor_context);
528         if (ac == NULL) {
529                 ldb_set_errstring(ldb, "Out of Memory");
530                 return NULL;
531         }
532
533         ac->module = module;
534         ac->req = req;
535         return ac;
536 }
537
538 static int descriptor_search_callback(struct ldb_request *req, struct ldb_reply *ares)
539 {
540         struct descriptor_context *ac;
541         struct ldb_val *sd_val = NULL;
542         struct ldb_message_element *sd_el;
543         DATA_BLOB *show_sd;
544         int ret = LDB_SUCCESS;
545
546         ac = talloc_get_type(req->context, struct descriptor_context);
547
548         if (!ares) {
549                 ret = LDB_ERR_OPERATIONS_ERROR;
550                 goto fail;
551         }
552         if (ares->error != LDB_SUCCESS) {
553                 return ldb_module_done(ac->req, ares->controls,
554                                         ares->response, ares->error);
555         }
556
557         switch (ares->type) {
558         case LDB_REPLY_ENTRY:
559                 sd_el = ldb_msg_find_element(ares->message, "nTSecurityDescriptor");
560                 if (sd_el) {
561                         sd_val = sd_el->values;
562                 }
563
564                 if (sd_val) {
565                         show_sd = descr_get_descriptor_to_show(ac->module, ac->req,
566                                                                sd_val, ac->sd_flags);
567                         if (!show_sd) {
568                                 ret = LDB_ERR_OPERATIONS_ERROR;
569                                 goto fail;
570                         }
571                         ldb_msg_remove_attr(ares->message, "nTSecurityDescriptor");
572                         ret = ldb_msg_add_steal_value(ares->message, "nTSecurityDescriptor", show_sd);
573                         if (ret != LDB_SUCCESS) {
574                                 goto fail;
575                         }
576                 }
577                 return ldb_module_send_entry(ac->req, ares->message, ares->controls);
578
579         case LDB_REPLY_REFERRAL:
580                 return ldb_module_send_referral(ac->req, ares->referral);
581
582         case LDB_REPLY_DONE:
583                 return ldb_module_done(ac->req, ares->controls,
584                                         ares->response, ares->error);
585         }
586
587 fail:
588         talloc_free(ares);
589         return ldb_module_done(ac->req, NULL, NULL, ret);
590 }
591
592 static int descriptor_add(struct ldb_module *module, struct ldb_request *req)
593 {
594         struct ldb_context *ldb = ldb_module_get_ctx(module);
595         struct ldb_request *add_req;
596         struct ldb_message *msg;
597         struct ldb_result *parent_res;
598         const struct ldb_val *parent_sd = NULL;
599         const struct ldb_val *user_sd;
600         struct ldb_dn *dn = req->op.add.message->dn;
601         struct ldb_dn *parent_dn, *nc_root;
602         struct ldb_message_element *objectclass_element, *sd_element;
603         int ret;
604         const struct dsdb_schema *schema;
605         DATA_BLOB *sd;
606         const struct dsdb_class *objectclass;
607         static const char * const parent_attrs[] = { "nTSecurityDescriptor", NULL };
608         uint32_t instanceType;
609         bool isNC = false;
610         uint32_t sd_flags = dsdb_request_sd_flags(req, NULL);
611
612         /* do not manipulate our control entries */
613         if (ldb_dn_is_special(dn)) {
614                 return ldb_next_request(module, req);
615         }
616
617         user_sd = ldb_msg_find_ldb_val(req->op.add.message, "nTSecurityDescriptor");
618         sd_element = ldb_msg_find_element(req->op.add.message, "nTSecurityDescriptor");
619         /* nTSecurityDescriptor without a value is an error, letting through so it is handled */
620         if (user_sd == NULL && sd_element) {
621                 return ldb_next_request(module, req);
622         }
623
624         ldb_debug(ldb, LDB_DEBUG_TRACE,"descriptor_add: %s\n", ldb_dn_get_linearized(dn));
625
626         instanceType = ldb_msg_find_attr_as_uint(req->op.add.message, "instanceType", 0);
627
628         if (instanceType & INSTANCE_TYPE_IS_NC_HEAD) {
629                 isNC = true;
630         }
631
632         if (!isNC) {
633                 ret = dsdb_find_nc_root(ldb, req, dn, &nc_root);
634                 if (ret != LDB_SUCCESS) {
635                         ldb_debug(ldb, LDB_DEBUG_TRACE,"descriptor_add: Could not find NC root for %s\n",
636                                 ldb_dn_get_linearized(dn));
637                         return ret;
638                 }
639
640                 if (ldb_dn_compare(dn, nc_root) == 0) {
641                         DEBUG(0, ("Found DN %s being a NC by the old method\n", ldb_dn_get_linearized(dn)));
642                         isNC = true;
643                 }
644         }
645
646         if (isNC) {
647                 DEBUG(2, ("DN: %s is a NC\n", ldb_dn_get_linearized(dn)));
648         }
649         if (!isNC) {
650                 /* if the object has a parent, retrieve its SD to
651                  * use for calculation. Unfortunately we do not yet have
652                  * instanceType, so we use dsdb_find_nc_root. */
653
654                 parent_dn = ldb_dn_get_parent(req, dn);
655                 if (parent_dn == NULL) {
656                         return ldb_oom(ldb);
657                 }
658
659                 /* we aren't any NC */
660                 ret = dsdb_module_search_dn(module, req, &parent_res, parent_dn,
661                                             parent_attrs,
662                                             DSDB_FLAG_NEXT_MODULE |
663                                             DSDB_FLAG_AS_SYSTEM |
664                                             DSDB_SEARCH_SHOW_RECYCLED,
665                                             req);
666                 if (ret != LDB_SUCCESS) {
667                         ldb_debug(ldb, LDB_DEBUG_TRACE,"descriptor_add: Could not find SD for %s\n",
668                                   ldb_dn_get_linearized(parent_dn));
669                         return ret;
670                 }
671                 if (parent_res->count != 1) {
672                         return ldb_operr(ldb);
673                 }
674                 parent_sd = ldb_msg_find_ldb_val(parent_res->msgs[0], "nTSecurityDescriptor");
675         }
676
677         schema = dsdb_get_schema(ldb, req);
678
679         objectclass_element = ldb_msg_find_element(req->op.add.message, "objectClass");
680         if (objectclass_element == NULL) {
681                 return ldb_operr(ldb);
682         }
683
684         objectclass = dsdb_get_last_structural_class(schema,
685                                                      objectclass_element);
686         if (objectclass == NULL) {
687                 return ldb_operr(ldb);
688         }
689
690         /*
691          * The SD_FLAG control is ignored on add
692          * and we default to all bits set.
693          */
694         sd_flags = SECINFO_OWNER|SECINFO_GROUP|SECINFO_SACL|SECINFO_DACL;
695
696         sd = get_new_descriptor(module, dn, req,
697                                 objectclass, parent_sd,
698                                 user_sd, NULL, sd_flags);
699         if (sd == NULL) {
700                 return ldb_operr(ldb);
701         }
702         msg = ldb_msg_copy_shallow(req, req->op.add.message);
703         if (msg == NULL) {
704                 return ldb_oom(ldb);
705         }
706         if (sd_element != NULL) {
707                 sd_element->values[0] = *sd;
708         } else {
709                 ret = ldb_msg_add_steal_value(msg,
710                                               "nTSecurityDescriptor",
711                                               sd);
712                 if (ret != LDB_SUCCESS) {
713                         return ret;
714                 }
715         }
716
717         ret = ldb_build_add_req(&add_req, ldb, req,
718                                 msg,
719                                 req->controls,
720                                 req, dsdb_next_callback,
721                                 req);
722         LDB_REQ_SET_LOCATION(add_req);
723         if (ret != LDB_SUCCESS) {
724                 return ldb_error(ldb, ret,
725                                  "descriptor_add: Error creating new add request.");
726         }
727
728         return ldb_next_request(module, add_req);
729 }
730
731 static int descriptor_modify(struct ldb_module *module, struct ldb_request *req)
732 {
733         struct ldb_context *ldb = ldb_module_get_ctx(module);
734         struct ldb_request *mod_req;
735         struct ldb_message *msg;
736         struct ldb_result *current_res, *parent_res;
737         const struct ldb_val *old_sd = NULL;
738         const struct ldb_val *parent_sd = NULL;
739         const struct ldb_val *user_sd;
740         struct ldb_dn *dn = req->op.mod.message->dn;
741         struct ldb_dn *parent_dn;
742         struct ldb_message_element *objectclass_element, *sd_element;
743         int ret;
744         uint32_t instanceType;
745         bool explicit_sd_flags = false;
746         uint32_t sd_flags = dsdb_request_sd_flags(req, &explicit_sd_flags);
747         const struct dsdb_schema *schema;
748         DATA_BLOB *sd;
749         const struct dsdb_class *objectclass;
750         static const char * const parent_attrs[] = { "nTSecurityDescriptor", NULL };
751         static const char * const current_attrs[] = { "nTSecurityDescriptor",
752                                                       "instanceType",
753                                                       "objectClass", NULL };
754         struct ldb_control *sd_propagation_control;
755         int cmp_ret = -1;
756
757         /* do not manipulate our control entries */
758         if (ldb_dn_is_special(dn)) {
759                 return ldb_next_request(module, req);
760         }
761
762         sd_propagation_control = ldb_request_get_control(req,
763                                         DSDB_CONTROL_SEC_DESC_PROPAGATION_OID);
764         if (sd_propagation_control != NULL) {
765                 if (sd_propagation_control->data != module) {
766                         return ldb_operr(ldb);
767                 }
768                 if (req->op.mod.message->num_elements != 0) {
769                         return ldb_operr(ldb);
770                 }
771                 if (explicit_sd_flags) {
772                         return ldb_operr(ldb);
773                 }
774                 if (sd_flags != 0xF) {
775                         return ldb_operr(ldb);
776                 }
777                 if (sd_propagation_control->critical == 0) {
778                         return ldb_operr(ldb);
779                 }
780
781                 sd_propagation_control->critical = 0;
782         }
783
784         sd_element = ldb_msg_find_element(req->op.mod.message, "nTSecurityDescriptor");
785         if (sd_propagation_control == NULL && sd_element == NULL) {
786                 return ldb_next_request(module, req);
787         }
788
789         /*
790          * nTSecurityDescriptor with DELETE is not supported yet.
791          * TODO: handle this correctly.
792          */
793         if (sd_propagation_control == NULL &&
794             LDB_FLAG_MOD_TYPE(sd_element->flags) == LDB_FLAG_MOD_DELETE)
795         {
796                 return ldb_module_error(module,
797                                         LDB_ERR_UNWILLING_TO_PERFORM,
798                                         "MOD_DELETE for nTSecurityDescriptor "
799                                         "not supported yet");
800         }
801
802         user_sd = ldb_msg_find_ldb_val(req->op.mod.message, "nTSecurityDescriptor");
803         /* nTSecurityDescriptor without a value is an error, letting through so it is handled */
804         if (sd_propagation_control == NULL && user_sd == NULL) {
805                 return ldb_next_request(module, req);
806         }
807
808         ldb_debug(ldb, LDB_DEBUG_TRACE,"descriptor_modify: %s\n", ldb_dn_get_linearized(dn));
809
810         ret = dsdb_module_search_dn(module, req, &current_res, dn,
811                                     current_attrs,
812                                     DSDB_FLAG_NEXT_MODULE |
813                                     DSDB_FLAG_AS_SYSTEM |
814                                     DSDB_SEARCH_SHOW_RECYCLED |
815                                     DSDB_SEARCH_SHOW_EXTENDED_DN,
816                                     req);
817         if (ret != LDB_SUCCESS) {
818                 ldb_debug(ldb, LDB_DEBUG_ERROR,"descriptor_modify: Could not find %s\n",
819                           ldb_dn_get_linearized(dn));
820                 return ret;
821         }
822
823         instanceType = ldb_msg_find_attr_as_uint(current_res->msgs[0],
824                                                  "instanceType", 0);
825         /* if the object has a parent, retrieve its SD to
826          * use for calculation */
827         if (!ldb_dn_is_null(current_res->msgs[0]->dn) &&
828             !(instanceType & INSTANCE_TYPE_IS_NC_HEAD)) {
829                 parent_dn = ldb_dn_get_parent(req, dn);
830                 if (parent_dn == NULL) {
831                         return ldb_oom(ldb);
832                 }
833                 ret = dsdb_module_search_dn(module, req, &parent_res, parent_dn,
834                                             parent_attrs,
835                                             DSDB_FLAG_NEXT_MODULE |
836                                             DSDB_FLAG_AS_SYSTEM |
837                                             DSDB_SEARCH_SHOW_RECYCLED,
838                                             req);
839                 if (ret != LDB_SUCCESS) {
840                         ldb_debug(ldb, LDB_DEBUG_ERROR, "descriptor_modify: Could not find SD for %s\n",
841                                   ldb_dn_get_linearized(parent_dn));
842                         return ret;
843                 }
844                 if (parent_res->count != 1) {
845                         return ldb_operr(ldb);
846                 }
847                 parent_sd = ldb_msg_find_ldb_val(parent_res->msgs[0], "nTSecurityDescriptor");
848         }
849
850         schema = dsdb_get_schema(ldb, req);
851
852         objectclass_element = ldb_msg_find_element(current_res->msgs[0], "objectClass");
853         if (objectclass_element == NULL) {
854                 return ldb_operr(ldb);
855         }
856
857         objectclass = dsdb_get_last_structural_class(schema,
858                                                      objectclass_element);
859         if (objectclass == NULL) {
860                 return ldb_operr(ldb);
861         }
862
863         old_sd = ldb_msg_find_ldb_val(current_res->msgs[0], "nTSecurityDescriptor");
864         if (old_sd == NULL) {
865                 return ldb_operr(ldb);
866         }
867
868         if (sd_propagation_control != NULL) {
869                 /*
870                  * This just triggers a recalculation of the
871                  * inherited aces.
872                  */
873                 user_sd = old_sd;
874         }
875
876         sd = get_new_descriptor(module, current_res->msgs[0]->dn, req,
877                                 objectclass, parent_sd,
878                                 user_sd, old_sd, sd_flags);
879         if (sd == NULL) {
880                 return ldb_operr(ldb);
881         }
882         msg = ldb_msg_copy_shallow(req, req->op.mod.message);
883         if (msg == NULL) {
884                 return ldb_oom(ldb);
885         }
886         cmp_ret = data_blob_cmp(old_sd, sd);
887         if (sd_propagation_control != NULL) {
888                 if (cmp_ret == 0) {
889                         /*
890                          * The nTSecurityDescriptor is unchanged,
891                          * which means we can stop the processing.
892                          *
893                          * We mark the control as critical again,
894                          * as we have not processed it, so the caller
895                          * can tell that the descriptor was unchanged.
896                          */
897                         sd_propagation_control->critical = 1;
898                         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
899                 }
900
901                 ret = ldb_msg_add_empty(msg, "nTSecurityDescriptor",
902                                         LDB_FLAG_MOD_REPLACE,
903                                         &sd_element);
904                 if (ret != LDB_SUCCESS) {
905                         return ldb_oom(ldb);
906                 }
907                 ret = ldb_msg_add_value(msg, "nTSecurityDescriptor",
908                                         sd, NULL);
909                 if (ret != LDB_SUCCESS) {
910                         return ldb_oom(ldb);
911                 }
912         } else if (cmp_ret != 0) {
913                 struct GUID guid;
914                 struct ldb_dn *nc_root;
915                 NTSTATUS status;
916
917                 ret = dsdb_find_nc_root(ldb,
918                                         msg,
919                                         current_res->msgs[0]->dn,
920                                         &nc_root);
921                 if (ret != LDB_SUCCESS) {
922                         return ldb_oom(ldb);
923                 }
924
925                 status = dsdb_get_extended_dn_guid(current_res->msgs[0]->dn,
926                                                    &guid,
927                                                    "GUID");
928                 if (!NT_STATUS_IS_OK(status)) {
929                         return ldb_operr(ldb);
930                 }
931
932                 /*
933                  * Force SD propagation on children of this record
934                  */
935                 ret = dsdb_module_schedule_sd_propagation(module,
936                                                           nc_root,
937                                                           guid,
938                                                           false);
939                 if (ret != LDB_SUCCESS) {
940                         return ldb_operr(ldb);
941                 }
942                 sd_element->values[0] = *sd;
943         } else {
944                 sd_element->values[0] = *sd;
945         }
946
947         ret = ldb_build_mod_req(&mod_req, ldb, req,
948                                 msg,
949                                 req->controls,
950                                 req,
951                                 dsdb_next_callback,
952                                 req);
953         LDB_REQ_SET_LOCATION(mod_req);
954         if (ret != LDB_SUCCESS) {
955                 return ret;
956         }
957
958         return ldb_next_request(module, mod_req);
959 }
960
961 static int descriptor_search(struct ldb_module *module, struct ldb_request *req)
962 {
963         int ret;
964         struct ldb_context *ldb;
965         struct ldb_request *down_req;
966         struct descriptor_context *ac;
967         bool explicit_sd_flags = false;
968         uint32_t sd_flags = dsdb_request_sd_flags(req, &explicit_sd_flags);
969         bool show_sd = explicit_sd_flags;
970
971         if (!show_sd &&
972             ldb_attr_in_list(req->op.search.attrs, "nTSecurityDescriptor"))
973         {
974                 show_sd = true;
975         }
976
977         if (!show_sd) {
978                 return ldb_next_request(module, req);
979         }
980
981         ldb = ldb_module_get_ctx(module);
982         ac = descriptor_init_context(module, req);
983         if (ac == NULL) {
984                 return ldb_operr(ldb);
985         }
986         ac->sd_flags = sd_flags;
987
988         ret = ldb_build_search_req_ex(&down_req, ldb, ac,
989                                       req->op.search.base,
990                                       req->op.search.scope,
991                                       req->op.search.tree,
992                                       req->op.search.attrs,
993                                       req->controls,
994                                       ac, descriptor_search_callback,
995                                       ac->req);
996         LDB_REQ_SET_LOCATION(down_req);
997         if (ret != LDB_SUCCESS) {
998                 return ret;
999         }
1000
1001         return ldb_next_request(ac->module, down_req);
1002 }
1003
1004 static int descriptor_rename(struct ldb_module *module, struct ldb_request *req)
1005 {
1006         struct ldb_context *ldb = ldb_module_get_ctx(module);
1007         struct ldb_dn *olddn = req->op.rename.olddn;
1008         struct ldb_dn *newdn = req->op.rename.newdn;
1009         int ret;
1010
1011         /* do not manipulate our control entries */
1012         if (ldb_dn_is_special(req->op.rename.olddn)) {
1013                 return ldb_next_request(module, req);
1014         }
1015
1016         ldb_debug(ldb, LDB_DEBUG_TRACE,"descriptor_rename: %s\n",
1017                   ldb_dn_get_linearized(olddn));
1018
1019         if (ldb_dn_compare(olddn, newdn) != 0) {
1020                 struct ldb_dn *nc_root;
1021                 struct GUID guid;
1022
1023                 ret = dsdb_find_nc_root(ldb, req, newdn, &nc_root);
1024                 if (ret != LDB_SUCCESS) {
1025                         return ldb_oom(ldb);
1026                 }
1027
1028                 ret = dsdb_module_guid_by_dn(module,
1029                                              olddn,
1030                                              &guid,
1031                                              req);
1032                 if (ret == LDB_SUCCESS) {
1033                         /*
1034                          * Without disturbing any errors if the olddn
1035                          * does not exit, force SD propagation on
1036                          * this record (get a new inherited SD from
1037                          * the potentially new parent
1038                          */
1039                         ret = dsdb_module_schedule_sd_propagation(module,
1040                                                                   nc_root,
1041                                                                   guid,
1042                                                                   true);
1043                         if (ret != LDB_SUCCESS) {
1044                                 return ldb_operr(ldb);
1045                         }
1046                 }
1047         }
1048
1049         return ldb_next_request(module, req);
1050 }
1051
1052 static void descriptor_changes_parser(TDB_DATA key, TDB_DATA data, void *private_data)
1053 {
1054         struct descriptor_changes **c_ptr = (struct descriptor_changes **)private_data;
1055         uintptr_t ptr = 0;
1056
1057         SMB_ASSERT(data.dsize == sizeof(ptr));
1058
1059         memcpy(&ptr, data.dptr, data.dsize);
1060
1061         *c_ptr = talloc_get_type_abort((void *)ptr, struct descriptor_changes);
1062 }
1063
1064 static int descriptor_extended_sec_desc_propagation(struct ldb_module *module,
1065                                                     struct ldb_request *req)
1066 {
1067         struct descriptor_data *descriptor_private =
1068                 talloc_get_type_abort(ldb_module_get_private(module),
1069                 struct descriptor_data);
1070         struct descriptor_transaction *t = &descriptor_private->transaction;
1071         struct ldb_context *ldb = ldb_module_get_ctx(module);
1072         struct dsdb_extended_sec_desc_propagation_op *op;
1073         struct descriptor_changes *c = NULL;
1074         TDB_DATA key;
1075         NTSTATUS status;
1076
1077         op = talloc_get_type(req->op.extended.data,
1078                              struct dsdb_extended_sec_desc_propagation_op);
1079         if (op == NULL) {
1080                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1081                           "descriptor_extended_sec_desc_propagation: "
1082                           "invalid extended data\n");
1083                 return LDB_ERR_PROTOCOL_ERROR;
1084         }
1085
1086         if (t->mem == NULL) {
1087                 return ldb_module_operr(module);
1088         }
1089
1090         /*
1091          * First we check if we already have an registration
1092          * for the given object.
1093          */
1094
1095         key = make_tdb_data((const void*)&op->guid, sizeof(op->guid));
1096         status = dbwrap_parse_record(t->changes.map, key,
1097                                      descriptor_changes_parser, &c);
1098         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1099                 c = NULL;
1100                 status = NT_STATUS_OK;
1101         }
1102         if (!NT_STATUS_IS_OK(status)) {
1103                 ldb_debug(ldb, LDB_DEBUG_FATAL,
1104                           "dbwrap_parse_record() - %s\n",
1105                           nt_errstr(status));
1106                 return ldb_module_operr(module);
1107         }
1108
1109         if (c == NULL) {
1110                 /*
1111                  * Create a new structure if we
1112                  * don't know about the object yet.
1113                  */
1114
1115                 c = talloc_zero(t->mem, struct descriptor_changes);
1116                 if (c == NULL) {
1117                         return ldb_module_oom(module);
1118                 }
1119                 c->nc_root = ldb_dn_copy(c, op->nc_root);
1120                 if (c->nc_root == NULL) {
1121                         return ldb_module_oom(module);
1122                 }
1123                 c->guid = op->guid;
1124         }
1125
1126         if (ldb_dn_compare(c->nc_root, op->nc_root) != 0) {
1127                 /*
1128                  * This is an unexpected situation,
1129                  * we don't expect the nc root to change
1130                  * during a replication cycle.
1131                  */
1132                 DBG_ERR("ERROR: Object %s nc_root changed %s => %s\n",
1133                         GUID_string(c, &c->guid),
1134                         ldb_dn_get_extended_linearized(c, c->nc_root, 1),
1135                         ldb_dn_get_extended_linearized(c, op->nc_root, 1));
1136                 return ldb_module_operr(module);
1137         }
1138
1139         c->ref_count += 1;
1140
1141         /*
1142          * Note that we only set, but don't clear values here,
1143          * it means c->force_self and c->force_children can
1144          * both be true in the end.
1145          */
1146         if (op->include_self) {
1147                 c->force_self = true;
1148         } else {
1149                 c->force_children = true;
1150         }
1151
1152         if (c->ref_count == 1) {
1153                 struct TDB_DATA val = make_tdb_data((const void*)&c, sizeof(c));
1154
1155                 /*
1156                  * Remember the change by objectGUID in order
1157                  * to avoid processing it more than once.
1158                  */
1159
1160                 status = dbwrap_store(t->changes.map, key, val, TDB_INSERT);
1161                 if (!NT_STATUS_IS_OK(status)) {
1162                         ldb_debug(ldb, LDB_DEBUG_FATAL,
1163                                   "dbwrap_parse_record() - %s\n",
1164                                   nt_errstr(status));
1165                         return ldb_module_operr(module);
1166                 }
1167
1168                 DLIST_ADD_END(t->changes.list, c);
1169                 t->changes.num_registered += 1;
1170         }
1171         t->changes.num_registrations += 1;
1172
1173         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
1174 }
1175
1176 static int descriptor_extended(struct ldb_module *module, struct ldb_request *req)
1177 {
1178         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_SEC_DESC_PROPAGATION_OID) == 0) {
1179                 return descriptor_extended_sec_desc_propagation(module, req);
1180         }
1181
1182         return ldb_next_request(module, req);
1183 }
1184
1185 static int descriptor_init(struct ldb_module *module)
1186 {
1187         struct ldb_context *ldb = ldb_module_get_ctx(module);
1188         int ret;
1189         struct descriptor_data *descriptor_private;
1190
1191         ret = ldb_mod_register_control(module, LDB_CONTROL_SD_FLAGS_OID);
1192         if (ret != LDB_SUCCESS) {
1193                 ldb_debug(ldb, LDB_DEBUG_ERROR,
1194                         "descriptor: Unable to register control with rootdse!\n");
1195                 return ldb_operr(ldb);
1196         }
1197
1198         descriptor_private = talloc_zero(module, struct descriptor_data);
1199         if (descriptor_private == NULL) {
1200                 ldb_oom(ldb);
1201                 return LDB_ERR_OPERATIONS_ERROR;
1202         }
1203         ldb_module_set_private(module, descriptor_private);
1204
1205         return ldb_next_init(module);
1206 }
1207
1208 static int descriptor_sd_propagation_object(struct ldb_module *module,
1209                                             struct ldb_message *msg,
1210                                             bool *stop)
1211 {
1212         struct descriptor_data *descriptor_private =
1213                 talloc_get_type_abort(ldb_module_get_private(module),
1214                 struct descriptor_data);
1215         struct descriptor_transaction *t = &descriptor_private->transaction;
1216         struct ldb_context *ldb = ldb_module_get_ctx(module);
1217         struct ldb_request *sub_req;
1218         struct ldb_result *mod_res;
1219         struct ldb_control *sd_propagation_control;
1220         int ret;
1221
1222         *stop = false;
1223
1224         t->objects.num_processed += 1;
1225
1226         mod_res = talloc_zero(msg, struct ldb_result);
1227         if (mod_res == NULL) {
1228                 return ldb_module_oom(module);
1229         }
1230
1231         ret = ldb_build_mod_req(&sub_req, ldb, mod_res,
1232                                 msg,
1233                                 NULL,
1234                                 mod_res,
1235                                 ldb_modify_default_callback,
1236                                 NULL);
1237         LDB_REQ_SET_LOCATION(sub_req);
1238         if (ret != LDB_SUCCESS) {
1239                 return ldb_module_operr(module);
1240         }
1241
1242         ldb_req_mark_trusted(sub_req);
1243
1244         ret = ldb_request_add_control(sub_req,
1245                                       DSDB_CONTROL_SEC_DESC_PROPAGATION_OID,
1246                                       true, module);
1247         if (ret != LDB_SUCCESS) {
1248                 return ldb_module_operr(module);
1249         }
1250
1251         sd_propagation_control = ldb_request_get_control(sub_req,
1252                                         DSDB_CONTROL_SEC_DESC_PROPAGATION_OID);
1253         if (sd_propagation_control == NULL) {
1254                 return ldb_module_operr(module);
1255         }
1256
1257         ret = dsdb_request_add_controls(sub_req,
1258                                         DSDB_FLAG_AS_SYSTEM |
1259                                         DSDB_SEARCH_SHOW_RECYCLED);
1260         if (ret != LDB_SUCCESS) {
1261                 return ldb_module_operr(module);
1262         }
1263
1264         ret = descriptor_modify(module, sub_req);
1265         if (ret == LDB_SUCCESS) {
1266                 ret = ldb_wait(sub_req->handle, LDB_WAIT_ALL);
1267         }
1268         if (ret != LDB_SUCCESS) {
1269                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1270                                        "descriptor_modify on %s failed: %s",
1271                                        ldb_dn_get_linearized(msg->dn),
1272                                        ldb_errstring(ldb_module_get_ctx(module)));
1273                 return LDB_ERR_OPERATIONS_ERROR;
1274         }
1275
1276         if (sd_propagation_control->critical != 0) {
1277                 *stop = true;
1278         }
1279
1280         talloc_free(mod_res);
1281
1282         return LDB_SUCCESS;
1283 }
1284
1285 static int descriptor_sd_propagation_msg_sort(struct ldb_message **m1,
1286                                               struct ldb_message **m2)
1287 {
1288         struct ldb_dn *dn1 = (*m1)->dn;
1289         struct ldb_dn *dn2 = (*m2)->dn;
1290
1291         /*
1292          * This sorts in tree order, parents first
1293          */
1294         return ldb_dn_compare(dn2, dn1);
1295 }
1296
1297 static int descriptor_sd_propagation_recursive(struct ldb_module *module,
1298                                                struct descriptor_changes *change)
1299 {
1300         struct descriptor_data *descriptor_private =
1301                 talloc_get_type_abort(ldb_module_get_private(module),
1302                 struct descriptor_data);
1303         struct descriptor_transaction *t = &descriptor_private->transaction;
1304         struct ldb_result *guid_res = NULL;
1305         struct ldb_result *res = NULL;
1306         unsigned int i;
1307         const char * const no_attrs[] = { "@__NONE__", NULL };
1308         struct ldb_dn *stopped_dn = NULL;
1309         struct GUID_txt_buf guid_buf;
1310         int ret;
1311         bool stop = false;
1312
1313         t->changes.num_processed += 1;
1314
1315         /*
1316          * First confirm this object has children, or exists
1317          * (depending on change->force_self)
1318          * 
1319          * LDB_SCOPE_SUBTREE searches are expensive.
1320          *
1321          * We know this is safe against a rename race as we are in the
1322          * prepare_commit(), so must be in a transaction.
1323          */
1324
1325         /* Find the DN by GUID, as this is stable under rename */
1326         ret = dsdb_module_search(module,
1327                                  change,
1328                                  &guid_res,
1329                                  change->nc_root,
1330                                  LDB_SCOPE_SUBTREE,
1331                                  no_attrs,
1332                                  DSDB_FLAG_NEXT_MODULE |
1333                                  DSDB_FLAG_AS_SYSTEM |
1334                                  DSDB_SEARCH_SHOW_DELETED |
1335                                  DSDB_SEARCH_SHOW_RECYCLED,
1336                                  NULL, /* parent_req */
1337                                  "(objectGUID=%s)",
1338                                  GUID_buf_string(&change->guid,
1339                                                  &guid_buf));
1340
1341         if (ret != LDB_SUCCESS) {
1342                 return ret;
1343         }
1344
1345         if (guid_res->count != 1) {
1346                 /*
1347                  * We were just given this GUID during the same
1348                  * transaction, if it is missing this is a big
1349                  * problem.
1350                  *
1351                  * Cleanup of tombstones does not trigger this module
1352                  * as it just does a delete.
1353                  */
1354                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1355                                        "failed to find GUID %s under %s "
1356                                        "for transaction-end SD inheritance: %d results",
1357                                        GUID_buf_string(&change->guid,
1358                                                        &guid_buf),
1359                                        ldb_dn_get_linearized(change->nc_root),
1360                                        guid_res->count);
1361                 return LDB_ERR_OPERATIONS_ERROR;
1362         }
1363
1364         /*
1365          * OK, so there was a parent, are there children?  Note: that
1366          * this time we do not search for deleted/recycled objects
1367          */
1368         ret = dsdb_module_search(module,
1369                                  change,
1370                                  &res,
1371                                  guid_res->msgs[0]->dn,
1372                                  LDB_SCOPE_ONELEVEL,
1373                                  no_attrs,
1374                                  DSDB_FLAG_NEXT_MODULE |
1375                                  DSDB_FLAG_AS_SYSTEM,
1376                                  NULL, /* parent_req */
1377                                  "(objectClass=*)");
1378         if (ret != LDB_SUCCESS) {
1379                 /*
1380                  * LDB_ERR_NO_SUCH_OBJECT, say if the DN was a deleted
1381                  * object, is ignored by the caller
1382                  */
1383                 return ret;
1384         }
1385
1386         if (res->count == 0 && !change->force_self) {
1387                 /* All done, no children */
1388                 TALLOC_FREE(res);
1389                 return LDB_SUCCESS;
1390         }
1391
1392         /*
1393          * First, if we are in force_self mode (eg renamed under new
1394          * parent) then apply the SD to the top object
1395          */
1396         if (change->force_self) {
1397                 ret = descriptor_sd_propagation_object(module,
1398                                                        guid_res->msgs[0],
1399                                                        &stop);
1400                 if (ret != LDB_SUCCESS) {
1401                         TALLOC_FREE(guid_res);
1402                         return ret;
1403                 }
1404
1405                 if (stop == true && !change->force_children) {
1406                         /* There was no change, nothing more to do */
1407                         TALLOC_FREE(guid_res);
1408                         return LDB_SUCCESS;
1409                 }
1410
1411                 if (res->count == 0) {
1412                         /* All done! */
1413                         TALLOC_FREE(guid_res);
1414                         return LDB_SUCCESS;
1415                 }
1416         }
1417
1418         /*
1419          * Look for children
1420          *
1421          * Note: that we do not search for deleted/recycled objects
1422          */
1423         ret = dsdb_module_search(module,
1424                                  change,
1425                                  &res,
1426                                  guid_res->msgs[0]->dn,
1427                                  LDB_SCOPE_SUBTREE,
1428                                  no_attrs,
1429                                  DSDB_FLAG_NEXT_MODULE |
1430                                  DSDB_FLAG_AS_SYSTEM,
1431                                  NULL, /* parent_req */
1432                                  "(objectClass=*)");
1433         if (ret != LDB_SUCCESS) {
1434                 return ret;
1435         }
1436
1437         TYPESAFE_QSORT(res->msgs, res->count,
1438                        descriptor_sd_propagation_msg_sort);
1439
1440         /* We start from 1, the top object has been done */
1441         for (i = 1; i < res->count; i++) {
1442                 /*
1443                  * ldb_dn_compare_base() does not match for NULL but
1444                  * this is clearer
1445                  */
1446                 if (stopped_dn != NULL) {
1447                         ret = ldb_dn_compare_base(stopped_dn,
1448                                                   res->msgs[i]->dn);
1449                         /*
1450                          * Skip further processing of this
1451                          * sub-subtree
1452                          */
1453                         if (ret == 0) {
1454                                 continue;
1455                         }
1456                 }
1457                 ret = descriptor_sd_propagation_object(module,
1458                                                        res->msgs[i],
1459                                                        &stop);
1460                 if (ret != LDB_SUCCESS) {
1461                         return ret;
1462                 }
1463
1464                 if (stop) {
1465                         /*
1466                          * If this child didn't change, then nothing
1467                          * under it needs to change
1468                          *
1469                          * res has been sorted into tree order so the
1470                          * next few entries can be skipped
1471                          */
1472                         stopped_dn = res->msgs[i]->dn;
1473                 }
1474         }
1475
1476         TALLOC_FREE(res);
1477         return LDB_SUCCESS;
1478 }
1479
1480 static int descriptor_start_transaction(struct ldb_module *module)
1481 {
1482         struct descriptor_data *descriptor_private =
1483                 talloc_get_type_abort(ldb_module_get_private(module),
1484                 struct descriptor_data);
1485         struct descriptor_transaction *t = &descriptor_private->transaction;
1486
1487         if (t->mem != NULL) {
1488                 return ldb_module_operr(module);
1489         }
1490
1491         *t = (struct descriptor_transaction) { .mem = NULL, };
1492         t->mem = talloc_new(descriptor_private);
1493         if (t->mem == NULL) {
1494                 return ldb_module_oom(module);
1495         }
1496         t->changes.map = db_open_rbt(t->mem);
1497         if (t->changes.map == NULL) {
1498                 TALLOC_FREE(t->mem);
1499                 *t = (struct descriptor_transaction) { .mem = NULL, };
1500                 return ldb_module_oom(module);
1501         }
1502
1503         return ldb_next_start_trans(module);
1504 }
1505
1506 static int descriptor_prepare_commit(struct ldb_module *module)
1507 {
1508         struct descriptor_data *descriptor_private =
1509                 talloc_get_type_abort(ldb_module_get_private(module),
1510                 struct descriptor_data);
1511         struct descriptor_transaction *t = &descriptor_private->transaction;
1512         struct descriptor_changes *c, *n;
1513         int ret;
1514
1515         DBG_NOTICE("changes: num_registrations=%zu\n",
1516                    t->changes.num_registrations);
1517         DBG_NOTICE("changes: num_registered=%zu\n",
1518                    t->changes.num_registered);
1519
1520         for (c = t->changes.list; c; c = n) {
1521                 n = c->next;
1522
1523                 DLIST_REMOVE(t->changes.list, c);
1524
1525                 ret = descriptor_sd_propagation_recursive(module, c);
1526                 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1527                         continue;
1528                 }
1529                 if (ret != LDB_SUCCESS) {
1530                         return ret;
1531                 }
1532         }
1533
1534         DBG_NOTICE("changes: num_processed=%zu\n", t->changes.num_processed);
1535         DBG_NOTICE("objects: num_processed=%zu\n", t->objects.num_processed);
1536
1537         return ldb_next_prepare_commit(module);
1538 }
1539
1540 static int descriptor_end_transaction(struct ldb_module *module)
1541 {
1542         struct descriptor_data *descriptor_private =
1543                 talloc_get_type_abort(ldb_module_get_private(module),
1544                 struct descriptor_data);
1545         struct descriptor_transaction *t = &descriptor_private->transaction;
1546
1547         TALLOC_FREE(t->mem);
1548         *t = (struct descriptor_transaction) { .mem = NULL, };
1549
1550         return ldb_next_end_trans(module);
1551 }
1552
1553 static int descriptor_del_transaction(struct ldb_module *module)
1554 {
1555         struct descriptor_data *descriptor_private =
1556                 talloc_get_type_abort(ldb_module_get_private(module),
1557                 struct descriptor_data);
1558         struct descriptor_transaction *t = &descriptor_private->transaction;
1559
1560         TALLOC_FREE(t->mem);
1561         *t = (struct descriptor_transaction) { .mem = NULL, };
1562
1563         return ldb_next_del_trans(module);
1564 }
1565
1566 static const struct ldb_module_ops ldb_descriptor_module_ops = {
1567         .name              = "descriptor",
1568         .search            = descriptor_search,
1569         .add               = descriptor_add,
1570         .modify            = descriptor_modify,
1571         .rename            = descriptor_rename,
1572         .init_context      = descriptor_init,
1573         .extended          = descriptor_extended,
1574         .start_transaction = descriptor_start_transaction,
1575         .prepare_commit    = descriptor_prepare_commit,
1576         .end_transaction   = descriptor_end_transaction,
1577         .del_transaction   = descriptor_del_transaction,
1578 };
1579
1580 int ldb_descriptor_module_init(const char *version)
1581 {
1582         LDB_MODULE_CHECK_VERSION(version);
1583         return ldb_register_module(&ldb_descriptor_module_ops);
1584 }