LCOV - code coverage report
Current view: top level - source4/dsdb/samdb/ldb_modules - operational.c (source / functions) Hit Total Coverage
Test: coverage report for abartlet/fix-coverage dd10fb34 Lines: 483 610 79.2 %
Date: 2021-09-23 10:06:22 Functions: 36 37 97.3 %

          Line data    Source code
       1             : /*
       2             :    ldb database library
       3             : 
       4             :    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2010
       5             :    Copyright (C) Andrew Tridgell 2005
       6             :    Copyright (C) Simo Sorce 2006-2008
       7             :    Copyright (C) Matthias Dieter Wallnöfer 2009
       8             : 
       9             :    This program is free software; you can redistribute it and/or modify
      10             :    it under the terms of the GNU General Public License as published by
      11             :    the Free Software Foundation; either version 3 of the License, or
      12             :    (at your option) any later version.
      13             :    
      14             :    This program is distributed in the hope that it will be useful,
      15             :    but WITHOUT ANY WARRANTY; without even the implied warranty of
      16             :    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      17             :    GNU General Public License for more details.
      18             :    
      19             :    You should have received a copy of the GNU General Public License
      20             :    along with this program.  If not, see <http://www.gnu.org/licenses/>.
      21             : */
      22             : 
      23             : /*
      24             :   handle operational attributes
      25             :  */
      26             : 
      27             : /*
      28             :   createTimeStamp: HIDDEN, searchable, ldaptime, alias for whenCreated
      29             :   modifyTimeStamp: HIDDEN, searchable, ldaptime, alias for whenChanged
      30             : 
      31             :      for the above two, we do the search as normal, and if
      32             :      createTimeStamp or modifyTimeStamp is asked for, then do
      33             :      additional searches for whenCreated and whenChanged and fill in
      34             :      the resulting values
      35             : 
      36             :      we also need to replace these with the whenCreated/whenChanged
      37             :      equivalent in the search expression trees
      38             : 
      39             :   whenCreated: not-HIDDEN, CONSTRUCTED, SEARCHABLE
      40             :   whenChanged: not-HIDDEN, CONSTRUCTED, SEARCHABLE
      41             : 
      42             :      on init we need to setup attribute handlers for these so
      43             :      comparisons are done correctly. The resolution is 1 second.
      44             : 
      45             :      on add we need to add both the above, for current time
      46             : 
      47             :      on modify we need to change whenChanged
      48             : 
      49             :   structuralObjectClass: HIDDEN, CONSTRUCTED, not-searchable. always same as objectclass?
      50             : 
      51             :      for this one we do the search as normal, then if requested ask
      52             :      for objectclass, change the attribute name, and add it
      53             : 
      54             :   primaryGroupToken: HIDDEN, CONSTRUCTED, SEARCHABLE
      55             : 
      56             :      contains the RID of a certain group object
      57             :     
      58             : 
      59             :   attributeTypes: in schema only
      60             :   objectClasses: in schema only
      61             :   matchingRules: in schema only
      62             :   matchingRuleUse: in schema only
      63             :   creatorsName: not supported by w2k3?
      64             :   modifiersName: not supported by w2k3?
      65             : */
      66             : 
      67             : #include "includes.h"
      68             : #include <ldb.h>
      69             : #include <ldb_module.h>
      70             : 
      71             : #include "librpc/gen_ndr/ndr_misc.h"
      72             : #include "librpc/gen_ndr/ndr_drsblobs.h"
      73             : #include "param/param.h"
      74             : #include "dsdb/samdb/samdb.h"
      75             : #include "dsdb/samdb/ldb_modules/util.h"
      76             : 
      77             : #include "libcli/security/security.h"
      78             : 
      79             : #ifndef ARRAY_SIZE
      80             : #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
      81             : #endif
      82             : 
      83             : #undef strcasecmp
      84             : 
      85             : struct operational_data {
      86             :         struct ldb_dn *aggregate_dn;
      87             : };
      88             : 
      89             : enum search_type {
      90             :         TOKEN_GROUPS,
      91             :         TOKEN_GROUPS_GLOBAL_AND_UNIVERSAL,
      92             :         TOKEN_GROUPS_NO_GC_ACCEPTABLE,
      93             : 
      94             :         /*
      95             :          * MS-DRSR 4.1.8.1.3 RevMembGetAccountGroups: Transitive membership in
      96             :          * all account groups in a given domain, excluding built-in groups.
      97             :          * (Used internally for msDS-ResultantPSO support)
      98             :          */
      99             :         ACCOUNT_GROUPS
     100             : };
     101             : 
     102             : static int get_pso_for_user(struct ldb_module *module,
     103             :                             struct ldb_message *user_msg,
     104             :                             struct ldb_request *parent,
     105             :                             struct ldb_message **pso_msg);
     106             : 
     107             : /*
     108             :   construct a canonical name from a message
     109             : */
     110          31 : static int construct_canonical_name(struct ldb_module *module,
     111             :                                     struct ldb_message *msg, enum ldb_scope scope,
     112             :                                     struct ldb_request *parent)
     113             : {
     114             :         char *canonicalName;
     115          31 :         canonicalName = ldb_dn_canonical_string(msg, msg->dn);
     116          31 :         if (canonicalName == NULL) {
     117           0 :                 return ldb_operr(ldb_module_get_ctx(module));
     118             :         }
     119          31 :         return ldb_msg_add_steal_string(msg, "canonicalName", canonicalName);
     120             : }
     121             : 
     122             : /*
     123             :   construct a primary group token for groups from a message
     124             : */
     125          19 : static int construct_primary_group_token(struct ldb_module *module,
     126             :                                          struct ldb_message *msg, enum ldb_scope scope,
     127             :                                          struct ldb_request *parent)
     128             : {
     129             :         struct ldb_context *ldb;
     130             :         uint32_t primary_group_token;
     131             :         
     132          19 :         ldb = ldb_module_get_ctx(module);
     133          19 :         if (ldb_match_msg_objectclass(msg, "group") == 1) {
     134             :                 primary_group_token
     135           7 :                         = samdb_result_rid_from_sid(msg, msg, "objectSid", 0);
     136           7 :                 if (primary_group_token == 0) {
     137           0 :                         return LDB_SUCCESS;
     138             :                 }
     139             : 
     140           7 :                 return samdb_msg_add_uint(ldb, msg, msg, "primaryGroupToken",
     141             :                         primary_group_token);
     142             :         } else {
     143          12 :                 return LDB_SUCCESS;
     144             :         }
     145             : }
     146             : 
     147             : /*
     148             :  * Returns the group SIDs for the user in the given LDB message
     149             :  */
     150        6979 : static int get_group_sids(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
     151             :                           struct ldb_message *msg, const char *attribute_string,
     152             :                           enum search_type type, struct dom_sid **groupSIDs,
     153             :                           unsigned int *num_groupSIDs)
     154             : {
     155        6979 :         const char *filter = NULL;
     156             :         NTSTATUS status;
     157             :         struct dom_sid *primary_group_sid;
     158             :         const char *primary_group_string;
     159             :         const char *primary_group_dn;
     160             :         DATA_BLOB primary_group_blob;
     161             :         struct dom_sid *account_sid;
     162             :         const char *account_sid_string;
     163             :         const char *account_sid_dn;
     164             :         DATA_BLOB account_sid_blob;
     165             :         struct dom_sid *domain_sid;
     166             : 
     167             :         /* If it's not a user, it won't have a primaryGroupID */
     168        6979 :         if (ldb_msg_find_element(msg, "primaryGroupID") == NULL) {
     169           3 :                 return LDB_SUCCESS;
     170             :         }
     171             : 
     172             :         /* Ensure it has an objectSID too */
     173        6976 :         account_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
     174        6976 :         if (account_sid == NULL) {
     175           0 :                 return LDB_SUCCESS;
     176             :         }
     177             : 
     178        6976 :         status = dom_sid_split_rid(mem_ctx, account_sid, &domain_sid, NULL);
     179        6976 :         if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) {
     180           0 :                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
     181        6976 :         } else if (!NT_STATUS_IS_OK(status)) {
     182           0 :                 return LDB_ERR_OPERATIONS_ERROR;
     183             :         }
     184             : 
     185        6976 :         primary_group_sid = dom_sid_add_rid(mem_ctx,
     186             :                                             domain_sid,
     187             :                                             ldb_msg_find_attr_as_uint(msg, "primaryGroupID", ~0));
     188        6976 :         if (!primary_group_sid) {
     189           0 :                 return ldb_oom(ldb);
     190             :         }
     191             : 
     192             :         /* only return security groups */
     193        6976 :         switch(type) {
     194           4 :         case TOKEN_GROUPS_GLOBAL_AND_UNIVERSAL:
     195           4 :                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=group)(groupType:1.2.840.113556.1.4.803:=%u)(|(groupType:1.2.840.113556.1.4.803:=%u)(groupType:1.2.840.113556.1.4.803:=%u)))",
     196             :                                          GROUP_TYPE_SECURITY_ENABLED, GROUP_TYPE_ACCOUNT_GROUP, GROUP_TYPE_UNIVERSAL_GROUP);
     197           4 :                 break;
     198        6134 :         case TOKEN_GROUPS_NO_GC_ACCEPTABLE:
     199             :         case TOKEN_GROUPS:
     200        6134 :                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=group)(groupType:1.2.840.113556.1.4.803:=%u))",
     201             :                                          GROUP_TYPE_SECURITY_ENABLED);
     202        6134 :                 break;
     203             : 
     204             :         /* for RevMembGetAccountGroups, exclude built-in groups */
     205         838 :         case ACCOUNT_GROUPS:
     206         838 :                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=group)(!(groupType:1.2.840.113556.1.4.803:=%u))(groupType:1.2.840.113556.1.4.803:=%u))",
     207             :                                 GROUP_TYPE_BUILTIN_LOCAL_GROUP, GROUP_TYPE_SECURITY_ENABLED);
     208         838 :                 break;
     209             :         }
     210             : 
     211        6976 :         if (!filter) {
     212           0 :                 return ldb_oom(ldb);
     213             :         }
     214             : 
     215        6976 :         primary_group_string = dom_sid_string(mem_ctx, primary_group_sid);
     216        6976 :         if (!primary_group_string) {
     217           0 :                 return ldb_oom(ldb);
     218             :         }
     219             : 
     220        6976 :         primary_group_dn = talloc_asprintf(mem_ctx, "<SID=%s>", primary_group_string);
     221        6976 :         if (!primary_group_dn) {
     222           0 :                 return ldb_oom(ldb);
     223             :         }
     224             : 
     225        6976 :         primary_group_blob = data_blob_string_const(primary_group_dn);
     226             : 
     227        6976 :         account_sid_string = dom_sid_string(mem_ctx, account_sid);
     228        6976 :         if (!account_sid_string) {
     229           0 :                 return ldb_oom(ldb);
     230             :         }
     231             : 
     232        6976 :         account_sid_dn = talloc_asprintf(mem_ctx, "<SID=%s>", account_sid_string);
     233        6976 :         if (!account_sid_dn) {
     234           0 :                 return ldb_oom(ldb);
     235             :         }
     236             : 
     237        6976 :         account_sid_blob = data_blob_string_const(account_sid_dn);
     238             : 
     239        6976 :         status = dsdb_expand_nested_groups(ldb, &account_sid_blob,
     240             :                                            true, /* We don't want to add the object's SID itself,
     241             :                                                     it's not returend in this attribute */
     242             :                                            filter,
     243             :                                            mem_ctx, groupSIDs, num_groupSIDs);
     244             : 
     245        6976 :         if (!NT_STATUS_IS_OK(status)) {
     246           0 :                 ldb_asprintf_errstring(ldb, "Failed to construct %s: expanding groups of SID %s failed: %s",
     247             :                                        attribute_string, account_sid_string,
     248             :                                        nt_errstr(status));
     249           0 :                 return LDB_ERR_OPERATIONS_ERROR;
     250             :         }
     251             : 
     252             :         /* Expands the primary group - this function takes in
     253             :          * memberOf-like values, so we fake one up with the
     254             :          * <SID=S-...> format of DN and then let it expand
     255             :          * them, as long as they meet the filter - so only
     256             :          * domain groups, not builtin groups
     257             :          */
     258        6976 :         status = dsdb_expand_nested_groups(ldb, &primary_group_blob, false, filter,
     259             :                                            mem_ctx, groupSIDs, num_groupSIDs);
     260        6976 :         if (!NT_STATUS_IS_OK(status)) {
     261           0 :                 ldb_asprintf_errstring(ldb, "Failed to construct %s: expanding groups of SID %s failed: %s",
     262             :                                        attribute_string, account_sid_string,
     263             :                                        nt_errstr(status));
     264           0 :                 return LDB_ERR_OPERATIONS_ERROR;
     265             :         }
     266             : 
     267        6706 :         return LDB_SUCCESS;
     268             : }
     269             : 
     270             : /*
     271             :   construct the token groups for SAM objects from a message
     272             : */
     273        6141 : static int construct_generic_token_groups(struct ldb_module *module,
     274             :                                           struct ldb_message *msg, enum ldb_scope scope,
     275             :                                           struct ldb_request *parent,
     276             :                                           const char *attribute_string,
     277             :                                           enum search_type type)
     278             : {
     279        6141 :         struct ldb_context *ldb = ldb_module_get_ctx(module);
     280        6141 :         TALLOC_CTX *tmp_ctx = talloc_new(msg);
     281             :         unsigned int i;
     282             :         int ret;
     283        6141 :         struct dom_sid *groupSIDs = NULL;
     284        6141 :         unsigned int num_groupSIDs = 0;
     285             : 
     286        6141 :         if (scope != LDB_SCOPE_BASE) {
     287           0 :                 ldb_set_errstring(ldb, "Cannot provide tokenGroups attribute, this is not a BASE search");
     288           0 :                 return LDB_ERR_OPERATIONS_ERROR;
     289             :         }
     290             : 
     291             :         /* calculate the group SIDs for this object */
     292        6141 :         ret = get_group_sids(ldb, tmp_ctx, msg, attribute_string, type,
     293             :                              &groupSIDs, &num_groupSIDs);
     294             : 
     295        6141 :         if (ret != LDB_SUCCESS) {
     296           0 :                 talloc_free(tmp_ctx);
     297           0 :                 return LDB_ERR_OPERATIONS_ERROR;
     298             :         }
     299             : 
     300             :         /* add these SIDs to the search result */
     301       49191 :         for (i=0; i < num_groupSIDs; i++) {
     302       43320 :                 ret = samdb_msg_add_dom_sid(ldb, msg, msg, attribute_string, &groupSIDs[i]);
     303       43320 :                 if (ret) {
     304           0 :                         talloc_free(tmp_ctx);
     305           0 :                         return ret;
     306             :                 }
     307             :         }
     308             : 
     309        5871 :         return LDB_SUCCESS;
     310             : }
     311             : 
     312        6137 : static int construct_token_groups(struct ldb_module *module,
     313             :                                   struct ldb_message *msg, enum ldb_scope scope,
     314             :                                   struct ldb_request *parent)
     315             : {
     316             :         /**
     317             :          * TODO: Add in a limiting domain when we start to support
     318             :          * trusted domains.
     319             :          */
     320        6137 :         return construct_generic_token_groups(module, msg, scope, parent,
     321             :                                               "tokenGroups",
     322             :                                               TOKEN_GROUPS);
     323             : }
     324             : 
     325           0 : static int construct_token_groups_no_gc(struct ldb_module *module,
     326             :                                         struct ldb_message *msg, enum ldb_scope scope,
     327             :                                         struct ldb_request *parent)
     328             : {
     329             :         /**
     330             :          * TODO: Add in a limiting domain when we start to support
     331             :          * trusted domains.
     332             :          */
     333           0 :         return construct_generic_token_groups(module, msg, scope, parent,
     334             :                                               "tokenGroupsNoGCAcceptable",
     335             :                                               TOKEN_GROUPS);
     336             : }
     337             : 
     338           4 : static int construct_global_universal_token_groups(struct ldb_module *module,
     339             :                                                    struct ldb_message *msg, enum ldb_scope scope,
     340             :                                                    struct ldb_request *parent)
     341             : {
     342           4 :         return construct_generic_token_groups(module, msg, scope, parent,
     343             :                                               "tokenGroupsGlobalAndUniversal",
     344             :                                               TOKEN_GROUPS_GLOBAL_AND_UNIVERSAL);
     345             : }
     346             : /*
     347             :   construct the parent GUID for an entry from a message
     348             : */
     349      636542 : static int construct_parent_guid(struct ldb_module *module,
     350             :                                  struct ldb_message *msg, enum ldb_scope scope,
     351             :                                  struct ldb_request *parent)
     352             : {
     353             :         struct ldb_result *res, *parent_res;
     354             :         const struct ldb_val *parent_guid;
     355      636542 :         const char *attrs[] = { "instanceType", NULL };
     356      636542 :         const char *attrs2[] = { "objectGUID", NULL };
     357             :         uint32_t instanceType;
     358             :         int ret;
     359             :         struct ldb_dn *parent_dn;
     360             :         struct ldb_val v;
     361             : 
     362             :         /* determine if the object is NC by instance type */
     363      636542 :         ret = dsdb_module_search_dn(module, msg, &res, msg->dn, attrs,
     364             :                                     DSDB_FLAG_NEXT_MODULE |
     365             :                                     DSDB_SEARCH_SHOW_RECYCLED, parent);
     366      636542 :         if (ret != LDB_SUCCESS) {
     367           0 :                 return ret;
     368             :         }
     369             : 
     370      636542 :         instanceType = ldb_msg_find_attr_as_uint(res->msgs[0],
     371             :                                                  "instanceType", 0);
     372      636542 :         talloc_free(res);
     373      636542 :         if (instanceType & INSTANCE_TYPE_IS_NC_HEAD) {
     374        1092 :                 DEBUG(4,(__location__ ": Object %s is NC\n",
     375             :                          ldb_dn_get_linearized(msg->dn)));
     376        1092 :                 return LDB_SUCCESS;
     377             :         }
     378      635450 :         parent_dn = ldb_dn_get_parent(msg, msg->dn);
     379             : 
     380      635450 :         if (parent_dn == NULL) {
     381           0 :                 DEBUG(4,(__location__ ": Failed to find parent for dn %s\n",
     382             :                                          ldb_dn_get_linearized(msg->dn)));
     383           0 :                 return LDB_ERR_OTHER;
     384             :         }
     385      635450 :         ret = dsdb_module_search_dn(module, msg, &parent_res, parent_dn, attrs2,
     386             :                                     DSDB_FLAG_NEXT_MODULE |
     387             :                                     DSDB_SEARCH_SHOW_RECYCLED, parent);
     388             :         /* not NC, so the object should have a parent*/
     389      635450 :         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
     390           0 :                 ret = ldb_error(ldb_module_get_ctx(module), LDB_ERR_OPERATIONS_ERROR, 
     391             :                                  talloc_asprintf(msg, "Parent dn %s for %s does not exist",
     392             :                                                  ldb_dn_get_linearized(parent_dn),
     393             :                                                  ldb_dn_get_linearized(msg->dn)));
     394           0 :                 talloc_free(parent_dn);
     395           0 :                 return ret;
     396      635450 :         } else if (ret != LDB_SUCCESS) {
     397           0 :                 talloc_free(parent_dn);
     398           0 :                 return ret;
     399             :         }
     400      635450 :         talloc_free(parent_dn);
     401             : 
     402      635450 :         parent_guid = ldb_msg_find_ldb_val(parent_res->msgs[0], "objectGUID");
     403      635450 :         if (!parent_guid) {
     404           0 :                 talloc_free(parent_res);
     405           0 :                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
     406             :         }
     407             : 
     408      635450 :         v = data_blob_dup_talloc(parent_res, *parent_guid);
     409      635450 :         if (!v.data) {
     410           0 :                 talloc_free(parent_res);
     411           0 :                 return ldb_oom(ldb_module_get_ctx(module));
     412             :         }
     413      635450 :         ret = ldb_msg_add_steal_value(msg, "parentGUID", &v);
     414      635450 :         talloc_free(parent_res);
     415      635450 :         return ret;
     416             : }
     417             : 
     418           1 : static int construct_modifyTimeStamp(struct ldb_module *module,
     419             :                                         struct ldb_message *msg, enum ldb_scope scope,
     420             :                                         struct ldb_request *parent)
     421             : {
     422           1 :         struct operational_data *data = talloc_get_type(ldb_module_get_private(module), struct operational_data);
     423           1 :         struct ldb_context *ldb = ldb_module_get_ctx(module);
     424             : 
     425             :         /* We may be being called before the init function has finished */
     426           1 :         if (!data) {
     427           0 :                 return LDB_SUCCESS;
     428             :         }
     429             : 
     430             :         /* Try and set this value up, if possible.  Don't worry if it
     431             :          * fails, we may not have the DB set up yet.
     432             :          */
     433           1 :         if (!data->aggregate_dn) {
     434           1 :                 data->aggregate_dn = samdb_aggregate_schema_dn(ldb, data);
     435             :         }
     436             : 
     437           1 :         if (data->aggregate_dn && ldb_dn_compare(data->aggregate_dn, msg->dn) == 0) {
     438             :                 /*
     439             :                  * If we have the DN for the object with common name = Aggregate and
     440             :                  * the request is for this DN then let's do the following:
     441             :                  * 1) search the object which changedUSN correspond to the one of the loaded
     442             :                  * schema.
     443             :                  * 2) Get the whenChanged attribute
     444             :                  * 3) Generate the modifyTimestamp out of the whenChanged attribute
     445             :                  */
     446           0 :                 const struct dsdb_schema *schema = dsdb_get_schema(ldb, NULL);
     447           0 :                 char *value = ldb_timestring(msg, schema->ts_last_change);
     448             : 
     449           0 :                 if (value == NULL) {
     450           0 :                         return ldb_oom(ldb_module_get_ctx(module));
     451             :                 }
     452             : 
     453           0 :                 return ldb_msg_add_string(msg, "modifyTimeStamp", value);
     454             :         }
     455           1 :         return ldb_msg_copy_attr(msg, "whenChanged", "modifyTimeStamp");
     456             : }
     457             : 
     458             : /*
     459             :   construct a subSchemaSubEntry
     460             : */
     461           1 : static int construct_subschema_subentry(struct ldb_module *module,
     462             :                                         struct ldb_message *msg, enum ldb_scope scope,
     463             :                                         struct ldb_request *parent)
     464             : {
     465           1 :         struct operational_data *data = talloc_get_type(ldb_module_get_private(module), struct operational_data);
     466             :         char *subSchemaSubEntry;
     467             : 
     468             :         /* We may be being called before the init function has finished */
     469           1 :         if (!data) {
     470           0 :                 return LDB_SUCCESS;
     471             :         }
     472             : 
     473             :         /* Try and set this value up, if possible.  Don't worry if it
     474             :          * fails, we may not have the DB set up yet, and it's not
     475             :          * really vital anyway */
     476           1 :         if (!data->aggregate_dn) {
     477           0 :                 struct ldb_context *ldb = ldb_module_get_ctx(module);
     478           0 :                 data->aggregate_dn = samdb_aggregate_schema_dn(ldb, data);
     479             :         }
     480             : 
     481           1 :         if (data->aggregate_dn) {
     482           1 :                 subSchemaSubEntry = ldb_dn_alloc_linearized(msg, data->aggregate_dn);
     483           1 :                 return ldb_msg_add_steal_string(msg, "subSchemaSubEntry", subSchemaSubEntry);
     484             :         }
     485           0 :         return LDB_SUCCESS;
     486             : }
     487             : 
     488             : 
     489       28162 : static int construct_msds_isrodc_with_dn(struct ldb_module *module,
     490             :                                          struct ldb_message *msg,
     491             :                                          struct ldb_message_element *object_category)
     492             : {
     493             :         struct ldb_context *ldb;
     494             :         struct ldb_dn *dn;
     495             :         const struct ldb_val *val;
     496             : 
     497       28162 :         ldb = ldb_module_get_ctx(module);
     498       28162 :         if (!ldb) {
     499           0 :                 DEBUG(4, (__location__ ": Failed to get ldb \n"));
     500           0 :                 return LDB_ERR_OPERATIONS_ERROR;
     501             :         }
     502             : 
     503       28162 :         dn = ldb_dn_new(msg, ldb, (const char *)object_category->values[0].data);
     504       28162 :         if (!dn) {
     505           0 :                 DEBUG(4, (__location__ ": Failed to create dn from %s \n",
     506             :                           (const char *)object_category->values[0].data));
     507           0 :                 return ldb_operr(ldb);
     508             :         }
     509             : 
     510       28162 :         val = ldb_dn_get_rdn_val(dn);
     511       28162 :         if (!val) {
     512           0 :                 DEBUG(4, (__location__ ": Failed to get rdn val from %s \n",
     513             :                           ldb_dn_get_linearized(dn)));
     514           0 :                 return ldb_operr(ldb);
     515             :         }
     516             : 
     517       28162 :         if (strequal((const char *)val->data, "NTDS-DSA")) {
     518       27784 :                 ldb_msg_add_string(msg, "msDS-isRODC", "FALSE");
     519             :         } else {
     520         378 :                 ldb_msg_add_string(msg, "msDS-isRODC", "TRUE");
     521             :         }
     522       27381 :         return LDB_SUCCESS;
     523             : }
     524             : 
     525          26 : static int construct_msds_isrodc_with_server_dn(struct ldb_module *module,
     526             :                                                 struct ldb_message *msg,
     527             :                                                 struct ldb_dn *dn,
     528             :                                                 struct ldb_request *parent)
     529             : {
     530             :         struct ldb_dn *server_dn;
     531          26 :         const char *attr_obj_cat[] = { "objectCategory", NULL };
     532             :         struct ldb_result *res;
     533             :         struct ldb_message_element *object_category;
     534             :         int ret;
     535             : 
     536          26 :         server_dn = ldb_dn_copy(msg, dn);
     537          26 :         if (!ldb_dn_add_child_fmt(server_dn, "CN=NTDS Settings")) {
     538           0 :                 DEBUG(4, (__location__ ": Failed to add child to %s \n",
     539             :                           ldb_dn_get_linearized(server_dn)));
     540           0 :                 return ldb_operr(ldb_module_get_ctx(module));
     541             :         }
     542             : 
     543          26 :         ret = dsdb_module_search_dn(module, msg, &res, server_dn, attr_obj_cat,
     544             :                                     DSDB_FLAG_NEXT_MODULE, parent);
     545          26 :         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
     546           5 :                 DEBUG(4,(__location__ ": Can't get objectCategory for %s \n",
     547             :                                          ldb_dn_get_linearized(server_dn)));
     548           5 :                 return LDB_SUCCESS;
     549          21 :         } else if (ret != LDB_SUCCESS) {
     550           0 :                 return ret;
     551             :         }
     552             : 
     553          21 :         object_category = ldb_msg_find_element(res->msgs[0], "objectCategory");
     554          21 :         if (!object_category) {
     555           0 :                 DEBUG(4,(__location__ ": Can't find objectCategory for %s \n",
     556             :                          ldb_dn_get_linearized(res->msgs[0]->dn)));
     557           0 :                 return LDB_SUCCESS;
     558             :         }
     559          21 :         return construct_msds_isrodc_with_dn(module, msg, object_category);
     560             : }
     561             : 
     562          12 : static int construct_msds_isrodc_with_computer_dn(struct ldb_module *module,
     563             :                                                   struct ldb_message *msg,
     564             :                                                   struct ldb_request *parent)
     565             : {
     566             :         int ret;
     567             :         struct ldb_dn *server_dn;
     568             : 
     569          12 :         ret = dsdb_module_reference_dn(module, msg, msg->dn, "serverReferenceBL",
     570             :                                        &server_dn, parent);
     571          12 :         if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_NO_SUCH_ATTRIBUTE) {
     572             :                 /* it's OK if we can't find serverReferenceBL attribute */
     573           2 :                 DEBUG(4,(__location__ ": Can't get serverReferenceBL for %s \n",
     574             :                          ldb_dn_get_linearized(msg->dn)));
     575           2 :                 return LDB_SUCCESS;
     576          10 :         } else if (ret != LDB_SUCCESS) {
     577           0 :                 return ret;
     578             :         }
     579             : 
     580          10 :         return construct_msds_isrodc_with_server_dn(module, msg, server_dn, parent);
     581             : }
     582             : 
     583             : /*
     584             :   construct msDS-isRODC attr
     585             : */
     586       28169 : static int construct_msds_isrodc(struct ldb_module *module,
     587             :                                  struct ldb_message *msg, enum ldb_scope scope,
     588             :                                  struct ldb_request *parent)
     589             : {
     590             :         struct ldb_message_element * object_class;
     591             :         struct ldb_message_element * object_category;
     592             :         unsigned int i;
     593             : 
     594       28169 :         object_class = ldb_msg_find_element(msg, "objectClass");
     595       28169 :         if (!object_class) {
     596           0 :                 DEBUG(4,(__location__ ": Can't get objectClass for %s \n",
     597             :                          ldb_dn_get_linearized(msg->dn)));
     598           0 :                 return ldb_operr(ldb_module_get_ctx(module));
     599             :         }
     600             : 
     601       83734 :         for (i=0; i<object_class->num_values; i++) {
     602       84515 :                 if (strequal((const char*)object_class->values[i].data, "nTDSDSA")) {
     603             :                         /* If TO!objectCategory  equals the DN of the classSchema  object for the nTDSDSA
     604             :                          * object class, then TO!msDS-isRODC  is false. Otherwise, TO!msDS-isRODC  is true.
     605             :                          */
     606       28141 :                         object_category = ldb_msg_find_element(msg, "objectCategory");
     607       28141 :                         if (!object_category) {
     608           0 :                                 DEBUG(4,(__location__ ": Can't get objectCategory for %s \n",
     609             :                                          ldb_dn_get_linearized(msg->dn)));
     610           0 :                                 return LDB_SUCCESS;
     611             :                         }
     612       28141 :                         return construct_msds_isrodc_with_dn(module, msg, object_category);
     613             :                 }
     614       56374 :                 if (strequal((const char*)object_class->values[i].data, "server")) {
     615             :                         /* Let TN be the nTDSDSA  object whose DN is "CN=NTDS Settings," prepended to
     616             :                          * the DN of TO. Apply the previous rule for the "TO is an nTDSDSA  object" case,
     617             :                          * substituting TN for TO.
     618             :                          */
     619          16 :                         return construct_msds_isrodc_with_server_dn(module, msg, msg->dn, parent);
     620             :                 }
     621       56358 :                 if (strequal((const char*)object_class->values[i].data, "computer")) {
     622             :                         /* Let TS be the server  object named by TO!serverReferenceBL. Apply the previous
     623             :                          * rule for the "TO is a server  object" case, substituting TS for TO.
     624             :                          */
     625          12 :                         return construct_msds_isrodc_with_computer_dn(module, msg, parent);
     626             :                 }
     627             :         }
     628             : 
     629           0 :         return LDB_SUCCESS;
     630             : }
     631             : 
     632             : 
     633             : /*
     634             :   construct msDS-keyVersionNumber attr
     635             : 
     636             :   TODO:  Make this based on the 'win2k' DS huristics bit...
     637             : 
     638             : */
     639      268726 : static int construct_msds_keyversionnumber(struct ldb_module *module,
     640             :                                            struct ldb_message *msg,
     641             :                                            enum ldb_scope scope,
     642             :                                            struct ldb_request *parent)
     643             : {
     644             :         uint32_t i;
     645             :         enum ndr_err_code ndr_err;
     646             :         const struct ldb_val *omd_value;
     647             :         struct replPropertyMetaDataBlob *omd;
     648             :         int ret;
     649             : 
     650      268726 :         omd_value = ldb_msg_find_ldb_val(msg, "replPropertyMetaData");
     651      268726 :         if (!omd_value) {
     652             :                 /* We can't make up a key version number without meta data */
     653           0 :                 return LDB_SUCCESS;
     654             :         }
     655             : 
     656      268726 :         omd = talloc(msg, struct replPropertyMetaDataBlob);
     657      268726 :         if (!omd) {
     658           0 :                 ldb_module_oom(module);
     659           0 :                 return LDB_SUCCESS;
     660             :         }
     661             : 
     662      268726 :         ndr_err = ndr_pull_struct_blob(omd_value, omd, omd,
     663             :                                        (ndr_pull_flags_fn_t)ndr_pull_replPropertyMetaDataBlob);
     664      268726 :         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
     665           0 :                 DEBUG(0,(__location__ ": Failed to parse replPropertyMetaData for %s when trying to add msDS-KeyVersionNumber\n",
     666             :                          ldb_dn_get_linearized(msg->dn)));
     667           0 :                 return ldb_operr(ldb_module_get_ctx(module));
     668             :         }
     669             : 
     670      268726 :         if (omd->version != 1) {
     671           0 :                 DEBUG(0,(__location__ ": bad version %u in replPropertyMetaData for %s when trying to add msDS-KeyVersionNumber\n",
     672             :                          omd->version, ldb_dn_get_linearized(msg->dn)));
     673           0 :                 talloc_free(omd);
     674           0 :                 return LDB_SUCCESS;
     675             :         }
     676     3614152 :         for (i=0; i<omd->ctr.ctr1.count; i++) {
     677     3621534 :                 if (omd->ctr.ctr1.array[i].attid == DRSUAPI_ATTID_unicodePwd) {
     678      268726 :                         ret = samdb_msg_add_uint(ldb_module_get_ctx(module),
     679             :                                                  msg, msg,
     680             :                                                  "msDS-KeyVersionNumber",
     681      261344 :                                                  omd->ctr.ctr1.array[i].version);
     682      268726 :                         if (ret != LDB_SUCCESS) {
     683           0 :                                 talloc_free(omd);
     684           0 :                                 return ret;
     685             :                         }
     686      261344 :                         break;
     687             :                 }
     688             :         }
     689      261344 :         return LDB_SUCCESS;
     690             : 
     691             : }
     692             : 
     693             : #define _UF_TRUST_ACCOUNTS ( \
     694             :         UF_WORKSTATION_TRUST_ACCOUNT | \
     695             :         UF_SERVER_TRUST_ACCOUNT | \
     696             :         UF_INTERDOMAIN_TRUST_ACCOUNT \
     697             : )
     698             : #define _UF_NO_EXPIRY_ACCOUNTS ( \
     699             :         UF_SMARTCARD_REQUIRED | \
     700             :         UF_DONT_EXPIRE_PASSWD | \
     701             :         _UF_TRUST_ACCOUNTS \
     702             : )
     703             : 
     704             : 
     705             : /*
     706             :  * Returns the Effective-MaximumPasswordAge for a user
     707             :  */
     708      479557 : static int64_t get_user_max_pwd_age(struct ldb_module *module,
     709             :                                     struct ldb_message *user_msg,
     710             :                                     struct ldb_request *parent,
     711             :                                     struct ldb_dn *nc_root)
     712             : {
     713             :         int ret;
     714      479557 :         struct ldb_message *pso = NULL;
     715      479557 :         struct ldb_context *ldb = ldb_module_get_ctx(module);
     716             : 
     717             :         /* if a PSO applies to the user, use its maxPwdAge */
     718      479557 :         ret = get_pso_for_user(module, user_msg, parent, &pso);
     719      479557 :         if (ret != LDB_SUCCESS) {
     720             : 
     721             :                 /* log the error, but fallback to the domain default */
     722           0 :                 DBG_ERR("Error retrieving PSO for %s\n",
     723             :                         ldb_dn_get_linearized(user_msg->dn));
     724             :         }
     725             : 
     726      479557 :         if (pso != NULL) {
     727        1568 :                 return ldb_msg_find_attr_as_int64(pso,
     728             :                                                   "msDS-MaximumPasswordAge", 0);
     729             :         }
     730             : 
     731             :         /* otherwise return the default domain value */
     732      477989 :         return samdb_search_int64(ldb, user_msg, 0, nc_root, "maxPwdAge", NULL);
     733             : }
     734             : 
     735             : /*
     736             :   calculate msDS-UserPasswordExpiryTimeComputed
     737             : */
     738      537013 : static NTTIME get_msds_user_password_expiry_time_computed(struct ldb_module *module,
     739             :                                                 struct ldb_message *msg,
     740             :                                                 struct ldb_request *parent,
     741             :                                                 struct ldb_dn *domain_dn)
     742             : {
     743             :         int64_t pwdLastSet, maxPwdAge;
     744             :         uint32_t userAccountControl;
     745             :         NTTIME ret;
     746             : 
     747      537013 :         userAccountControl = ldb_msg_find_attr_as_uint(msg,
     748             :                                         "userAccountControl",
     749             :                                         0);
     750      537013 :         if (userAccountControl & _UF_NO_EXPIRY_ACCOUNTS) {
     751       41967 :                 return 0x7FFFFFFFFFFFFFFFULL;
     752             :         }
     753             : 
     754      494032 :         pwdLastSet = ldb_msg_find_attr_as_int64(msg, "pwdLastSet", 0);
     755      494032 :         if (pwdLastSet == 0) {
     756       14441 :                 return 0;
     757             :         }
     758             : 
     759      479557 :         if (pwdLastSet <= -1) {
     760             :                 /*
     761             :                  * This can't really happen...
     762             :                  */
     763           0 :                 return 0x7FFFFFFFFFFFFFFFULL;
     764             :         }
     765             : 
     766      479557 :         if (pwdLastSet >= 0x7FFFFFFFFFFFFFFFLL) {
     767             :                 /*
     768             :                  * Somethings wrong with the clock...
     769             :                  */
     770           0 :                 return 0x7FFFFFFFFFFFFFFFULL;
     771             :         }
     772             : 
     773             :         /*
     774             :          * Note that maxPwdAge is a stored as negative value.
     775             :          *
     776             :          * Possible values are in the range of:
     777             :          *
     778             :          * maxPwdAge: -864000000001
     779             :          * to
     780             :          * maxPwdAge: -9223372036854775808 (-0x8000000000000000ULL)
     781             :          *
     782             :          */
     783      479557 :         maxPwdAge = get_user_max_pwd_age(module, msg, parent, domain_dn);
     784      479557 :         if (maxPwdAge >= -864000000000) {
     785             :                 /*
     786             :                  * This is not really possible...
     787             :                  */
     788          64 :                 return 0x7FFFFFFFFFFFFFFFULL;
     789             :         }
     790             : 
     791      479493 :         if (maxPwdAge == -0x8000000000000000LL) {
     792           0 :                 return 0x7FFFFFFFFFFFFFFFULL;
     793             :         }
     794             : 
     795             :         /*
     796             :          * Note we already caught maxPwdAge == -0x8000000000000000ULL
     797             :          * and pwdLastSet >= 0x7FFFFFFFFFFFFFFFULL above.
     798             :          *
     799             :          * Remember maxPwdAge is a negative number,
     800             :          * so it results in the following.
     801             :          *
     802             :          * 0x7FFFFFFFFFFFFFFEULL + 0x7FFFFFFFFFFFFFFFULL
     803             :          * =
     804             :          * 0xFFFFFFFFFFFFFFFDULL
     805             :          *
     806             :          * or to put it another way, adding two numbers less than 1<<63 can't
     807             :          * ever be more than 1<<64, therefore this result can't wrap.
     808             :          */
     809      479493 :         ret = (NTTIME)pwdLastSet - (NTTIME)maxPwdAge;
     810      479493 :         if (ret >= 0x7FFFFFFFFFFFFFFFULL) {
     811           0 :                 return 0x7FFFFFFFFFFFFFFFULL;
     812             :         }
     813             : 
     814      479493 :         return ret;
     815             : }
     816             : 
     817             : /*
     818             :  * Returns the Effective-LockoutDuration for a user
     819             :  */
     820        2140 : static int64_t get_user_lockout_duration(struct ldb_module *module,
     821             :                                          struct ldb_message *user_msg,
     822             :                                          struct ldb_request *parent,
     823             :                                          struct ldb_dn *nc_root)
     824             : {
     825             :         int ret;
     826        2140 :         struct ldb_message *pso = NULL;
     827        2140 :         struct ldb_context *ldb = ldb_module_get_ctx(module);
     828             : 
     829             :         /* if a PSO applies to the user, use its lockoutDuration */
     830        2140 :         ret = get_pso_for_user(module, user_msg, parent, &pso);
     831        2140 :         if (ret != LDB_SUCCESS) {
     832             : 
     833             :                 /* log the error, but fallback to the domain default */
     834           0 :                 DBG_ERR("Error retrieving PSO for %s\n",
     835             :                         ldb_dn_get_linearized(user_msg->dn));
     836             :         }
     837             : 
     838        2140 :         if (pso != NULL) {
     839         319 :                 return ldb_msg_find_attr_as_int64(pso,
     840             :                                                   "msDS-LockoutDuration", 0);
     841             :         }
     842             : 
     843             :         /* otherwise return the default domain value */
     844        1821 :         return samdb_search_int64(ldb, user_msg, 0, nc_root, "lockoutDuration",
     845             :                                   NULL);
     846             : }
     847             : 
     848             : /*
     849             :   construct msDS-User-Account-Control-Computed attr
     850             : */
     851      305948 : static int construct_msds_user_account_control_computed(struct ldb_module *module,
     852             :                                                         struct ldb_message *msg, enum ldb_scope scope,
     853             :                                                         struct ldb_request *parent)
     854             : {
     855             :         uint32_t userAccountControl;
     856      305948 :         uint32_t msDS_User_Account_Control_Computed = 0;
     857      305948 :         struct ldb_context *ldb = ldb_module_get_ctx(module);
     858             :         NTTIME now;
     859             :         struct ldb_dn *nc_root;
     860             :         int ret;
     861             : 
     862      305948 :         ret = dsdb_find_nc_root(ldb, msg, msg->dn, &nc_root);
     863      305948 :         if (ret != 0) {
     864           0 :                 ldb_asprintf_errstring(ldb,
     865             :                                        "Failed to find NC root of DN: %s: %s",
     866             :                                        ldb_dn_get_linearized(msg->dn),
     867             :                                        ldb_errstring(ldb_module_get_ctx(module)));
     868           0 :                 return ret;
     869             :         }
     870      305948 :         if (ldb_dn_compare(nc_root, ldb_get_default_basedn(ldb)) != 0) {
     871             :                 /* Only calculate this on our default NC */
     872           0 :                 return 0;
     873             :         }
     874             :         /* Test account expire time */
     875      305948 :         unix_to_nt_time(&now, time(NULL));
     876             : 
     877      305948 :         userAccountControl = ldb_msg_find_attr_as_uint(msg,
     878             :                                                        "userAccountControl",
     879             :                                                        0);
     880      305948 :         if (!(userAccountControl & _UF_TRUST_ACCOUNTS)) {
     881             : 
     882      262959 :                 int64_t lockoutTime = ldb_msg_find_attr_as_int64(msg, "lockoutTime", 0);
     883      262959 :                 if (lockoutTime != 0) {
     884             :                         int64_t lockoutDuration;
     885             : 
     886        2140 :                         lockoutDuration = get_user_lockout_duration(module, msg,
     887             :                                                                     parent,
     888             :                                                                     nc_root);
     889             : 
     890             :                         /* zero locks out until the administrator intervenes */
     891        2140 :                         if (lockoutDuration >= 0) {
     892           0 :                                 msDS_User_Account_Control_Computed |= UF_LOCKOUT;
     893        2140 :                         } else if (lockoutTime - lockoutDuration >= now) {
     894        1583 :                                 msDS_User_Account_Control_Computed |= UF_LOCKOUT;
     895             :                         }
     896             :                 }
     897             :         }
     898             : 
     899      305948 :         if (!(userAccountControl & _UF_NO_EXPIRY_ACCOUNTS)) {
     900      245673 :                 NTTIME must_change_time
     901      260529 :                         = get_msds_user_password_expiry_time_computed(module,
     902             :                                                                       msg,
     903             :                                                                       parent,
     904             :                                                                       nc_root);
     905             :                 /* check for expired password */
     906      260529 :                 if (must_change_time < now) {
     907       12195 :                         msDS_User_Account_Control_Computed |= UF_PASSWORD_EXPIRED;
     908             :                 }
     909             :         }
     910             : 
     911      596173 :         return samdb_msg_add_int64(ldb,
     912      305948 :                                    msg->elements, msg,
     913             :                                    "msDS-User-Account-Control-Computed",
     914             :                                    msDS_User_Account_Control_Computed);
     915             : }
     916             : 
     917             : /*
     918             :   construct msDS-UserPasswordExpiryTimeComputed
     919             : */
     920      276484 : static int construct_msds_user_password_expiry_time_computed(struct ldb_module *module,
     921             :                                                              struct ldb_message *msg, enum ldb_scope scope,
     922             :                                                              struct ldb_request *parent)
     923             : {
     924      276484 :         struct ldb_context *ldb = ldb_module_get_ctx(module);
     925             :         struct ldb_dn *nc_root;
     926             :         int64_t password_expiry_time;
     927             :         int ret;
     928             : 
     929      276484 :         ret = dsdb_find_nc_root(ldb, msg, msg->dn, &nc_root);
     930      276484 :         if (ret != 0) {
     931           0 :                 ldb_asprintf_errstring(ldb,
     932             :                                        "Failed to find NC root of DN: %s: %s",
     933             :                                        ldb_dn_get_linearized(msg->dn),
     934             :                                        ldb_errstring(ldb));
     935           0 :                 return ret;
     936             :         }
     937             : 
     938      276484 :         if (ldb_dn_compare(nc_root, ldb_get_default_basedn(ldb)) != 0) {
     939             :                 /* Only calculate this on our default NC */
     940           0 :                 return 0;
     941             :         }
     942             : 
     943             :         password_expiry_time
     944      276484 :                 = get_msds_user_password_expiry_time_computed(module, msg,
     945             :                                                               parent, nc_root);
     946             : 
     947      276484 :         return samdb_msg_add_int64(ldb,
     948      276484 :                                    msg->elements, msg,
     949             :                                    "msDS-UserPasswordExpiryTimeComputed",
     950             :                                    password_expiry_time);
     951             : }
     952             : 
     953             : /*
     954             :  * Checks whether the msDS-ResultantPSO attribute is supported for a given
     955             :  * user object. As per MS-ADTS, section 3.1.1.4.5.36 msDS-ResultantPSO.
     956             :  */
     957      605720 : static bool pso_is_supported(struct ldb_context *ldb, struct ldb_message *msg)
     958             : {
     959             :         int functional_level;
     960             :         uint32_t uac;
     961             :         uint32_t user_rid;
     962             : 
     963      605720 :         functional_level = dsdb_functional_level(ldb);
     964      605720 :         if (functional_level < DS_DOMAIN_FUNCTION_2008) {
     965       51050 :                 return false;
     966             :         }
     967             : 
     968             :         /* msDS-ResultantPSO is only supported for user objects */
     969      554661 :         if (!ldb_match_msg_objectclass(msg, "user")) {
     970           1 :                 return false;
     971             :         }
     972             : 
     973             :         /* ...and only if the ADS_UF_NORMAL_ACCOUNT bit is set */
     974      554660 :         uac = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
     975      554660 :         if (!(uac & UF_NORMAL_ACCOUNT)) {
     976       19526 :                 return false;
     977             :         }
     978             : 
     979             :         /* skip it if it's the special KRBTGT default account */
     980      534426 :         user_rid = samdb_result_rid_from_sid(msg, msg, "objectSid", 0);
     981      534426 :         if (user_rid == DOMAIN_RID_KRBTGT) {
     982      235827 :                 return false;
     983             :         }
     984             : 
     985             :         /* ...or if it's a special KRBTGT account for an RODC KDC */
     986      290957 :         if (ldb_msg_find_ldb_val(msg, "msDS-SecondaryKrbTgtNumber") != NULL) {
     987       14858 :                 return false;
     988             :         }
     989             : 
     990      276099 :         return true;
     991             : }
     992             : 
     993             : /*
     994             :  * Returns the number of PSO objects that exist in the DB
     995             :  */
     996      273816 : static int get_pso_count(struct ldb_module *module, TALLOC_CTX *mem_ctx,
     997             :                          struct ldb_request *parent, int *pso_count)
     998             : {
     999             :         static const char * const attrs[] = { NULL };
    1000             :         int ret;
    1001      273816 :         struct ldb_dn *domain_dn = NULL;
    1002      273816 :         struct ldb_dn *psc_dn = NULL;
    1003      273816 :         struct ldb_result *res = NULL;
    1004      273816 :         struct ldb_context *ldb = ldb_module_get_ctx(module);
    1005             : 
    1006      273816 :         *pso_count = 0;
    1007      273816 :         domain_dn = ldb_get_default_basedn(ldb);
    1008      273816 :         psc_dn = ldb_dn_new_fmt(mem_ctx, ldb,
    1009             :                                 "CN=Password Settings Container,CN=System,%s",
    1010             :                                 ldb_dn_get_linearized(domain_dn));
    1011      273816 :         if (psc_dn == NULL) {
    1012           0 :                 return ldb_oom(ldb);
    1013             :         }
    1014             : 
    1015             :         /* get the number of PSO children */
    1016      273816 :         ret = dsdb_module_search(module, mem_ctx, &res, psc_dn,
    1017             :                                  LDB_SCOPE_ONELEVEL, attrs,
    1018             :                                  DSDB_FLAG_NEXT_MODULE, parent,
    1019             :                                  "(objectClass=msDS-PasswordSettings)");
    1020             : 
    1021             :         /*
    1022             :          * Just ignore PSOs if the container doesn't exist. This is a weird
    1023             :          * corner-case where the AD DB was created from a pre-2008 base schema,
    1024             :          * and then the FL was manually upgraded.
    1025             :          */
    1026      273816 :         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
    1027           0 :                 DBG_NOTICE("No Password Settings Container exists\n");
    1028           0 :                 return LDB_SUCCESS;
    1029             :         }
    1030             : 
    1031      273816 :         if (ret != LDB_SUCCESS) {
    1032           0 :                 return ret;
    1033             :         }
    1034             : 
    1035      273816 :         *pso_count = res->count;
    1036      273816 :         talloc_free(res);
    1037      273816 :         talloc_free(psc_dn);
    1038             : 
    1039      273816 :         return LDB_SUCCESS;
    1040             : }
    1041             : 
    1042             : /*
    1043             :  * Compares two PSO objects returned by a search, to work out the better PSO.
    1044             :  * The PSO with the lowest precedence is better, otherwise (if the precedence
    1045             :  * is equal) the PSO with the lower GUID wins.
    1046             :  */
    1047         669 : static int pso_compare(struct ldb_message **m1, struct ldb_message **m2)
    1048             : {
    1049             :         uint32_t prec1;
    1050             :         uint32_t prec2;
    1051             : 
    1052         669 :         prec1 = ldb_msg_find_attr_as_uint(*m1, "msDS-PasswordSettingsPrecedence",
    1053             :                                           0xffffffff);
    1054         669 :         prec2 = ldb_msg_find_attr_as_uint(*m2, "msDS-PasswordSettingsPrecedence",
    1055             :                                           0xffffffff);
    1056             : 
    1057             :         /* if precedence is equal, use the lowest GUID */
    1058         669 :         if (prec1 == prec2) {
    1059         141 :                 struct GUID guid1 = samdb_result_guid(*m1, "objectGUID");
    1060         141 :                 struct GUID guid2 = samdb_result_guid(*m2, "objectGUID");
    1061             : 
    1062         141 :                 return ndr_guid_compare(&guid1, &guid2);
    1063             :         } else {
    1064         528 :                 return prec1 - prec2;
    1065             :         }
    1066             : }
    1067             : 
    1068             : /*
    1069             :  * Search for PSO objects that apply to the object SIDs specified
    1070             :  */
    1071        2103 : static int pso_search_by_sids(struct ldb_module *module, TALLOC_CTX *mem_ctx,
    1072             :                               struct ldb_request *parent,
    1073             :                               struct dom_sid *sid_array, unsigned int num_sids,
    1074             :                               struct ldb_result **result)
    1075             : {
    1076             :         int ret;
    1077             :         int i;
    1078        2103 :         struct ldb_context *ldb = ldb_module_get_ctx(module);
    1079        2103 :         char *sid_filter = NULL;
    1080        2103 :         struct ldb_dn *domain_dn = NULL;
    1081        2103 :         struct ldb_dn *psc_dn = NULL;
    1082        2103 :         const char *attrs[] = {
    1083             :                 "msDS-PasswordSettingsPrecedence",
    1084             :                 "objectGUID",
    1085             :                 "msDS-LockoutDuration",
    1086             :                 "msDS-MaximumPasswordAge",
    1087             :                 NULL
    1088             :         };
    1089             : 
    1090             :         /* build a query for PSO objects that apply to any of the SIDs given */
    1091        2103 :         sid_filter = talloc_strdup(mem_ctx, "");
    1092             : 
    1093        6678 :         for (i = 0; sid_filter && i < num_sids; i++) {
    1094             :                 struct dom_sid_buf sid_buf;
    1095             : 
    1096        4575 :                 sid_filter = talloc_asprintf_append(
    1097             :                         sid_filter,
    1098             :                         "(msDS-PSOAppliesTo=<SID=%s>)",
    1099        4575 :                         dom_sid_str_buf(&sid_array[i], &sid_buf));
    1100             :         }
    1101             : 
    1102        2103 :         if (sid_filter == NULL) {
    1103           0 :                 return ldb_oom(ldb);
    1104             :         }
    1105             : 
    1106             :         /* only PSOs located in the Password Settings Container are valid */
    1107        2103 :         domain_dn = ldb_get_default_basedn(ldb);
    1108        2103 :         psc_dn = ldb_dn_new_fmt(mem_ctx, ldb,
    1109             :                                 "CN=Password Settings Container,CN=System,%s",
    1110             :                                 ldb_dn_get_linearized(domain_dn));
    1111        2103 :         if (psc_dn == NULL) {
    1112           0 :                 return ldb_oom(ldb);
    1113             :         }
    1114             : 
    1115        2103 :         ret = dsdb_module_search(module, mem_ctx, result, psc_dn,
    1116             :                                  LDB_SCOPE_ONELEVEL, attrs,
    1117             :                                  DSDB_FLAG_NEXT_MODULE, parent,
    1118             :                                  "(&(objectClass=msDS-PasswordSettings)(|%s))",
    1119             :                                  sid_filter);
    1120        2103 :         talloc_free(sid_filter);
    1121        2103 :         return ret;
    1122             : }
    1123             : 
    1124             : /*
    1125             :  * Returns the best PSO object that applies to the object SID(s) specified
    1126             :  */
    1127        2103 : static int pso_find_best(struct ldb_module *module, TALLOC_CTX *mem_ctx,
    1128             :                          struct ldb_request *parent, struct dom_sid *sid_array,
    1129             :                          unsigned int num_sids, struct ldb_message **best_pso)
    1130             : {
    1131        2103 :         struct ldb_result *res = NULL;
    1132             :         int ret;
    1133             : 
    1134        2103 :         *best_pso = NULL;
    1135             : 
    1136             :         /* find any PSOs that apply to the SIDs specified */
    1137        2103 :         ret = pso_search_by_sids(module, mem_ctx, parent, sid_array, num_sids,
    1138             :                                  &res);
    1139        2103 :         if (ret != LDB_SUCCESS) {
    1140           0 :                 DBG_ERR("Error %d retrieving PSO for SID(s)\n", ret);
    1141           0 :                 return ret;
    1142             :         }
    1143             : 
    1144             :         /* sort the list so that the best PSO is first */
    1145        2103 :         TYPESAFE_QSORT(res->msgs, res->count, pso_compare);
    1146             : 
    1147        2103 :         if (res->count > 0) {
    1148        1498 :                 *best_pso = res->msgs[0];
    1149             :         }
    1150             : 
    1151        2103 :         return LDB_SUCCESS;
    1152             : }
    1153             : 
    1154             : /*
    1155             :  * Determines the Password Settings Object (PSO) that applies to the given user
    1156             :  */
    1157      605720 : static int get_pso_for_user(struct ldb_module *module,
    1158             :                             struct ldb_message *user_msg,
    1159             :                             struct ldb_request *parent,
    1160             :                             struct ldb_message **pso_msg)
    1161             : {
    1162             :         bool pso_supported;
    1163      605720 :         struct dom_sid *groupSIDs = NULL;
    1164      605720 :         unsigned int num_groupSIDs = 0;
    1165      605720 :         struct ldb_context *ldb = ldb_module_get_ctx(module);
    1166      605720 :         struct ldb_message *best_pso = NULL;
    1167      605720 :         struct ldb_dn *pso_dn = NULL;
    1168             :         int ret;
    1169      605720 :         struct ldb_message_element *el = NULL;
    1170      605720 :         TALLOC_CTX *tmp_ctx = NULL;
    1171      605720 :         int pso_count = 0;
    1172      605720 :         struct ldb_result *res = NULL;
    1173             :         static const char *attrs[] = {
    1174             :                 "msDS-LockoutDuration",
    1175             :                 "msDS-MaximumPasswordAge",
    1176             :                 NULL
    1177             :         };
    1178             : 
    1179      605720 :         *pso_msg = NULL;
    1180             : 
    1181             :         /* first, check msDS-ResultantPSO is supported for this object */
    1182      605720 :         pso_supported = pso_is_supported(ldb, user_msg);
    1183             : 
    1184      605720 :         if (!pso_supported) {
    1185      321262 :                 return LDB_SUCCESS;
    1186             :         }
    1187             : 
    1188      276099 :         tmp_ctx = talloc_new(user_msg);
    1189             : 
    1190             :         /*
    1191             :          * Several different constructed attributes try to use the PSO info. If
    1192             :          * we've already constructed the msDS-ResultantPSO for this user, we can
    1193             :          * just re-use the result, rather than calculating it from scratch again
    1194             :          */
    1195      276099 :         pso_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, user_msg,
    1196             :                                          "msDS-ResultantPSO");
    1197             : 
    1198      276099 :         if (pso_dn != NULL) {
    1199        1037 :                 ret = dsdb_module_search_dn(module, tmp_ctx, &res, pso_dn,
    1200             :                                             attrs, DSDB_FLAG_NEXT_MODULE,
    1201             :                                             parent);
    1202        1037 :                 if (ret != LDB_SUCCESS) {
    1203           0 :                         DBG_ERR("Error %d retrieving PSO %s\n", ret,
    1204             :                                 ldb_dn_get_linearized(pso_dn));
    1205           0 :                         talloc_free(tmp_ctx);
    1206           0 :                         return ret;
    1207             :                 }
    1208             : 
    1209        1037 :                 if (res->count == 1) {
    1210        1037 :                         *pso_msg = res->msgs[0];
    1211        1037 :                         return LDB_SUCCESS;
    1212             :                 }
    1213             :         }
    1214             : 
    1215             :         /*
    1216             :          * if any PSOs apply directly to the user, they are considered first
    1217             :          * before we check group membership PSOs
    1218             :          */
    1219      275062 :         el = ldb_msg_find_element(user_msg, "msDS-PSOApplied");
    1220             : 
    1221      275062 :         if (el != NULL && el->num_values > 0) {
    1222        1265 :                 struct dom_sid *user_sid = NULL;
    1223             : 
    1224             :                 /* lookup the best PSO object, based on the user's SID */
    1225        1265 :                 user_sid = samdb_result_dom_sid(tmp_ctx, user_msg, "objectSid");
    1226             : 
    1227        1265 :                 ret = pso_find_best(module, tmp_ctx, parent, user_sid, 1,
    1228             :                                     &best_pso);
    1229        1265 :                 if (ret != LDB_SUCCESS) {
    1230           0 :                         talloc_free(tmp_ctx);
    1231           0 :                         return ret;
    1232             :                 }
    1233             : 
    1234        1265 :                 if (best_pso != NULL) {
    1235        1246 :                         *pso_msg = best_pso;
    1236        1246 :                         return LDB_SUCCESS;
    1237             :                 }
    1238             :         }
    1239             : 
    1240             :         /*
    1241             :          * If no valid PSO applies directly to the user, then try its groups.
    1242             :          * The group expansion is expensive, so check there are actually
    1243             :          * PSOs in the DB first (which is a quick search). Note in the above
    1244             :          * cases we could tell that a PSO applied to the user, based on info
    1245             :          * already retrieved by the user search.
    1246             :          */
    1247      273816 :         ret = get_pso_count(module, tmp_ctx, parent, &pso_count);
    1248      273816 :         if (ret != LDB_SUCCESS) {
    1249           0 :                 DBG_ERR("Error %d determining PSOs in system\n", ret);
    1250           0 :                 talloc_free(tmp_ctx);
    1251           0 :                 return ret;
    1252             :         }
    1253             : 
    1254      273816 :         if (pso_count == 0) {
    1255      272978 :                 talloc_free(tmp_ctx);
    1256      272978 :                 return LDB_SUCCESS;
    1257             :         }
    1258             : 
    1259             :         /* Work out the SIDs of any account groups the user is a member of */
    1260         838 :         ret = get_group_sids(ldb, tmp_ctx, user_msg,
    1261             :                              "msDS-ResultantPSO", ACCOUNT_GROUPS,
    1262             :                              &groupSIDs, &num_groupSIDs);
    1263         838 :         if (ret != LDB_SUCCESS) {
    1264           0 :                 DBG_ERR("Error %d determining group SIDs for %s\n", ret,
    1265             :                         ldb_dn_get_linearized(user_msg->dn));
    1266           0 :                 talloc_free(tmp_ctx);
    1267           0 :                 return ret;
    1268             :         }
    1269             : 
    1270             :         /* lookup the best PSO that applies to any of these groups */
    1271         838 :         ret = pso_find_best(module, tmp_ctx, parent, groupSIDs,
    1272             :                             num_groupSIDs, &best_pso);
    1273         838 :         if (ret != LDB_SUCCESS) {
    1274           0 :                 talloc_free(tmp_ctx);
    1275           0 :                 return ret;
    1276             :         }
    1277             : 
    1278         838 :         *pso_msg = best_pso;
    1279         838 :         return LDB_SUCCESS;
    1280             : }
    1281             : 
    1282             : /*
    1283             :  * Constructs the msDS-ResultantPSO attribute, which is the DN of the Password
    1284             :  * Settings Object (PSO) that applies to that user.
    1285             :  */
    1286      124023 : static int construct_resultant_pso(struct ldb_module *module,
    1287             :                                    struct ldb_message *msg,
    1288             :                                    enum ldb_scope scope,
    1289             :                                    struct ldb_request *parent)
    1290             : {
    1291      124023 :         struct ldb_message *pso = NULL;
    1292             :         int ret;
    1293             : 
    1294             :         /* work out the PSO (if any) that applies to this user */
    1295      124023 :         ret = get_pso_for_user(module, msg, parent, &pso);
    1296      124023 :         if (ret != LDB_SUCCESS) {
    1297           0 :                 DBG_ERR("Couldn't determine PSO for %s\n",
    1298             :                         ldb_dn_get_linearized(msg->dn));
    1299           0 :                 return ret;
    1300             :         }
    1301             : 
    1302      124023 :         if (pso != NULL) {
    1303         648 :                 DBG_INFO("%s is resultant PSO for user %s\n",
    1304             :                          ldb_dn_get_linearized(pso->dn),
    1305             :                          ldb_dn_get_linearized(msg->dn));
    1306         648 :                 return ldb_msg_add_string(msg, "msDS-ResultantPSO",
    1307         648 :                                           ldb_dn_get_linearized(pso->dn));
    1308             :         }
    1309             : 
    1310             :         /* no PSO applies to this user */
    1311      120089 :         return LDB_SUCCESS;
    1312             : }
    1313             : 
    1314             : struct op_controls_flags {
    1315             :         bool sd;
    1316             :         bool bypassoperational;
    1317             : };
    1318             : 
    1319    75176537 : static bool check_keep_control_for_attribute(struct op_controls_flags* controls_flags, const char* attr) {
    1320    78159453 :         if (controls_flags->bypassoperational && ldb_attr_cmp(attr, "msDS-KeyVersionNumber") == 0 ) {
    1321           8 :                 return true;
    1322             :         }
    1323    75176529 :         return false;
    1324             : }
    1325             : 
    1326             : /*
    1327             :   a list of attribute names that should be substituted in the parse
    1328             :   tree before the search is done
    1329             : */
    1330             : static const struct {
    1331             :         const char *attr;
    1332             :         const char *replace;
    1333             : } parse_tree_sub[] = {
    1334             :         { "createTimeStamp", "whenCreated" },
    1335             :         { "modifyTimeStamp", "whenChanged" }
    1336             : };
    1337             : 
    1338             : 
    1339             : struct op_attributes_replace {
    1340             :         const char *attr;
    1341             :         const char *replace;
    1342             :         const char * const *extra_attrs;
    1343             :         int (*constructor)(struct ldb_module *, struct ldb_message *, enum ldb_scope, struct ldb_request *);
    1344             : };
    1345             : 
    1346             : /* the 'extra_attrs' required for msDS-ResultantPSO */
    1347             : #define RESULTANT_PSO_COMPUTED_ATTRS \
    1348             :         "msDS-PSOApplied", \
    1349             :         "userAccountControl", \
    1350             :         "objectSid", \
    1351             :         "msDS-SecondaryKrbTgtNumber", \
    1352             :         "primaryGroupID"
    1353             : 
    1354             : /*
    1355             :  * any other constructed attributes that want to work out the PSO also need to
    1356             :  * include objectClass (this gets included via 'replace' for msDS-ResultantPSO)
    1357             :  */
    1358             : #define PSO_ATTR_DEPENDENCIES \
    1359             :         RESULTANT_PSO_COMPUTED_ATTRS, \
    1360             :         "objectClass"
    1361             : 
    1362             : static const char *objectSid_attr[] =
    1363             : {
    1364             :         "objectSid",
    1365             :         NULL
    1366             : };
    1367             : 
    1368             : 
    1369             : static const char *objectCategory_attr[] =
    1370             : {
    1371             :         "objectCategory",
    1372             :         NULL
    1373             : };
    1374             : 
    1375             : 
    1376             : static const char *user_account_control_computed_attrs[] =
    1377             : {
    1378             :         "lockoutTime",
    1379             :         "pwdLastSet",
    1380             :         PSO_ATTR_DEPENDENCIES,
    1381             :         NULL
    1382             : };
    1383             : 
    1384             : 
    1385             : static const char *user_password_expiry_time_computed_attrs[] =
    1386             : {
    1387             :         "pwdLastSet",
    1388             :         PSO_ATTR_DEPENDENCIES,
    1389             :         NULL
    1390             : };
    1391             : 
    1392             : static const char *resultant_pso_computed_attrs[] =
    1393             : {
    1394             :         RESULTANT_PSO_COMPUTED_ATTRS,
    1395             :         NULL
    1396             : };
    1397             : 
    1398             : /*
    1399             :   a list of attribute names that are hidden, but can be searched for
    1400             :   using another (non-hidden) name to produce the correct result
    1401             : */
    1402             : static const struct op_attributes_replace search_sub[] = {
    1403             :         { "createTimeStamp", "whenCreated", NULL , NULL },
    1404             :         { "modifyTimeStamp", "whenChanged", NULL , construct_modifyTimeStamp},
    1405             :         { "structuralObjectClass", "objectClass", NULL , NULL },
    1406             :         { "canonicalName", NULL, NULL , construct_canonical_name },
    1407             :         { "primaryGroupToken", "objectClass", objectSid_attr, construct_primary_group_token },
    1408             :         { "tokenGroups", "primaryGroupID", objectSid_attr, construct_token_groups },
    1409             :         { "tokenGroupsNoGCAcceptable", "primaryGroupID", objectSid_attr, construct_token_groups_no_gc},
    1410             :         { "tokenGroupsGlobalAndUniversal", "primaryGroupID", objectSid_attr, construct_global_universal_token_groups },
    1411             :         { "parentGUID", NULL, NULL, construct_parent_guid },
    1412             :         { "subSchemaSubEntry", NULL, NULL, construct_subschema_subentry },
    1413             :         { "msDS-isRODC", "objectClass", objectCategory_attr, construct_msds_isrodc },
    1414             :         { "msDS-KeyVersionNumber", "replPropertyMetaData", NULL, construct_msds_keyversionnumber },
    1415             :         { "msDS-User-Account-Control-Computed", "userAccountControl", user_account_control_computed_attrs,
    1416             :           construct_msds_user_account_control_computed },
    1417             :         { "msDS-UserPasswordExpiryTimeComputed", "userAccountControl", user_password_expiry_time_computed_attrs,
    1418             :           construct_msds_user_password_expiry_time_computed },
    1419             :         { "msDS-ResultantPSO", "objectClass", resultant_pso_computed_attrs,
    1420             :           construct_resultant_pso }
    1421             : };
    1422             : 
    1423             : 
    1424             : enum op_remove {
    1425             :         OPERATIONAL_REMOVE_ALWAYS, /* remove always */
    1426             :         OPERATIONAL_REMOVE_UNASKED,/* remove if not requested */
    1427             :         OPERATIONAL_SD_FLAGS,      /* show if SD_FLAGS_OID set, or asked for */
    1428             :         OPERATIONAL_REMOVE_UNLESS_CONTROL        /* remove always unless an adhoc control has been specified */
    1429             : };
    1430             : 
    1431             : /*
    1432             :   a list of attributes that may need to be removed from the
    1433             :   underlying db return
    1434             : 
    1435             :   Some of these are attributes that were once stored, but are now calculated
    1436             : */
    1437             : struct op_attributes_operations {
    1438             :         const char *attr;
    1439             :         enum op_remove op;
    1440             : };
    1441             : 
    1442             : static const struct op_attributes_operations operational_remove[] = {
    1443             :         { "nTSecurityDescriptor",    OPERATIONAL_SD_FLAGS },
    1444             :         { "msDS-KeyVersionNumber",   OPERATIONAL_REMOVE_UNLESS_CONTROL  },
    1445             :         { "parentGUID",              OPERATIONAL_REMOVE_ALWAYS  },
    1446             :         { "replPropertyMetaData",    OPERATIONAL_REMOVE_UNASKED },
    1447             : #define _SEP ,OPERATIONAL_REMOVE_UNASKED},{
    1448             :         { DSDB_SECRET_ATTRIBUTES_EX(_SEP), OPERATIONAL_REMOVE_UNASKED }
    1449             : };
    1450             : 
    1451             : 
    1452             : /*
    1453             :   post process a search result record. For any search_sub[] attributes that were
    1454             :   asked for, we need to call the appropriate copy routine to copy the result
    1455             :   into the message, then remove any attributes that we added to the search but
    1456             :   were not asked for by the user
    1457             : */
    1458    60810865 : static int operational_search_post_process(struct ldb_module *module,
    1459             :                                            struct ldb_message *msg,
    1460             :                                            enum ldb_scope scope,
    1461             :                                            const char * const *attrs_from_user,
    1462             :                                            const char * const *attrs_searched_for,
    1463             :                                            struct op_controls_flags* controls_flags,
    1464             :                                            struct op_attributes_operations *list,
    1465             :                                            unsigned int list_size,
    1466             :                                            struct op_attributes_replace *list_replace,
    1467             :                                            unsigned int list_replace_size,
    1468             :                                            struct ldb_request *parent)
    1469             : {
    1470             :         struct ldb_context *ldb;
    1471    60810865 :         unsigned int i, a = 0;
    1472    60810865 :         bool constructed_attributes = false;
    1473             : 
    1474    60810865 :         ldb = ldb_module_get_ctx(module);
    1475             : 
    1476             :         /* removed any attrs that should not be shown to the user */
    1477  1135219317 :         for (i=0; i < list_size; i++) {
    1478  1074408452 :                 ldb_msg_remove_attr(msg, list[i].attr);
    1479             :         }
    1480             : 
    1481    60686163 :         for (a=0; a < list_replace_size; a++) {
    1482     1673085 :                 if (check_keep_control_for_attribute(controls_flags,
    1483     1646087 :                                                      list_replace[a].attr)) {
    1484           0 :                         continue;
    1485             :                 }
    1486             : 
    1487             :                 /* construct the new attribute, using either a supplied
    1488             :                         constructor or a simple copy */
    1489     1646087 :                 constructed_attributes = true;
    1490     1646087 :                 if (list_replace[a].constructor != NULL) {
    1491     1646085 :                         if (list_replace[a].constructor(module, msg, scope, parent) != LDB_SUCCESS) {
    1492           0 :                                 goto failed;
    1493             :                         }
    1494           4 :                 } else if (ldb_msg_copy_attr(msg,
    1495           2 :                                              list_replace[a].replace,
    1496           2 :                                              list_replace[a].attr) != LDB_SUCCESS) {
    1497           0 :                         goto failed;
    1498             :                 }
    1499             :         }
    1500             : 
    1501             :         /* Deletion of the search helper attributes are needed if:
    1502             :          * - we generated constructed attributes and
    1503             :          * - we aren't requesting all attributes
    1504             :          */
    1505    60810865 :         if ((constructed_attributes) && (!ldb_attr_in_list(attrs_from_user, "*"))) {
    1506     1532948 :                 for (i=0; i < list_replace_size; i++) {
    1507             :                         /* remove the added search helper attributes, unless
    1508             :                          * they were asked for by the user */
    1509     2114671 :                         if (list_replace[i].replace != NULL &&
    1510     1009513 :                             !ldb_attr_in_list(attrs_from_user, list_replace[i].replace)) {
    1511      307703 :                                 ldb_msg_remove_attr(msg, list_replace[i].replace);
    1512             :                         }
    1513     1105158 :                         if (list_replace[i].extra_attrs != NULL) {
    1514             :                                 unsigned int j;
    1515     5758584 :                                 for (j=0; list_replace[i].extra_attrs[j]; j++) {
    1516     5037416 :                                         if (!ldb_attr_in_list(attrs_from_user, list_replace[i].extra_attrs[j])) {
    1517     1359042 :                                                 ldb_msg_remove_attr(msg, list_replace[i].extra_attrs[j]);
    1518             :                                         }
    1519             :                                 }
    1520             :                         }
    1521             :                 }
    1522             :         }
    1523             : 
    1524    59040076 :         return 0;
    1525             : 
    1526           0 : failed:
    1527           0 :         ldb_debug_set(ldb, LDB_DEBUG_WARNING,
    1528             :                       "operational_search_post_process failed for attribute '%s' - %s",
    1529           0 :                       list_replace[a].attr, ldb_errstring(ldb));
    1530           0 :         return -1;
    1531             : }
    1532             : 
    1533             : /*
    1534             :   hook search operations
    1535             : */
    1536             : 
    1537             : struct operational_context {
    1538             :         struct ldb_module *module;
    1539             :         struct ldb_request *req;
    1540             :         enum ldb_scope scope;
    1541             :         const char * const *attrs;
    1542             :         struct op_controls_flags* controls_flags;
    1543             :         struct op_attributes_operations *list_operations;
    1544             :         unsigned int list_operations_size;
    1545             :         struct op_attributes_replace *attrs_to_replace;
    1546             :         unsigned int attrs_to_replace_size;
    1547             : };
    1548             : 
    1549    86315455 : static int operational_callback(struct ldb_request *req, struct ldb_reply *ares)
    1550             : {
    1551             :         struct operational_context *ac;
    1552             :         int ret;
    1553             : 
    1554    86315455 :         ac = talloc_get_type(req->context, struct operational_context);
    1555             : 
    1556    86315455 :         if (!ares) {
    1557           0 :                 return ldb_module_done(ac->req, NULL, NULL,
    1558             :                                         LDB_ERR_OPERATIONS_ERROR);
    1559             :         }
    1560    86315455 :         if (ares->error != LDB_SUCCESS) {
    1561      338820 :                 return ldb_module_done(ac->req, ares->controls,
    1562             :                                         ares->response, ares->error);
    1563             :         }
    1564             : 
    1565    85976635 :         switch (ares->type) {
    1566    60810865 :         case LDB_REPLY_ENTRY:
    1567             :                 /* for each record returned post-process to add any derived
    1568             :                    attributes that have been asked for */
    1569    60810865 :                 ret = operational_search_post_process(ac->module,
    1570             :                                                       ares->message,
    1571             :                                                       ac->scope,
    1572             :                                                       ac->attrs,
    1573             :                                                       req->op.search.attrs,
    1574             :                                                       ac->controls_flags,
    1575             :                                                       ac->list_operations,
    1576             :                                                       ac->list_operations_size,
    1577             :                                                       ac->attrs_to_replace,
    1578             :                                                       ac->attrs_to_replace_size,
    1579             :                                                       req);
    1580    60810865 :                 if (ret != 0) {
    1581           0 :                         return ldb_module_done(ac->req, NULL, NULL,
    1582             :                                                 LDB_ERR_OPERATIONS_ERROR);
    1583             :                 }
    1584    60810865 :                 return ldb_module_send_entry(ac->req, ares->message, ares->controls);
    1585             : 
    1586     2425559 :         case LDB_REPLY_REFERRAL:
    1587     2425559 :                 return ldb_module_send_referral(ac->req, ares->referral);
    1588             : 
    1589    22740211 :         case LDB_REPLY_DONE:
    1590             : 
    1591    22740211 :                 return ldb_module_done(ac->req, ares->controls,
    1592             :                                         ares->response, LDB_SUCCESS);
    1593             :         }
    1594             : 
    1595           0 :         talloc_free(ares);
    1596           0 :         return LDB_SUCCESS;
    1597             : }
    1598             : 
    1599    23122128 : static struct op_attributes_operations* operation_get_op_list(TALLOC_CTX *ctx,
    1600             :                                                               const char* const* attrs,
    1601             :                                                               const char* const* searched_attrs,
    1602             :                                                               struct op_controls_flags* controls_flags)
    1603             : {
    1604    23122128 :         int idx = 0;
    1605             :         int i;
    1606    23122128 :         struct op_attributes_operations *list = talloc_zero_array(ctx,
    1607             :                                                                   struct op_attributes_operations,
    1608             :                                                                   ARRAY_SIZE(operational_remove) + 1);
    1609             : 
    1610    23122128 :         if (list == NULL) {
    1611           0 :                 return NULL;
    1612             :         }
    1613             : 
    1614   438165852 :         for (i=0; i<ARRAY_SIZE(operational_remove); i++) {
    1615   416198304 :                 switch (operational_remove[i].op) {
    1616   346831920 :                 case OPERATIONAL_REMOVE_UNASKED:
    1617   346831920 :                         if (ldb_attr_in_list(attrs, operational_remove[i].attr)) {
    1618    13543797 :                                 continue;
    1619             :                         }
    1620   333288123 :                         if (ldb_attr_in_list(searched_attrs, operational_remove[i].attr)) {
    1621      269685 :                                 continue;
    1622             :                         }
    1623   333018438 :                         list[idx].attr = operational_remove[i].attr;
    1624   333018438 :                         list[idx].op = OPERATIONAL_REMOVE_UNASKED;
    1625   333018438 :                         idx++;
    1626   333018438 :                         break;
    1627             : 
    1628    23122128 :                 case OPERATIONAL_REMOVE_ALWAYS:
    1629    23122128 :                         list[idx].attr = operational_remove[i].attr;
    1630    23122128 :                         list[idx].op = OPERATIONAL_REMOVE_ALWAYS;
    1631    23122128 :                         idx++;
    1632    23122128 :                         break;
    1633             : 
    1634    23122128 :                 case OPERATIONAL_REMOVE_UNLESS_CONTROL:
    1635    24276708 :                         if (!check_keep_control_for_attribute(controls_flags, operational_remove[i].attr)) {
    1636    23122124 :                                 list[idx].attr = operational_remove[i].attr;
    1637    23122124 :                                 list[idx].op = OPERATIONAL_REMOVE_UNLESS_CONTROL;
    1638    23122124 :                                 idx++;
    1639             :                         }
    1640    21967548 :                         break;
    1641             : 
    1642    23122128 :                 case OPERATIONAL_SD_FLAGS:
    1643    23122128 :                         if (ldb_attr_in_list(attrs, operational_remove[i].attr)) {
    1644     5935455 :                                 continue;
    1645             :                         }
    1646    17186673 :                         if (controls_flags->sd) {
    1647     1102087 :                                 if (attrs == NULL) {
    1648       20448 :                                         continue;
    1649             :                                 }
    1650     1081639 :                                 if (attrs[0] == NULL) {
    1651           0 :                                         continue;
    1652             :                                 }
    1653     1081639 :                                 if (ldb_attr_in_list(attrs, "*")) {
    1654      365419 :                                         continue;
    1655             :                                 }
    1656             :                         }
    1657    16800806 :                         list[idx].attr = operational_remove[i].attr;
    1658    16800806 :                         list[idx].op = OPERATIONAL_SD_FLAGS;
    1659    16800806 :                         idx++;
    1660    16800806 :                         break;
    1661             :                 }
    1662             :         }
    1663             : 
    1664    21967548 :         return list;
    1665             : }
    1666             : 
    1667    28525305 : static int operational_search(struct ldb_module *module, struct ldb_request *req)
    1668             : {
    1669             :         struct ldb_context *ldb;
    1670             :         struct operational_context *ac;
    1671             :         struct ldb_request *down_req;
    1672    28525305 :         const char **search_attrs = NULL;
    1673             :         unsigned int i, a;
    1674             :         int ret;
    1675             : 
    1676             :         /* There are no operational attributes on special DNs */
    1677    28525305 :         if (ldb_dn_is_special(req->op.search.base)) {
    1678     5403177 :                 return ldb_next_request(module, req);
    1679             :         }
    1680             : 
    1681    23122128 :         ldb = ldb_module_get_ctx(module);
    1682             : 
    1683    23122128 :         ac = talloc(req, struct operational_context);
    1684    23122128 :         if (ac == NULL) {
    1685           0 :                 return ldb_oom(ldb);
    1686             :         }
    1687             : 
    1688    23122128 :         ac->module = module;
    1689    23122128 :         ac->req = req;
    1690    23122128 :         ac->scope = req->op.search.scope;
    1691    23122128 :         ac->attrs = req->op.search.attrs;
    1692             : 
    1693             :         /*  FIXME: We must copy the tree and keep the original
    1694             :          *  unmodified. SSS */
    1695             :         /* replace any attributes in the parse tree that are
    1696             :            searchable, but are stored using a different name in the
    1697             :            backend */
    1698    69366384 :         for (i=0;i<ARRAY_SIZE(parse_tree_sub);i++) {
    1699    46244256 :                 ldb_parse_tree_attr_replace(req->op.search.tree,
    1700     6973742 :                                             parse_tree_sub[i].attr,
    1701     6973742 :                                             parse_tree_sub[i].replace);
    1702             :         }
    1703             : 
    1704    23122128 :         ac->controls_flags = talloc(ac, struct op_controls_flags);
    1705             :         /* remember if the SD_FLAGS_OID was set */
    1706    23122128 :         ac->controls_flags->sd = (ldb_request_get_control(req, LDB_CONTROL_SD_FLAGS_OID) != NULL);
    1707             :         /* remember if the LDB_CONTROL_BYPASS_OPERATIONAL_OID */
    1708    42757385 :         ac->controls_flags->bypassoperational =
    1709    42757385 :                 (ldb_request_get_control(req, LDB_CONTROL_BYPASS_OPERATIONAL_OID) != NULL);
    1710             : 
    1711    23122128 :         ac->attrs_to_replace = NULL;
    1712    23122128 :         ac->attrs_to_replace_size = 0;
    1713             :         /* in the list of attributes we are looking for, rename any
    1714             :            attributes to the alias for any hidden attributes that can
    1715             :            be fetched directly using non-hidden names.
    1716             :            Note that order here can affect performance, e.g. we should process
    1717             :            msDS-ResultantPSO before msDS-User-Account-Control-Computed (as the
    1718             :            latter is also dependent on the PSO information) */
    1719    76513366 :         for (a=0;ac->attrs && ac->attrs[a];a++) {
    1720    53391238 :                 if (check_keep_control_for_attribute(ac->controls_flags, ac->attrs[a])) {
    1721           4 :                         continue;
    1722             :                 }
    1723   852458406 :                 for (i=0;i<ARRAY_SIZE(search_sub);i++) {
    1724             : 
    1725   800868510 :                         if (ldb_attr_cmp(ac->attrs[a], search_sub[i].attr) != 0 ) {
    1726   798893360 :                                 continue;
    1727             :                         }
    1728             : 
    1729     1975150 :                         ac->attrs_to_replace = talloc_realloc(ac,
    1730             :                                                               ac->attrs_to_replace,
    1731             :                                                               struct op_attributes_replace,
    1732             :                                                               ac->attrs_to_replace_size + 1);
    1733             : 
    1734     1975150 :                         ac->attrs_to_replace[ac->attrs_to_replace_size] = search_sub[i];
    1735     1975150 :                         ac->attrs_to_replace_size++;
    1736     1975150 :                         if (!search_sub[i].replace) {
    1737      961598 :                                 continue;
    1738             :                         }
    1739             : 
    1740     1013552 :                         if (search_sub[i].extra_attrs && search_sub[i].extra_attrs[0]) {
    1741             :                                 unsigned int j;
    1742             :                                 const char **search_attrs2;
    1743             :                                 /* Only adds to the end of the list */
    1744     5782310 :                                 for (j = 0; search_sub[i].extra_attrs[j]; j++) {
    1745     5058083 :                                         search_attrs2 = ldb_attr_list_copy_add(req, search_attrs
    1746             :                                                                                ? search_attrs
    1747             :                                                                                : ac->attrs, 
    1748     4925749 :                                                                                search_sub[i].extra_attrs[j]);
    1749     5058083 :                                         if (search_attrs2 == NULL) {
    1750           0 :                                                 return ldb_operr(ldb);
    1751             :                                         }
    1752             :                                         /* may be NULL, talloc_free() doesn't mind */
    1753     5058083 :                                         talloc_free(search_attrs);
    1754     5058083 :                                         search_attrs = search_attrs2;
    1755             :                                 }
    1756             :                         }
    1757             : 
    1758     1013552 :                         if (!search_attrs) {
    1759      162850 :                                 search_attrs = ldb_attr_list_copy(req, ac->attrs);
    1760      162850 :                                 if (search_attrs == NULL) {
    1761           0 :                                         return ldb_operr(ldb);
    1762             :                                 }
    1763             :                         }
    1764             :                         /* Despite the ldb_attr_list_copy_add, this is safe as that fn only adds to the end */
    1765     1013552 :                         search_attrs[a] = search_sub[i].replace;
    1766             :                 }
    1767             :         }
    1768    23122128 :         ac->list_operations = operation_get_op_list(ac, ac->attrs,
    1769             :                                                     search_attrs == NULL?req->op.search.attrs:search_attrs,
    1770             :                                                     ac->controls_flags);
    1771    21967548 :         ac->list_operations_size = 0;
    1772    23122128 :         i = 0;
    1773             : 
    1774   438820881 :         while (ac->list_operations && ac->list_operations[i].attr != NULL) {
    1775   396063496 :                 i++;
    1776             :         }
    1777    23122128 :         ac->list_operations_size = i;
    1778    23122128 :         ret = ldb_build_search_req_ex(&down_req, ldb, ac,
    1779             :                                         req->op.search.base,
    1780             :                                         req->op.search.scope,
    1781             :                                         req->op.search.tree,
    1782             :                                         /* use new set of attrs if any */
    1783             :                                         search_attrs == NULL?req->op.search.attrs:search_attrs,
    1784             :                                         req->controls,
    1785             :                                         ac, operational_callback,
    1786             :                                         req);
    1787    23122128 :         LDB_REQ_SET_LOCATION(down_req);
    1788    23122128 :         if (ret != LDB_SUCCESS) {
    1789           0 :                 return ldb_operr(ldb);
    1790             :         }
    1791             : 
    1792             :         /* perform the search */
    1793    23122128 :         return ldb_next_request(module, down_req);
    1794             : }
    1795             : 
    1796      132464 : static int operational_init(struct ldb_module *ctx)
    1797             : {
    1798             :         struct operational_data *data;
    1799             :         int ret;
    1800             : 
    1801      132464 :         ret = ldb_next_init(ctx);
    1802             : 
    1803      132464 :         if (ret != LDB_SUCCESS) {
    1804           0 :                 return ret;
    1805             :         }
    1806             : 
    1807      132464 :         data = talloc_zero(ctx, struct operational_data);
    1808      132464 :         if (!data) {
    1809           0 :                 return ldb_module_oom(ctx);
    1810             :         }
    1811             : 
    1812      132464 :         ldb_module_set_private(ctx, data);
    1813             : 
    1814      132464 :         return LDB_SUCCESS;
    1815             : }
    1816             : 
    1817             : static const struct ldb_module_ops ldb_operational_module_ops = {
    1818             :         .name              = "operational",
    1819             :         .search            = operational_search,
    1820             :         .init_context      = operational_init
    1821             : };
    1822             : 
    1823        5536 : int ldb_operational_module_init(const char *version)
    1824             : {
    1825        5536 :         LDB_MODULE_CHECK_VERSION(version);
    1826        5536 :         return ldb_register_module(&ldb_operational_module_ops);
    1827             : }

Generated by: LCOV version 1.13