4 Copyright (C) Matthieu Patou <mat@matws.net> 2011
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "ldb/include/ldb.h"
23 #include "ldb/include/ldb_errors.h"
24 #include "ldb/include/ldb_module.h"
25 #include "libcli/security/security.h"
26 #include "librpc/gen_ndr/drsblobs.h"
27 #include "librpc/gen_ndr/ndr_drsblobs.h"
28 #include "librpc/ndr/libndr.h"
29 #include "dsdb/samdb/samdb.h"
30 #include "dsdb/samdb/ldb_modules/util.h"
31 #include "lib/util/smb_strtox.h"
33 #define LDAP_DIRSYNC_OBJECT_SECURITY 0x01
34 #define LDAP_DIRSYNC_ANCESTORS_FIRST_ORDER 0x800
35 #define LDAP_DIRSYNC_PUBLIC_DATA_ONLY 0x2000
36 #define LDAP_DIRSYNC_INCREMENTAL_VALUES 0x80000000
39 struct dirsync_context {
40 struct ldb_module *module;
41 struct ldb_request *req;
44 * We keep a track of the number of attributes that we
45 * add just for the need of the implementation
46 * it will be useful to track the entries that need not to
47 * be returned because there is no real change
50 unsigned int nbDefaultAttrs;
60 const struct GUID *our_invocation_id;
61 const struct dsdb_schema *schema;
62 struct ldb_dn *nc_root;
63 struct drsuapi_DsReplicaCursor *cursors;
67 static int dirsync_filter_entry(struct ldb_request *req,
68 struct ldb_message *msg,
69 struct ldb_control **controls,
70 struct dirsync_context *dsc,
73 struct ldb_context *ldb;
75 enum ndr_err_code ndr_err;
79 struct ldb_val *replMetaData = NULL;
80 struct replPropertyMetaDataBlob rmd;
81 const struct dsdb_attribute *attr;
82 const char **listAttr = NULL;
83 bool namereturned = false;
84 bool nameasked = false;
86 /* Adjustment for the added attributes, it will reduce the number of
87 * expected to be here attributes*/
88 unsigned int delta = 0;
89 const char **myaccept = NULL;
90 const char *emptyaccept[] = { NULL };
91 const char *extendedaccept[] = { "GUID", "SID", "WKGUID", NULL };
92 const char *rdn = NULL;
93 struct ldb_message_element *el;
94 struct ldb_message *newmsg;
97 * Where we asked to do extended dn ?
98 * if so filter out everything bug GUID, SID, WKGUID,
99 * if not filter out everything (just keep the dn).
101 if ( dsc->noextended == true ) {
102 myaccept = emptyaccept;
104 myaccept = extendedaccept;
106 ldb = ldb_module_get_ctx(dsc->module);
108 if (msg->num_elements == 0) {
110 * Entry that we don't really have access to
114 ldb_dn_extended_filter(msg->dn, myaccept);
117 * If the RDN starts with CN then the CN attribute is never returned
119 rdn = ldb_dn_get_rdn_name(msg->dn);
122 * if objectGUID is asked and we are dealing for the referrals entries and
123 * the usn searched is 0 then we didn't count the objectGUID as an automatically
124 * returned attribute, do to so we increment delta.
126 if (referral == true &&
127 ldb_attr_in_list(req->op.search.attrs, "objectGUID") &&
128 dsc->fromreqUSN == 0) {
134 * In terms of big O notation this is not the best algorithm,
135 * but we try our best not to make the worse one.
136 * We are obliged to run through the n message's elements
137 * and through the p elements of the replPropertyMetaData.
139 * It turns out that we are crawling twice the message's elements
140 * the first crawl is to remove the non replicated and generated
141 * attributes. The second one is to remove attributes that haven't
142 * a USN > as the requested one.
144 * In the second crawl we are reading the list of elements in the
145 * replPropertyMetaData for each remaining replicated attribute.
146 * In order to keep the list small
148 * We have a O(n'*p') complexity, in worse case n' = n and p' = p
149 * but in most case n' = n/2 (at least half of returned attributes
150 * are not replicated or generated) and p' is small as we
151 * list only the attribute that have been modified since last interrogation
154 for (i = msg->num_elements - 1; i >= 0; i--) {
155 if (ldb_attr_cmp(msg->elements[i].name, "uSNChanged") == 0) {
157 /* Read the USN it will be used at the end of the filtering
158 * to update the max USN in the cookie if we
159 * decide to keep this entry
162 (const char*)msg->elements[i].values[0].data,
168 ldb_set_errstring(ldb,
169 "Failed to convert USN");
170 return ldb_module_done(dsc->req,
173 LDB_ERR_OPERATIONS_ERROR);
178 if (ldb_attr_cmp(msg->elements[i].name,
179 "replPropertyMetaData") == 0) {
180 replMetaData = (talloc_steal(dsc, &msg->elements[i].values[0]));
185 if (replMetaData == NULL) {
186 bool guidfound = false;
189 * We are in the case of deleted object where we don't have the
192 if (!ldb_msg_find_attr_as_uint(msg, "isDeleted", 0)) {
194 * This is not a deleted item and we don't
195 * have the replPropertyMetaData.
200 el = ldb_msg_find_element(msg, "objectGUID");
205 * We expect to find the GUID in the object,
206 * if it turns out not to be the case sometimes
207 * we will uncomment the code below
209 SMB_ASSERT(guidfound == true);
210 return ldb_module_send_entry(dsc->req, msg, controls);
213 newmsg = ldb_msg_new(dsc->req);
214 if (newmsg == NULL) {
218 ndr_err = ndr_pull_struct_blob(replMetaData, dsc, &rmd,
219 (ndr_pull_flags_fn_t)ndr_pull_replPropertyMetaDataBlob);
220 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
221 ldb_set_errstring(ldb, "Unable to unmarshall replPropertyMetaData");
222 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
224 if (ldb_attr_in_list(req->op.search.attrs, "name") ||
225 ldb_attr_in_list(req->op.search.attrs, "*")) {
230 * If we don't have an USN and no uptodateness array then we skip the
231 * test phase this is an optimisation for the case when you
232 * first query the DC without a cookie.
233 * As this query is most probably the one
234 * that will return the biggest answer, skipping this part
235 * will really save time.
237 if (ldb_dn_compare(dsc->nc_root, msg->dn) == 0) {
238 /* If we have name then we expect to have parentGUID,
239 * it will not be the case for the root of the NC
244 if (dsc->fromreqUSN > 0 || dsc->cursors != NULL) {
247 * Allocate an array of size(replMetaData) of char*
248 * we know that it will be oversized but it's a short lived element
250 listAttr = talloc_array(msg, const char*, rmd.ctr.ctr1.count + 1);
251 if (listAttr == NULL) {
254 for (n=0; n < rmd.ctr.ctr1.count; n++) {
255 struct replPropertyMetaData1 *omd = &rmd.ctr.ctr1.array[n];
256 if (omd->local_usn > dsc->fromreqUSN) {
257 const struct dsdb_attribute *a = dsdb_attribute_by_attributeID_id(dsc->schema,
259 if (!dsc->localonly) {
260 struct drsuapi_DsReplicaCursor *tab = dsc->cursors;
262 for (l=0; l < dsc->cursor_size; l++) {
263 if (GUID_equal(&tab[l].source_dsa_invocation_id, &omd->originating_invocation_id) &&
264 tab[l].highest_usn >= omd->originating_usn) {
266 * If we have in the uptodateness vector an entry
267 * with the same invocation id as the originating invocation
268 * and if the usn in the vector is greater or equal to
269 * the one in originating_usn, then it means that this entry
270 * has already been sent (from another DC) to the client
271 * no need to resend it one more time.
276 /* If we are here it's because we have a usn > (max(usn of vectors))*/
278 if (namereturned == false &&
280 ldb_attr_cmp(a->lDAPDisplayName, "name") == 0) {
282 if (ldb_dn_compare(dsc->nc_root, msg->dn) == 0) {
286 listAttr[j] = a->lDAPDisplayName;
295 if (ldb_attr_in_list(req->op.search.attrs, "*") ||
296 ldb_attr_in_list(req->op.search.attrs, "name")) {
303 * Let's loop around the remaining elements
304 * to see which one are in the listAttr.
305 * If they are in this array it means that
306 * their localusn > usn from the request (in the cookie)
307 * if not we remove the attribute.
309 for (i = msg->num_elements - 1; i >= 0; i--) {
310 const char *ldapattrname;
312 el = &(msg->elements[i]);
313 ldapattrname = el->name;
315 attr = dsdb_attribute_by_lDAPDisplayName(dsc->schema,
323 if (attr->linkID & 1) {
325 * Attribute is a backlink so let's remove it
330 if (ldb_attr_cmp(msg->elements[i].name,
331 "replPropertyMetaData") == 0) {
335 if ((attr->systemFlags & (DS_FLAG_ATTR_NOT_REPLICATED | DS_FLAG_ATTR_IS_CONSTRUCTED))) {
336 if (ldb_attr_cmp(attr->lDAPDisplayName, "objectGUID") != 0 &&
337 ldb_attr_cmp(attr->lDAPDisplayName, "parentGUID") != 0) {
339 * Attribute is constructed or not replicated, let's get rid of it
343 /* Let's keep the attribute that we forced to be added
344 * even if they are not in the replicationMetaData
345 * or are just generated
347 if (namereturned == false &&
348 (ldb_attr_cmp(attr->lDAPDisplayName, "parentGUID") == 0)) {
352 if (ldb_msg_add(newmsg, el, LDB_FLAG_MOD_ADD) != LDB_SUCCESS) {
353 return ldb_error(ldb,
354 LDB_ERR_OPERATIONS_ERROR,
355 "Unable to add attribute");
357 talloc_steal(newmsg->elements, el->name);
358 talloc_steal(newmsg->elements, el->values);
363 if (ldb_attr_cmp(msg->elements[i].name, rdn) == 0) {
365 * We have an attribute that is the same as the start of the RDN
366 * (ie. attribute CN with rdn CN=).
371 if (ldb_attr_cmp(attr->lDAPDisplayName, "instanceType") == 0) {
372 if (ldb_msg_add(newmsg, el, LDB_FLAG_MOD_ADD) != LDB_SUCCESS) {
373 return ldb_error(ldb,
374 LDB_ERR_OPERATIONS_ERROR,
375 "Unable to add attribute");
377 talloc_steal(newmsg->elements, el->name);
378 talloc_steal(newmsg->elements, el->values);
381 /* For links, when our functional level > windows 2000
382 * we use the RMD_LOCAL_USN information to decide whether
383 * we return the attribute or not.
384 * For windows 2000 this information is in the replPropertyMetaData
385 * so it will be handled like any other replicated attribute
388 if (dsc->functional_level > DS_DOMAIN_FUNCTION_2000 &&
389 attr->linkID != 0 ) {
392 * Elements for incremental changes on linked attributes
394 struct ldb_message_element *el_incr_add = NULL;
395 struct ldb_message_element *el_incr_del = NULL;
397 * Attribute is a forwardlink so let's remove it
400 for (k = el->num_values -1; k >= 0; k--) {
403 uint32_t tmp_usn = 0;
404 uint32_t tmp_usn2 = 0;
405 struct GUID invocation_id = GUID_zero();
406 struct dsdb_dn *dn = dsdb_dn_parse(msg, ldb, &el->values[k], attr->syntax->ldap_oid);
407 struct ldb_dn *copydn;
409 ldb_set_errstring(ldb, "Cannot parse DN");
410 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
413 copydn = ldb_dn_copy(msg, dn->dn);
414 if (copydn == NULL) {
418 status = dsdb_get_extended_dn_uint32(dn->dn, &tmp_usn, "RMD_LOCAL_USN");
419 if (!NT_STATUS_IS_OK(status)) {
421 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
423 status = dsdb_get_extended_dn_guid(dn->dn, &invocation_id, "RMD_INVOCID");
424 if (!NT_STATUS_IS_OK(status)) {
426 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
429 status = dsdb_get_extended_dn_uint32(dn->dn, &flags, "RMD_FLAGS");
430 if (!NT_STATUS_IS_OK(status)) {
432 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
435 status = dsdb_get_extended_dn_uint32(dn->dn, &tmp_usn2, "RMD_ORIGINATING_USN");
436 if (!NT_STATUS_IS_OK(status)) {
438 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
441 ldb_dn_extended_filter(dn->dn, myaccept);
442 dn_ln = dsdb_dn_get_extended_linearized(dn, dn,
447 ldb_set_errstring(ldb, "Cannot linearize dn");
448 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
451 talloc_free(el->values[k].data);
452 el->values[k].data = (uint8_t*)talloc_steal(el->values, dn_ln);
453 if (el->values[k].data == NULL) {
455 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
457 el->values[k].length = strlen(dn_ln);
460 if (tmp_usn > dsc->fromreqUSN) {
461 if (!dsc->localonly) {
462 struct drsuapi_DsReplicaCursor *tab = dsc->cursors;
465 for (l=0; l < dsc->cursor_size; l++) {
466 if (GUID_equal(&tab[l].source_dsa_invocation_id, &invocation_id) &&
467 tab[l].highest_usn >= tmp_usn2) {
469 * If we have in the uptodateness vector an entry
470 * with the same invocation id as the originating invocation
471 * and if the usn in the vector is greater or equal to
472 * the one in originating_usn, then it means that this entry
473 * has already been sent (from another DC) to the client
474 * no need to resend it one more time.
479 /* If we are here it's because we have a usn > (max(usn of vectors))*/
484 /* If we are here it's because the link is more recent than either any
485 * originating usn or local usn
488 if (dsc->linkIncrVal == true) {
489 struct ldb_message_element *tmpel;
490 if (flags & DSDB_RMD_FLAG_DELETED) {
491 /* We have to check that the inactive link still point to an existing object */
496 status = dsdb_get_extended_dn_guid(copydn, &guid, "GUID");
497 if (!NT_STATUS_IS_OK(status)) {
498 DEBUG(0,(__location__ " Unable to extract GUID in linked attribute '%s' in '%s'\n",
499 el->name, ldb_dn_get_linearized(copydn)));
500 return ldb_operr(ldb);
502 ret = dsdb_module_dn_by_guid(dsc->module, newmsg, &guid, &tdn, req);
503 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
504 DEBUG(2, (" Search of guid %s returned 0 objects, skipping it !\n",
505 GUID_string(newmsg, &guid)));
507 } else if (ret != LDB_SUCCESS) {
508 DEBUG(0, (__location__ " Search of guid %s failed with error code %d\n",
509 GUID_string(newmsg, &guid),
519 tmpel = talloc_zero(newmsg, struct ldb_message_element);
523 tmpel->values = talloc_array(tmpel, struct ldb_val, 1);
524 if (tmpel->values == NULL) {
527 if (flags & DSDB_RMD_FLAG_DELETED) {
528 tmpel->name = talloc_asprintf(tmpel,
533 tmpel->name = talloc_asprintf(tmpel,
537 if (tmpel->name == NULL) {
540 tmpel->num_values = 1;
542 tmpel->num_values += 1;
543 tmpel->values = talloc_realloc(tmpel,
547 if (tmpel->values == NULL) {
551 tmpel->values[tmpel->num_values -1].data =talloc_steal(tmpel->values, el->values[k].data);
552 tmpel->values[tmpel->num_values -1].length = el->values[k].length;
554 if (flags & DSDB_RMD_FLAG_DELETED) {
562 if (dsc->linkIncrVal == false) {
563 if (flags & DSDB_RMD_FLAG_DELETED) {
576 if (dsc->linkIncrVal == false) {
577 if (ldb_msg_add(newmsg, el, LDB_FLAG_MOD_ADD) != LDB_SUCCESS) {
578 return ldb_error(ldb,
579 LDB_ERR_OPERATIONS_ERROR,
580 "Unable to add attribute");
582 talloc_steal(newmsg->elements, el->name);
583 talloc_steal(newmsg->elements, el->values);
586 if (ldb_msg_add(newmsg, el_incr_del, LDB_FLAG_MOD_ADD))
587 return ldb_error(ldb,
588 LDB_ERR_OPERATIONS_ERROR,
589 "Unable to add attribute");
592 if (ldb_msg_add(newmsg, el_incr_add, LDB_FLAG_MOD_ADD))
593 return ldb_error(ldb,
594 LDB_ERR_OPERATIONS_ERROR,
595 "Unable to add attribute");
603 for (j=0; j<size; j++) {
605 * We mark attribute that has already been seen well
606 * as seen. So that after attribute that are still in
607 * listAttr are attributes that has been modified after
608 * the requested USN but not present in the attributes
609 * returned by the ldb search.
610 * That is to say attributes that have been removed
612 if (listAttr[j] && ldb_attr_cmp(listAttr[j], ldapattrname) == 0) {
623 if (ldb_msg_add(newmsg, el, LDB_FLAG_MOD_ADD) != LDB_SUCCESS) {
624 return ldb_error(ldb,
625 LDB_ERR_OPERATIONS_ERROR,
626 "Unable to add attribute");
628 talloc_steal(newmsg->elements, el->name);
629 talloc_steal(newmsg->elements, el->values);
633 talloc_steal(newmsg->elements, msg);
636 * Here we run through the list of attributes returned
637 * in the propertyMetaData.
638 * Entries of this list have usn > requested_usn,
639 * entries that are also present in the message have been
640 * replaced by NULL, so at this moment the list contains
641 * only elements that have a usn > requested_usn and that
642 * haven't been seen. It's attributes that were removed.
643 * We add them to the message like empty elements.
645 for (j=0; j<size; j++) {
647 ldb_attr_in_list(req->op.search.attrs, "*") ||
648 ldb_attr_in_list(req->op.search.attrs, listAttr[j])) &&
649 (ldb_attr_cmp(listAttr[j], rdn) != 0) &&
650 (ldb_attr_cmp(listAttr[j], "instanceType") != 0)) {
651 ldb_msg_add_empty(newmsg, listAttr[j], LDB_FLAG_MOD_DELETE, NULL);
654 talloc_free(listAttr);
656 if ((newmsg->num_elements - ( dsc->nbDefaultAttrs - delta)) > 0) {
658 * After cleaning attributes there is still some attributes that were not added just
659 * for the purpose of the control (objectGUID, instanceType, ...)
662 newmsg->dn = talloc_steal(newmsg, msg->dn);
663 if (val > dsc->highestUSN) {
664 dsc->highestUSN = val;
666 return ldb_module_send_entry(dsc->req, newmsg, controls);
674 static int dirsync_create_vector(struct ldb_request *req,
675 struct ldb_reply *ares,
676 struct dirsync_context *dsc,
677 struct ldapControlDirSyncCookie *cookie,
678 struct ldb_context *ldb)
680 struct ldb_result *resVector;
681 const char* attrVector[] = {"replUpToDateVector", NULL };
682 uint64_t highest_usn;
685 struct drsuapi_DsReplicaCursor *tab;
687 ret = ldb_sequence_number(ldb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
688 if (ret != LDB_SUCCESS) {
689 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR, "Unable to get highest USN from current NC");
692 /* If we have a full answer then the highest USN
693 * is not the highest USN from the result set but the
694 * highest of the naming context, unless the sequence is not updated yet.
696 if (highest_usn > dsc->highestUSN) {
697 dsc->highestUSN = highest_usn;
701 ret = dsdb_module_search_dn(dsc->module, dsc, &resVector,
704 DSDB_FLAG_NEXT_MODULE, req);
705 if (ret != LDB_SUCCESS) {
706 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
707 "Unable to get replUpToDateVector for current NC");
710 if (resVector->count != 0) {
713 struct ldb_message_element *el = ldb_msg_find_element(resVector->msgs[0], "replUpToDateVector");
715 enum ndr_err_code ndr_err;
716 struct replUpToDateVectorBlob utd;
717 blob.data = el->values[0].data;
718 blob.length = el->values[0].length;
719 ndr_err = ndr_pull_struct_blob(&blob, dsc, &utd,
720 (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
722 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
723 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
724 "Unable to pull replUpToDateVectorBlob structure");
728 count += utd.ctr.ctr2.count;
729 tab = talloc_array(cookie, struct drsuapi_DsReplicaCursor, count);
733 for (i=1; i < count; i++) {
734 memset(&tab[i], 0, sizeof(struct drsuapi_DsReplicaCursor));
735 tab[i].highest_usn = utd.ctr.ctr2.cursors[i-1].highest_usn;
736 tab[i].source_dsa_invocation_id = utd.ctr.ctr2.cursors[i-1].source_dsa_invocation_id;
739 tab = talloc_array(cookie, struct drsuapi_DsReplicaCursor, count);
746 * No replUpToDateVector ? it happens quite often (1 DC,
747 * other DCs didn't update ...
749 tab = talloc_array(cookie, struct drsuapi_DsReplicaCursor, count);
754 /* Our vector is always the first */
755 tab[0].highest_usn = dsc->highestUSN;
756 tab[0].source_dsa_invocation_id = *(dsc->our_invocation_id);
759 /* We have to add the uptodateness vector that we have*/
760 /* Version is always 1 in dirsync cookies */
761 cookie->blob.extra.uptodateness_vector.version = 1;
762 cookie->blob.extra.uptodateness_vector.reserved = 0;
763 cookie->blob.extra.uptodateness_vector.ctr.ctr1.count = count;
764 cookie->blob.extra.uptodateness_vector.ctr.ctr1.reserved = 0;
765 cookie->blob.extra.uptodateness_vector.ctr.ctr1.cursors = tab;
770 static int dirsync_search_callback(struct ldb_request *req, struct ldb_reply *ares)
773 struct dirsync_context *dsc;
774 struct ldb_result *res, *res2;
775 struct ldb_dirsync_control *control;
776 struct ldapControlDirSyncCookie *cookie;
777 struct ldb_context *ldb;
782 const char *attrs[] = { "objectGUID", NULL };
783 enum ndr_err_code ndr_err;
787 dsc = talloc_get_type_abort(req->context, struct dirsync_context);
788 ldb = ldb_module_get_ctx(dsc->module);
790 return ldb_module_done(dsc->req, NULL, NULL,
791 LDB_ERR_OPERATIONS_ERROR);
793 if (ares->error != LDB_SUCCESS) {
794 return ldb_module_done(dsc->req, ares->controls,
795 ares->response, ares->error);
798 switch (ares->type) {
799 case LDB_REPLY_ENTRY:
800 return dirsync_filter_entry(req, ares->message, ares->controls, dsc, false);
802 case LDB_REPLY_REFERRAL:
803 /* Skip the ldap(s):// so up to 8 chars,
804 * we don't care to be precise as the goal is to be in
805 * the name of DC, then we search the next '/'
806 * as it will be the last char before the DN of the referral
808 if (strncmp(ares->referral, "ldap://", 7) == 0) {
809 tmp = ares->referral + 7;
810 } else if (strncmp(ares->referral, "ldaps://", 8) == 0) {
811 tmp = ares->referral + 8;
813 return ldb_operr(ldb);
816 tmp = strchr(tmp, '/');
818 return ldb_operr(ldb);
822 dn = ldb_dn_new(dsc, ldb, tmp);
827 flags = DSDB_FLAG_NEXT_MODULE |
828 DSDB_SEARCH_SHOW_DELETED |
829 DSDB_SEARCH_SHOW_EXTENDED_DN;
831 ret = dsdb_module_search_tree(dsc->module, dsc, &res,
834 req->op.search.attrs,
837 if (ret != LDB_SUCCESS) {
842 if (res->count > 1) {
843 char *ldbmsg = talloc_asprintf(dn, "LDB returned more than result for dn: %s", tmp);
845 ldb_set_errstring(ldb, ldbmsg);
848 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
849 } else if (res->count == 0) {
850 /* if nothing is returned then it means that we don't
858 * Fetch the objectGUID of the root of current NC
860 ret = dsdb_module_search_dn(dsc->module, dsc, &res2,
863 DSDB_FLAG_NEXT_MODULE, req);
865 if (ret != LDB_SUCCESS) {
868 if (res2->msgs[0]->num_elements != 1) {
869 ldb_set_errstring(ldb,
870 "More than 1 attribute returned while looking for objectGUID");
871 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
874 val = res2->msgs[0]->elements[0].values;
875 ret = ldb_msg_add_value(res->msgs[0], "parentGUID", val, NULL);
877 * It *very* important to steal otherwise as val is in a subcontext
878 * related to res2, when the value will be one more time stolen
879 * it's elements[x].values that will be stolen, so it's important to
880 * recreate the context hierarchy as if it was done from a ldb_request
882 talloc_steal(res->msgs[0]->elements[0].values, val);
883 if (ret != LDB_SUCCESS) {
886 return dirsync_filter_entry(req, res->msgs[0], res->controls, dsc, true);
890 * Let's add our own control
893 control = talloc_zero(ares->controls, struct ldb_dirsync_control);
894 if (control == NULL) {
899 * When outputting flags is used to say more results.
900 * For the moment we didn't honour the size info */
905 * max_attribute is unused cf. 3.1.1.3.4.1.3 LDAP_SERVER_DIRSYNC_OID in MS-ADTS
908 control->max_attributes = 0;
909 cookie = talloc_zero(control, struct ldapControlDirSyncCookie);
910 if (cookie == NULL) {
915 ret = dirsync_create_vector(req, ares, dsc, cookie, ldb);
916 if (ret != LDB_SUCCESS) {
917 return ldb_module_done(dsc->req, NULL, NULL, ret);
921 unix_to_nt_time(&now, time(NULL));
922 cookie->blob.time = now;
923 cookie->blob.highwatermark.highest_usn = dsc->highestUSN;
924 cookie->blob.highwatermark.tmp_highest_usn = dsc->highestUSN;
925 cookie->blob.guid1 = *(dsc->our_invocation_id);
927 blob = talloc_zero(control, DATA_BLOB);
932 ndr_err = ndr_push_struct_blob(blob, blob, cookie,
933 (ndr_push_flags_fn_t)ndr_push_ldapControlDirSyncCookie);
935 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
936 ldb_set_errstring(ldb, "Can't marshall ldapControlDirSyncCookie struct");
937 return ldb_module_done(dsc->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
939 control->cookie = (char *)blob->data;
940 control->cookie_len = blob->length;
941 ldb_reply_add_control(ares, LDB_CONTROL_DIRSYNC_OID, true, control);
943 return ldb_module_done(dsc->req, ares->controls,
944 ares->response, LDB_SUCCESS);
950 static int dirsync_ldb_search(struct ldb_module *module, struct ldb_request *req)
952 struct ldb_control *control;
953 struct ldb_result *acl_res;
954 struct ldb_dirsync_control *dirsync_ctl;
955 struct ldb_control *extended = NULL;
956 struct ldb_request *down_req;
957 struct dirsync_context *dsc;
958 struct ldb_context *ldb;
959 struct ldb_parse_tree *new_tree = req->op.search.tree;
960 enum ndr_err_code ndr_err;
966 if (ldb_dn_is_special(req->op.search.base)) {
967 return ldb_next_request(module, req);
971 * check if there's a dirsync control
973 control = ldb_request_get_control(req, LDB_CONTROL_DIRSYNC_OID);
974 if (control == NULL) {
975 /* not found go on */
976 return ldb_next_request(module, req);
979 ldb = ldb_module_get_ctx(module);
981 * This control must always be critical otherwise we return PROTOCOL error
983 if (!control->critical) {
984 return ldb_operr(ldb);
987 dsc = talloc_zero(req, struct dirsync_context);
991 dsc->module = module;
993 dsc->nbDefaultAttrs = 0;
996 dirsync_ctl = talloc_get_type(control->data, struct ldb_dirsync_control);
997 if (dirsync_ctl == NULL) {
998 return ldb_error(ldb, LDB_ERR_PROTOCOL_ERROR, "No data in dirsync control");
1001 ret = dsdb_find_nc_root(ldb, dsc, req->op.search.base, &dsc->nc_root);
1002 if (ret != LDB_SUCCESS) {
1006 if (ldb_dn_compare(dsc->nc_root, req->op.search.base) != 0) {
1007 if (dirsync_ctl->flags & LDAP_DIRSYNC_OBJECT_SECURITY) {
1008 return ldb_error(ldb, LDB_ERR_UNWILLING_TO_PERFORM,
1009 "DN is not one of the naming context");
1012 return ldb_error(ldb, LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS,
1013 "dN is not one of the naming context");
1017 if (!(dirsync_ctl->flags & LDAP_DIRSYNC_OBJECT_SECURITY)) {
1018 struct dom_sid *sid;
1019 struct security_descriptor *sd = NULL;
1020 const char *acl_attrs[] = { "nTSecurityDescriptor", "objectSid", "objectClass", NULL };
1021 const struct dsdb_schema *schema = NULL;
1022 const struct dsdb_class *objectclass = NULL;
1024 * If we don't have the flag and if we have the "replicate directory change" granted
1025 * then we upgrade ourself to system to not be blocked by the acl
1027 /* FIXME we won't check the replicate directory change filtered attribute set
1028 * it should be done so that if attr is not empty then we check that the user
1029 * has also this right
1033 * First change to system to get the SD of the root of current NC
1034 * if we don't the acl_read will forbid us the right to read it ...
1036 ret = dsdb_module_search_dn(module, dsc, &acl_res,
1037 req->op.search.base,
1039 DSDB_FLAG_NEXT_MODULE|DSDB_FLAG_AS_SYSTEM, req);
1041 if (ret != LDB_SUCCESS) {
1045 sid = samdb_result_dom_sid(dsc, acl_res->msgs[0], "objectSid");
1046 /* sid can be null ... */
1047 ret = dsdb_get_sd_from_ldb_message(ldb_module_get_ctx(module), acl_res, acl_res->msgs[0], &sd);
1049 if (ret != LDB_SUCCESS) {
1052 schema = dsdb_get_schema(ldb, req);
1054 return LDB_ERR_OPERATIONS_ERROR;
1056 objectclass = dsdb_get_structural_oc_from_msg(schema, acl_res->msgs[0]);
1059 * While we never use the answer to this for access
1060 * control (after CVE-2023-4154), we return a
1061 * different error message depending on if the user
1062 * was granted GUID_DRS_GET_CHANGES to provide a closer
1063 * emulation and keep some tests passing.
1065 * (Samba's ACL logic is not well suited to redacting
1066 * only the secret and RODC filtered attributes).
1068 ret = acl_check_extended_right(dsc, module, req, objectclass,
1069 sd, acl_user_token(module),
1070 GUID_DRS_GET_CHANGES, SEC_ADS_CONTROL_ACCESS, sid);
1072 if (ret != LDB_SUCCESS) {
1075 talloc_free(acl_res);
1078 dsc->functional_level = dsdb_functional_level(ldb);
1080 if (req->op.search.attrs) {
1081 attrs = ldb_attr_list_copy(dsc, req->op.search.attrs);
1082 if (attrs == NULL) {
1083 return ldb_oom(ldb);
1086 * Check if we have only "dn" as attribute, if so then
1087 * treat as if "*" was requested
1089 if (attrs && attrs[0]) {
1090 if (ldb_attr_cmp(attrs[0], "dn") == 0 && !attrs[1]) {
1091 attrs = talloc_array(dsc, const char*, 2);
1092 if (attrs == NULL) {
1093 return ldb_oom(ldb);
1100 * When returning all the attributes return also the SD as
1103 if (ldb_attr_in_list(attrs, "*")) {
1104 struct ldb_sd_flags_control *sdctr = talloc_zero(dsc, struct ldb_sd_flags_control);
1105 sdctr->secinfo_flags = 0xF;
1106 ret = ldb_request_add_control(req, LDB_CONTROL_SD_FLAGS_OID, false, sdctr);
1107 if (ret != LDB_SUCCESS) {
1110 attrs = ldb_attr_list_copy_add(dsc, attrs, "parentGUID");
1111 if (attrs == NULL) {
1112 return ldb_oom(ldb);
1114 attrs = ldb_attr_list_copy_add(dsc, attrs, "replPropertyMetaData");
1115 if (attrs == NULL) {
1116 return ldb_oom(ldb);
1119 * When no attributes are asked we in any case expect at least 3 attributes:
1125 dsc->nbDefaultAttrs = 3;
1128 * We will need this two attributes in the callback
1130 attrs = ldb_attr_list_copy_add(dsc, attrs, "usnChanged");
1131 if (attrs == NULL) {
1132 return ldb_operr(ldb);
1134 attrs = ldb_attr_list_copy_add(dsc, attrs, "replPropertyMetaData");
1135 if (attrs == NULL) {
1136 return ldb_operr(ldb);
1139 if (!ldb_attr_in_list(attrs, "instanceType")) {
1140 attrs = ldb_attr_list_copy_add(dsc, attrs, "instanceType");
1141 if (attrs == NULL) {
1142 return ldb_operr(ldb);
1144 dsc->nbDefaultAttrs++;
1147 if (!ldb_attr_in_list(attrs, "objectGUID")) {
1148 attrs = ldb_attr_list_copy_add(dsc, attrs, "objectGUID");
1149 if (attrs == NULL) {
1150 return ldb_operr(ldb);
1154 * Always increment the number of asked attributes as we don't care if objectGUID was asked
1155 * or not for counting the number of "real" attributes returned.
1157 dsc->nbDefaultAttrs++;
1159 if (!ldb_attr_in_list(attrs, "parentGUID")) {
1160 attrs = ldb_attr_list_copy_add(dsc, attrs, "parentGUID");
1161 if (attrs == NULL) {
1162 return ldb_operr(ldb);
1165 dsc->nbDefaultAttrs++;
1169 struct ldb_sd_flags_control *sdctr = talloc_zero(dsc, struct ldb_sd_flags_control);
1170 sdctr->secinfo_flags = 0xF;
1171 ret = ldb_request_add_control(req, LDB_CONTROL_SD_FLAGS_OID, false, sdctr);
1172 attrs = talloc_array(dsc, const char*, 4);
1173 if (attrs == NULL) {
1174 return ldb_operr(ldb);
1177 attrs[1] = "parentGUID";
1178 attrs[2] = "replPropertyMetaData";
1180 if (ret != LDB_SUCCESS) {
1184 * When no attributes are asked we in anycase expect at least 3 attributes:
1190 dsc->nbDefaultAttrs = 3;
1193 /* check if there's an extended dn control */
1194 extended = ldb_request_get_control(req, LDB_CONTROL_EXTENDED_DN_OID);
1195 if (extended != NULL) {
1196 struct ldb_extended_dn_control *extended_ctrl = NULL;
1198 if (extended->data != NULL) {
1199 extended_ctrl = talloc_get_type(extended->data,
1200 struct ldb_extended_dn_control);
1202 if (extended_ctrl != NULL) {
1203 dsc->extended_type = extended_ctrl->type;
1206 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, false, NULL);
1207 if (ret != LDB_SUCCESS) {
1210 dsc->noextended = true;
1213 if (ldb_request_get_control(req, LDB_CONTROL_REVEAL_INTERNALS) == NULL) {
1214 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
1215 if (ret != LDB_SUCCESS) {
1220 if (ldb_request_get_control(req, LDB_CONTROL_SHOW_RECYCLED_OID) == NULL) {
1221 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
1222 if (ret != LDB_SUCCESS) {
1227 if (ldb_request_get_control(req, LDB_CONTROL_SHOW_DELETED_OID) == NULL) {
1228 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, false, NULL);
1229 if (ret != LDB_SUCCESS) {
1234 if (dirsync_ctl->flags & LDAP_DIRSYNC_INCREMENTAL_VALUES) {
1235 dsc->linkIncrVal = true;
1237 dsc->linkIncrVal = false;
1240 dsc->our_invocation_id = samdb_ntds_invocation_id(ldb);
1241 if (dsc->our_invocation_id == NULL) {
1242 return ldb_operr(ldb);
1245 if (dirsync_ctl->cookie_len > 0) {
1246 struct ldapControlDirSyncCookie cookie;
1248 blob.data = (uint8_t *)dirsync_ctl->cookie;
1249 blob.length = dirsync_ctl->cookie_len;
1250 ndr_err = ndr_pull_struct_blob(&blob, dsc, &cookie,
1251 (ndr_pull_flags_fn_t)ndr_pull_ldapControlDirSyncCookie);
1253 /* If we can't unmarshall the cookie into the correct structure we return
1254 * unsupported critical extension
1256 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1257 return ldb_error(ldb, LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION,
1258 "Unable to unmarshall cookie as a ldapControlDirSyncCookie structure");
1262 * Let's search for the max usn within the cookie
1264 if (GUID_equal(&(cookie.blob.guid1), dsc->our_invocation_id)) {
1266 * Ok, it's our invocation ID so we can treat the demand
1267 * Let's take the highest usn from (tmp)highest_usn
1269 dsc->fromreqUSN = cookie.blob.highwatermark.tmp_highest_usn;
1270 dsc->localonly = true;
1272 if (cookie.blob.highwatermark.highest_usn > cookie.blob.highwatermark.tmp_highest_usn) {
1273 dsc->fromreqUSN = cookie.blob.highwatermark.highest_usn;
1276 dsc->localonly = false;
1278 if (cookie.blob.extra_length > 0 &&
1279 cookie.blob.extra.uptodateness_vector.ctr.ctr1.count > 0) {
1280 struct drsuapi_DsReplicaCursor cursor;
1282 for (p=0; p < cookie.blob.extra.uptodateness_vector.ctr.ctr1.count; p++) {
1283 cursor = cookie.blob.extra.uptodateness_vector.ctr.ctr1.cursors[p];
1284 if (GUID_equal( &(cursor.source_dsa_invocation_id), dsc->our_invocation_id)) {
1285 if (cursor.highest_usn > dsc->fromreqUSN) {
1286 dsc->fromreqUSN = cursor.highest_usn;
1290 dsc->cursors = talloc_steal(dsc,
1291 cookie.blob.extra.uptodateness_vector.ctr.ctr1.cursors);
1292 if (dsc->cursors == NULL) {
1293 return ldb_oom(ldb);
1295 dsc->cursor_size = p;
1299 DEBUG(4, ("Dirsync: searching with min usn > %llu\n",
1300 (long long unsigned int)dsc->fromreqUSN));
1301 if (dsc->fromreqUSN > 0) {
1302 /* FIXME it would be better to use PRId64 */
1303 char *expression = talloc_asprintf(dsc, "(&%s(uSNChanged>=%llu))",
1304 ldb_filter_from_tree(dsc,
1305 req->op.search.tree),
1306 (long long unsigned int)(dsc->fromreqUSN + 1));
1308 if (expression == NULL) {
1309 return ldb_oom(ldb);
1311 new_tree = ldb_parse_tree(req, expression);
1312 if (new_tree == NULL) {
1313 return ldb_error(ldb, LDB_ERR_OPERATIONS_ERROR,
1314 "Problem while parsing tree");
1319 * Mark dirsync control as uncritical (done)
1321 * We need this so ranged_results knows how to behave with
1324 control->critical = false;
1325 dsc->schema = dsdb_get_schema(ldb, dsc);
1327 * At the beginning we make the hypothesis that we will return a
1328 * complete result set.
1331 dsc->partial = false;
1334 * 3.1.1.3.4.1.3 of MS-ADTS.pdf specify that if the scope is not subtree
1335 * we treat the search as if subtree was specified
1338 ret = ldb_build_search_req_ex(&down_req, ldb, dsc,
1339 req->op.search.base,
1344 dsc, dirsync_search_callback,
1346 LDB_REQ_SET_LOCATION(down_req);
1347 if (ret != LDB_SUCCESS) {
1350 /* perform the search */
1351 return ldb_next_request(module, down_req);
1354 static int dirsync_ldb_init(struct ldb_module *module)
1358 ret = ldb_mod_register_control(module, LDB_CONTROL_DIRSYNC_OID);
1359 if (ret != LDB_SUCCESS) {
1360 ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_ERROR,
1361 "dirsync: Unable to register control with rootdse!\n");
1362 return ldb_operr(ldb_module_get_ctx(module));
1365 return ldb_next_init(module);
1368 static const struct ldb_module_ops ldb_dirsync_ldb_module_ops = {
1370 .search = dirsync_ldb_search,
1371 .init_context = dirsync_ldb_init,
1375 initialise the module
1377 _PUBLIC_ int ldb_dirsync_module_init(const char *version)
1380 LDB_MODULE_CHECK_VERSION(version);
1381 ret = ldb_register_module(&ldb_dirsync_ldb_module_ops);