/// <summary> /// Pages through LDAP results filtered by Linq spec. /// Caveats: /// (1) paging iterates through all prior pages - a limitation of LDAP, /// (2) sorting can only take one attribute, and that attribute must be /// indexed in LDAP, or the server-side sort will fail. /// </summary> /// <typeparam name="T">The mapped type.</typeparam> /// <param name="spec">The filter specification.</param> /// <param name="offsetPage">How many pages into the results. 0 = first page.</param> /// <param name="pageSize">Size of a page. Default = 10.</param> /// <param name="sortKeys">Sorting options.</param> /// <returns></returns> public virtual IEnumerable <T> PageWithPageControl <T>( Specification <T> spec, int offsetPage = 0, int pageSize = 10, SortKey[] sortKeys = null ) where T : IEntry, new() { ILinqSearchResponse <T> result = null; int curPage = 0; while (curPage++ <= offsetPage) { var search = new LinqSearchRequest <T>(DistinguishedName, spec.AsExpression(), Scope); var pageControl = new PageResultRequestControl(pageSize); var soc = new SearchOptionsControl(SearchOption.DomainScope); search.Controls.Add(pageControl); search.Controls.Add(soc); if (sortKeys != null) { var sortControl = new SortRequestControl(sortKeys); search.Controls.Add(sortControl); } result = Connection.SendRequest(search); } return(result?.Entries); }
public SearchRequest GetSearchRequest(string filter, SearchScope scope, string[] attribs, string domainName = null, string adsPath = null) { Domain targetDomain; try { targetDomain = GetDomain(domainName); } catch { Verbose($"Unable to contact domain {domainName}"); return(null); } domainName = targetDomain.Name; adsPath = adsPath?.Replace("LDAP://", "") ?? $"DC={domainName.Replace(".", ",DC=")}"; var request = new SearchRequest(adsPath, filter, scope, attribs); //Add our search options control var soc = new SearchOptionsControl(SearchOption.DomainScope); request.Controls.Add(soc); return(request); }
public static string GetSingleValue(LdapConnection conn, string filter, SearchScope scope, string[] attrsToReturn, string dn) { var request = new SearchRequest(dn, filter, scope, attrsToReturn); var searchControl = new SearchOptionsControl(); request.Controls.Add(searchControl); SearchResponse response; try { response = (SearchResponse)conn.SendRequest(request); foreach (SearchResultEntry entry in response.Entries) { return(entry.DistinguishedName); } return(null); } catch (Exception e) { Console.WriteLine("Unexpected error: {0}", e.Message); return(null); } }
internal static IEnumerable <SearchResultEntry> GetResponses(string dn, string filter, SearchScope scope, string[] attrsToReturn, bool useGC = false) { var connection = useGC ? ConnectGCLDAP() : ConnectLDAP(); var request = new SearchRequest(dn, filter, scope, attrsToReturn); // the size of each page var pageReqControl = new PageResultRequestControl(500); // turn off referral chasing so that data // from other partitions is not returned var searchControl = new SearchOptionsControl(SearchOption.DomainScope); //Unhandled Exception: System.ComponentModel.InvalidEnumArgumentException: //The value of argument 'value' (0) is invalid for Enum type 'SearchOption'. //var searchControl = new SearchOptionsControl(); request.Controls.Add(pageReqControl); request.Controls.Add(searchControl); while (true) { SearchResponse response; try { response = (SearchResponse)connection.SendRequest(request); } catch (Exception e) { //Console.WriteLine(e.StackTrace); Console.WriteLine("[X] ERROR: {0}", e.Message); yield break; } if (response.Controls.Length != 1 || !(response.Controls[0] is PageResultResponseControl)) { Console.WriteLine("The server does not support this advanced search operation"); yield break; } var pageResControl = (PageResultResponseControl)response.Controls[0]; //Console.WriteLine("\n[*] This page contains {0} response entries:\n", response.Entries.Count); foreach (SearchResultEntry entry in response.Entries) { yield return(entry); } if (pageResControl.Cookie.Length == 0) { break; } pageReqControl.Cookie = pageResControl.Cookie; } }
public AdElement[] GetEntriesWithAttributes(string distinguishedName, string request) { var searchRequest = new SearchRequest(distinguishedName, request, SearchScope.Subtree); PageResultRequestControl prc = new PageResultRequestControl(1000); SearchOptionsControl soc = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope); searchRequest.Controls.Add(prc); searchRequest.Controls.Add(soc); var result = new List <AdElement>(); do { SearchResponse searchResponse = null; Exception exc = null; for (int i = 0; i < 5; i++) { try { searchResponse = (SearchResponse)_LdapConnection.SendRequest(searchRequest, new TimeSpan(0, 2, 0)); i = 5; } catch (Exception ex) { exc = ex; } } if (searchResponse == null) { throw exc; } foreach (DirectoryControl control in searchResponse.Controls) { if (control is PageResultResponseControl) { //update the cookie for next set prc.Cookie = ((PageResultResponseControl)control).Cookie; break; } } //add them to our collection ILog log = LogManager.GetLogger("ContactProcessLog "); log.Info("1"); foreach (var entryObject in searchResponse.Entries) { var entry = (SearchResultEntry)entryObject; result.Add(new AdElement(entry)); } }while (prc.Cookie.Length != 0); return(result.ToArray()); }
public static List <string> AutenticaUsuario(string usuario, string senha) { List <string> retorno = new List <string>(); WebReturn <bool> retr = new WebReturn <bool>(); try { if (MODODESENVOLVIMENTO != 1) { LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(CAMINHO_LDAP, PORTA_LDAP)); con.SessionOptions.ProtocolVersion = 3; // con.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback((LdapConnection l, X509Certificate x) => { return(true); }); // con.Credential = new NetworkCredential(usuario, senha); con.AuthType = AuthType.Negotiate; // var ldapFilter = string.Format("(&(objectCategory=person)(objectClass=user)(&(sAMAccountName={0})))", usuario); // var getUserRequest = new SearchRequest(DISTINGUISHEDNAME_LDAP, ldapFilter, SearchScope.Subtree, new[] { "MemberOf" }) { SizeLimit = 1 }; // var SearchControl = new SearchOptionsControl(SearchOption.DomainScope); getUserRequest.Controls.Add(SearchControl); // var userResponse = (SearchResponse)con.SendRequest(getUserRequest); retorno.AddRange(ObterGruposRedeUsuario(userResponse.Entries[0])); } else { //retorno.Add("SMART.GESTAOACESSOSMART"); //retorno.Add("SMART.POS.GESTAOVISITA"); //retorno.Add("SMART.FINANCEIRO"); //retorno.Add("SMART.CENTRALCOMPRAS"); //retorno.Add("SMART.PORTAL.TECNOLOGIAINFO"); //return retorno; return(null); } } catch (Exception ex) { retr.Code = 1; retr.Message = ex.Message; Utilitarios.CriaLogErro(ex); Utilitarios.InserirLog(ex, System.Reflection.MethodInfo.GetCurrentMethod().Name, string.Join(";", System.Reflection.MethodInfo.GetCurrentMethod().GetParameters().Select(val => val.Name)), ex.GetType().Name, "ERRO AUTENTICAR USUARIO SISTEMA.!!"); return(new List <string>()); } return(retorno); }
internal SearchRequest GetRequest() { var root = $"DC={_domain.Name.Replace(".", ",DC=")}"; var request = new SearchRequest(root, "(&(sAMAccountType=805306368)(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))", SearchScope.Subtree, null); var soc = new SearchOptionsControl(SearchOption.DomainScope); request.Controls.Add(soc); return(request); }
public override void JustGronkIT() { string filter = "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"; string tartgetOU = @"yourdomain.com"; string[] attrs = { "sAMAccountName", "givenName", "sn", "initials", "description", "userPrincipalName", "distinguishedName", "extentionAttribute6", "departmentNumber", "wwwHomePage", "manager", "extensionName", "mail", "telephoneNumber" }; using (_LDAP = new LdapConnection(Properties.Settings.Default.Domain)) { myADUsers = new ADDataSet(); myADUsers.ADUsers.MinimumCapacity = 60000; myADUsers.ADUsers.CaseSensitive = false; try { SearchRequest request = new SearchRequest(tartgetOU, filter, System.DirectoryServices.Protocols.SearchScope.Subtree, attrs); PageResultRequestControl pageRequest = new PageResultRequestControl(5000); request.Controls.Add(pageRequest); SearchOptionsControl searchOptions = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope); request.Controls.Add(searchOptions); while (true) { SearchResponse searchResponse = (SearchResponse)_LDAP.SendRequest(request); PageResultResponseControl pageResponse = (PageResultResponseControl)searchResponse.Controls[0]; foreach (SearchResultEntry entry in searchResponse.Entries) { string _myUserid = ""; string _myUPN = ""; SearchResultAttributeCollection attributes = entry.Attributes; foreach (DirectoryAttribute attribute in attributes.Values) { if (attribute.Name.Equals("sAMAccountName")) { _myUserid = (string)attribute[0] ?? ""; _myUserid.Trim(); } if (attribute.Name.Equals("userPrincipalName")) { _myUPN = (string)attribute[0] ?? ""; _myUPN.Trim(); } //etc with each datum you return from AD } //foreach DirectoryAttribute //do something with all the above info, I put it into a dataset } //foreach SearchResultEntry if (pageResponse.Cookie.Length == 0) //check and see if there are more pages { break; //There are no more pages } pageRequest.Cookie = pageResponse.Cookie; } //while loop } //try catch {} } //using _LDAP } //JustGronkIT method
public void Ctor_Flags() { var control = new SearchOptionsControl(SearchOption.PhantomRoot); Assert.True(control.IsCritical); Assert.Equal(SearchOption.PhantomRoot, control.SearchOption); Assert.True(control.ServerSide); Assert.Equal("1.2.840.113556.1.4.1340", control.Type); Assert.Equal(new byte[] { 48, 132, 0, 0, 0, 3, 2, 1, 2 }, control.GetValue()); }
public void Ctor_Default() { var control = new SearchOptionsControl(); Assert.True(control.IsCritical); Assert.Equal(SearchOption.DomainScope, control.SearchOption); Assert.True(control.ServerSide); Assert.Equal("1.2.840.113556.1.4.1340", control.Type); Assert.Equal(new byte[] { 48, 132, 0, 0, 0, 3, 2, 1, 1 }, control.GetValue()); }
private void LoadDomains() { SearchRequest request = new SearchRequest(null, "(objectClass=domainDNS)", SearchScope.Subtree, new string[] { "canonicalName", "objectSid" }); PageResultRequestControl pagecookie = new PageResultRequestControl(1000); request.Controls.Add(pagecookie); SearchOptionsControl phantomcookie = new SearchOptionsControl(SearchOption.PhantomRoot); request.Controls.Add(phantomcookie); LdapDirectoryIdentifier ldapid = new LdapDirectoryIdentifier(ForestBase.DefaultDC.Name, 389, true, false); using (LdapConnector ldapcon = new LdapConnector(ldapid)) { if ((ForestBase.GivenCreds != null) && (ForestBase.GivenCreds.HasCreds)) { ldapcon.Credential = ForestBase.GivenCreds.NetCreds; } ldapcon.SessionOptions.ReferralChasing = ReferralChasingOptions.All; ldapcon.Bind(); SearchResponse response = (SearchResponse)ldapcon.SendRequest(request); foreach (SearchResultEntry entry in response.Entries) { if (entry.DistinguishedName.ToLowerInvariant() != ForestBase.RootDomainNamingContext.ToLowerInvariant()) { string domdns = null; entry.GetStringAttributeSafe("canonicalName", out domdns); domdns = domdns.TrimChar("/"); foreach (DomainControllerHelper dchelper in GetDcList(domdns, entry.DistinguishedName)) { StoreDC(dchelper, entry.DistinguishedName); } List <byte[]> bsids; entry.GetAttributeSafe("objectSid", out bsids); SecurityIdentifier dsid = new SecurityIdentifier(bsids[0], 0); ForestBase.DomainSids.AddSafe(entry.DistinguishedName, dsid.ToString()); } } } }
public void Ctor_Flags() { var control = new SearchOptionsControl(SearchOption.PhantomRoot); Assert.True(control.IsCritical); Assert.Equal(SearchOption.PhantomRoot, control.SearchOption); Assert.True(control.ServerSide); Assert.Equal("1.2.840.113556.1.4.1340", control.Type); var expected = (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) ? new byte[] { 48, 132, 0, 0, 0, 3, 2, 1, 2 } : new byte[] { 48, 3, 2, 1, 2 }; Assert.Equal(expected, control.GetValue()); }
internal void SetSearchRequest(String SearchRoot, String LdapFilter) { this.SearchRequest = new SearchRequest(); this.SearchRequest.DistinguishedName = SearchRoot; this.SearchRequest.Filter = LdapFilter; this.SearchRequest.Scope = SearchScope.Subtree; this.SearchRequest.Attributes.AddRange(this.Properties); this.PageRequest = new PageResultRequestControl(1000); this.SearchRequest.Controls.Add(this.PageRequest); SearchOptionsControl SearchOptions = new SearchOptionsControl(SearchOption.DomainScope); this.SearchRequest.Controls.Add(SearchOptions); }
/// <summary> /// Retrieves current state of LDAP database and reflects it to the CMS. /// </summary> public void Synchronize() { try { var request = new SearchRequest(DefaultNamingContext, "(&(|(objectClass=user)(objectClass=group))(usnchanged>=" + (Dispatcher.HighestUsnChanged + 1) + "))", SearchScope.Subtree, null); request.Controls.Add(new ShowDeletedControl()); // Page result var prc = new PageResultRequestControl(5); request.Controls.Add(prc); var soc = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope); request.Controls.Add(soc); while (true) { var searchResponse = (SearchResponse)Connection.SendRequest(request); if (searchResponse != null) { // Find the returned page response control foreach (DirectoryControl control in searchResponse.Controls) { if (control is PageResultResponseControl) { //update the cookie for next set prc.Cookie = ((PageResultResponseControl)control).Cookie; break; } } Dispatcher.AddToQueue(searchResponse.Entries.Cast <SearchResultEntry>().Where(p => LdapHelper.IsUser(p, PersonObjectCategory) || LdapHelper.IsGroup(p, GroupObjectCategory)).ToList()); if (prc.Cookie.Length == 0) { break; } } else { break; } } } catch (Exception ex) { LogError("Full synchronization failed.", ex); } }
protected internal virtual IEnumerable <SearchResultEntry> GetSearchResult(string identity, ISearchOptions searchOptions, SearchScope searchScope, int?pageSize) { if (searchOptions == null) { throw new ArgumentNullException("searchOptions"); } using (var ldapConnection = this.LdapConnectionFactory.Create(this.LdapConnectionSettings)) { var searchRequest = this.CreateSearchRequest(identity, this.ConcatenateFilters(this.DirectorySettings.Filter, searchOptions.Filter), searchScope, this.GetAttributes(searchOptions)); if (pageSize != null) { var pageResultRequestControl = new PageResultRequestControl(pageSize.Value); searchRequest.Controls.Add(pageResultRequestControl); var searchOptionsControl = new SearchOptionsControl(SearchOption.DomainScope); searchRequest.Controls.Add(searchOptionsControl); var searchResult = new List <SearchResultEntry>(); while (true) { var searchResponse = this.GetSearchResponse(ldapConnection, searchRequest); if (searchResponse.Controls.Length != 1 || !(searchResponse.Controls[0] is PageResultResponseControl)) { throw new InvalidOperationException("The server cannot page the result."); } var pageResultResponseControl = (PageResultResponseControl)searchResponse.Controls[0]; searchResult.AddRange(searchResponse.Entries.Cast <SearchResultEntry>()); if (pageResultResponseControl.Cookie.Length == 0) { break; } pageResultRequestControl.Cookie = pageResultResponseControl.Cookie; } } return(this.GetSearchResponse(ldapConnection, searchRequest).Entries.Cast <SearchResultEntry>()); } }
internal static SearchResultEntry GetSingleResponse(string dn, string filter, SearchScope scope, string[] attrsToReturn, bool useGC) { var connection = useGC ? ConnectGCLDAP() : ConnectLDAP(); var request = new SearchRequest(dn, filter, scope);//, attrsToReturn); // the size of each page var pageReqControl = new PageResultRequestControl(500); // turn off referral chasing so that data // from other partitions is not returned var searchControl = new SearchOptionsControl(SearchOption.DomainScope); //Unhandled Exception: System.ComponentModel.InvalidEnumArgumentException: //The value of argument 'value' (0) is invalid for Enum type 'SearchOption'. //var searchControl = new SearchOptionsControl(); request.Controls.Add(pageReqControl); request.Controls.Add(searchControl); try { var response = (SearchResponse)connection.SendRequest(request); if (response.Entries.Count == 0) { return(null); } return(response.Entries[0]); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } finally { if (useGC) { connection.Dispose(); } } }
private static SearchRequest GetRequest(string dn, string filter, string[] returnAttrs, SearchScope scope = SearchScope.Subtree) { var request = new SearchRequest(dn, filter, scope, returnAttrs); // turn off referral chasing so that data // from other partitions is not returned var searchControl = new SearchOptionsControl(SearchOption.DomainScope); //To retrieve nTSecurityDescriptor attribute https://github.com/BloodHoundAD/SharpHound3/blob/master/SharpHound3/DirectorySearch.cs#L157 var securityDescriptorFlagControl = new SecurityDescriptorFlagControl { SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner }; request.Controls.Add(securityDescriptorFlagControl); request.Controls.Add(searchControl); return(request); }
/// <summary> /// Pages through LDAP results filtered by Linq spec. /// Caveats: /// (1) paging iterates through all prior pages - a limitation of LDAP, /// (2) sorting can only take one attribute, and that attribute must be /// indexed in LDAP, or the server-side sort will fail. /// </summary> /// <typeparam name="T">The mapped type.</typeparam> /// <param name="spec">The filter specification.</param> /// <param name="offsetPage">How many pages into the results. 0 = first page.</param> /// <param name="pageSize">Size of a page. Default = 10.</param> /// <param name="sortKeys">Sorting options.</param> /// <returns></returns> public virtual IEnumerable <T> PageWithVLV <T>( Specification <T> spec, int offsetPage = 0, int pageSize = 10, SortKey[] sortKeys = null ) where T : IEntry, new() { var search = new LinqSearchRequest <T>(DistinguishedName, spec.AsExpression(), Scope); var pageControl = new VlvRequestControl(0, pageSize - 1, pageSize * offsetPage + 1); var soc = new SearchOptionsControl(SearchOption.DomainScope); search.Controls.Add(pageControl); search.Controls.Add(soc); if (sortKeys != null) { var sortControl = new SortRequestControl(sortKeys); search.Controls.Add(sortControl); } return(Connection.SendRequest(search).Entries); }
public IEnumerable <SearchResultEntryCollection> PagedSearch( string searchFilter, string[] attributesToLoad) { var pagedResults = new List <SearchResultEntryCollection>(); var searchRequest = new SearchRequest (searchBaseDN, searchFilter, SearchScope.Subtree, attributesToLoad); var searchOptions = new SearchOptionsControl(SearchOption.DomainScope); searchRequest.Controls.Add(searchOptions); var pageResultRequestControl = new PageResultRequestControl(pageSize); searchRequest.Controls.Add(pageResultRequestControl); while (true) { var searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest); var pageResponse = (PageResultResponseControl)searchResponse.Controls[0]; yield return(searchResponse.Entries); if (pageResponse.Cookie.Length == 0) { break; } pageResultRequestControl.Cookie = pageResponse.Cookie; } }
/// <summary> /// Performs LDAP Search and extracts attributes. /// </summary> /// <param name="logger">The logger.</param> /// <param name="CurrentTime">Locked program timestamp value</param> private void ExtractLDAPResults(LogHelper logger, DateTime CurrentTime) { List <string> AttributesToAdd = new List <string>(); foreach (PropertyBase item in this.Properties) { AttributesToAdd.Add(item.Mapping); } string[] _attrs = AttributesToAdd.ToArray(); String sFilter = SetQueryFilter(this.BatchAction, CurrentTime); SearchRequest searchRequest = new SearchRequest(this.SearchRoot, sFilter, SearchScope.Subtree, _attrs); PageResultRequestControl PageResponse = new PageResultRequestControl(this.PageSize); SearchOptionsControl SearchOptions = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope); searchRequest.Controls.Add(PageResponse); searchRequest.Controls.Add(SearchOptions); logger.LogVerbose(string.Format("Establishing LDAP Connection to: {0}", this.ServerName)); using (LdapConnection connection = CreateLDAPConnection()) { logger.LogVerbose(string.Format("Performing a {0} operation with filter: {1}", this.BatchAction, sFilter)); while (true) { SearchResponse response = null; try { response = connection.SendRequest(searchRequest) as SearchResponse; } catch (Exception ex) { throw new Exception("An error occurred whilst creating the SearchResponse", ex); } int ResponseCount = response.Entries.Count; int CurrentBatchSize; if (ResponseCount != this.PageSize) { CurrentBatchSize = ResponseCount; } else { CurrentBatchSize = this.PageSize; } string FilePath = CSVCreateFile(this.CSVDirectoryLocation, _TotalUsers, CurrentBatchSize); foreach (DirectoryControl control in response.Controls) { if (control is PageResultResponseControl) { PageResponse.Cookie = ((PageResultResponseControl)control).Cookie; break; } } // Create CSV file for current batch of users using (CSVWriter BatchFile = new CSVWriter(FilePath)) { // Create column headings for CSV file CSVUserEntry heading = new CSVUserEntry(); // Iterate over attribute headings foreach (PropertyBase item in this.Properties) { heading.Add(item.Name); } BatchFile.CSVWriteUser(heading, logger); // Create new CSV row for each user foreach (SearchResultEntry sre in response.Entries) { // Placeholder for CSV entry of current user CSVUserEntry user = new CSVUserEntry(); // Exract each user attribute specified in XML file foreach (PropertyBase item in this.Properties) { try { DirectoryAttribute attr = sre.Attributes[item.Mapping]; string value = string.Empty; if (null != attr && attr.Count > 0) { value = attr[0].ToString(); } if (item.Index == this.UserNameIndex) { user.Add(CreateUserAccountName(value, attr)); } else { user.Add(value); } } catch (Exception ex) { if (logger != null) { logger.LogException(string.Empty, ex); _TotalFailures++; } } } // Write current user to CSV file BatchFile.CSVWriteUser(user, logger); // Increment user count value _TotalUsers++; } } logger.LogVerbose(string.Format("Successfully extracted {0} users to {1} - the total user count is: {2}", CurrentBatchSize, FilePath, _TotalUsers)); if (PageResponse.Cookie.Length == 0) { break; } } } }
protected void BuildRequest(string searchBase, string ldapFilter, string[] propertiesToLoad, SearchScope scope) { Request = new SearchRequest(searchBase, ldapFilter, scope, propertiesToLoad); Request.TimeLimit = TimeSpan.FromSeconds((double)ForestBase.CurrentTimeOut); if (QueryInfo.PhantomRoot) { Request.DistinguishedName = null; SearchOptionsControl sopcontrol = new SearchOptionsControl(SearchOption.PhantomRoot); Request.Controls.Add(sopcontrol); } if (QueryInfo.PerformDirSync) { Request.TimeLimit = new TimeSpan(0, 10, 0); DirSyncCookie(); } else { if (ASQRequired) { AsqCookie(); } if (QueryInfo.PerformSort) { SortCookie(); } if (QueryInfo.VlvRequired) { VlvControls(); } else if (QueryInfo.PerformPagedQuery) { PageCookie(1000); } StatsCookie(); } if (QueryInfo.ShowDeleted) { ShowDeletedControl showdeleted = new ShowDeletedControl { ServerSide = true }; Request.Controls.Add(showdeleted); } if (QueryInfo.ShowRecycled) { DirectoryControl showrecycled = new DirectoryControl(SHOW_RECYCLED_CONTROL_OID, null, true, true); Request.Controls.Add(showrecycled); } }
/// <summary> /// Performs LDAP Search and extracts attributes. /// </summary> /// <param name="logger">The logger.</param> /// <param name="currentTime">Locked program timestamp value</param> Task ExtractLdapResultsAsync(DateTime currentTime) { var attributesToAdd = new List <string>(); foreach (var item in Properties) { attributesToAdd.Add(item.Mapping); } attributesToAdd.Add("userAccountControl"); var ldapFilter = SetQueryFilter(BatchAction, currentTime); var searchRequest = new SearchRequest(SearchRoot, ldapFilter, SearchScope.Subtree, attributesToAdd.ToArray()); var pageResponse = new PageResultRequestControl(PageSize); var searchOptions = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope); searchRequest.Controls.Add(pageResponse); searchRequest.Controls.Add(searchOptions); Log?.LogInformation($"Establishing LDAP Connection to: {ServerName}"); using (var connection = CreateLdapConnection()) { Log?.LogInformation($"Performing a {BatchAction} operation with filter: {ldapFilter}"); while (true) { SearchResponse response = null; try { response = connection.SendRequest(searchRequest) as SearchResponse; } catch (Exception e) { throw new Exception("An error occurred whilst creating the SearchResponse", e); } var responseCount = response.Entries.Count; var currentBatchSize = (responseCount != PageSize ? responseCount : PageSize); var filePath = CsvCreateFile(DirectoryLocation, _totalUsers, currentBatchSize); foreach (var control in response.Controls) { if (control is PageResultResponseControl responseControl) { pageResponse.Cookie = responseControl.Cookie; break; } } // Create CSV file for current batch of users using (var batchFile = new CsvWriter(filePath, Log)) { // Create column headings for CSV file var heading = new CsvRow(); // Iterate over attribute headings foreach (var item in Properties) { heading.Add(item.Name); } batchFile.CsvWrite(heading); // Create new CSV row for each user foreach (SearchResultEntry sre in response.Entries) { // Placeholder for CSV entry of current user var entry = new CsvRow(); var syncValue = true; // Get whether account is disabled var userAccountControlAttr = sre.Attributes["userAccountControl"]; var accountDisabled = true; if (userAccountControlAttr != null && userAccountControlAttr.Count > 0) { var userAccountControlValue = userAccountControlAttr[0].ToString(); try { var userAccountControl = int.Parse(userAccountControlValue); accountDisabled = (userAccountControl & ACCOUNTDISABLE) == ACCOUNTDISABLE; } catch (Exception e) { Log?.LogCritical(e, e.Message); } } // Extract each user attribute specified in XML file foreach (var item in Properties) { try { var attr = sre.Attributes[item.Mapping]; var value = (attr != null && attr.Count > 0 ? attr[0].ToString() : string.Empty); if (syncValue && TryParseValue(item, entry, value, accountDisabled, attr, sre)) { continue; } if (item.Index == UserNameIndex) { entry.Add(CreateUserAccountName(value, attr)); continue; } entry.Add(syncValue ? value : string.Empty); } catch (Exception e) { Log?.LogCritical(e, string.Empty); _totalFailures++; } } // Write current user to CSV file batchFile.CsvWrite(entry); // Increment user count value _totalUsers++; } } Log?.LogInformation($"Successfully extracted {currentBatchSize} users to {filePath} - the total user count is: {_totalUsers}"); if (pageResponse.Cookie.Length == 0) { break; } } } return(Task.CompletedTask); }
public void TestPageRequests() { using (LdapConnection connection = GetConnection()) { string ouName = "ProtocolsGroup8"; string dn = "ou=" + ouName; try { for (int i = 0; i < 20; i++) { DeleteEntry(connection, "ou=ProtocolsSubGroup8." + i + "," + dn); } DeleteEntry(connection, dn); AddOrganizationalUnit(connection, dn); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName); Assert.NotNull(sre); for (int i = 0; i < 20; i++) { AddOrganizationalUnit(connection, "ou=ProtocolsSubGroup8." + i + "," + dn); } string filter = "(objectClass=*)"; SearchRequest searchRequest = new SearchRequest( dn + "," + LdapConfiguration.Configuration.Domain, filter, SearchScope.Subtree, null); PageResultRequestControl pageRequest = new PageResultRequestControl(5); searchRequest.Controls.Add(pageRequest); SearchOptionsControl searchOptions = new SearchOptionsControl(SearchOption.DomainScope); searchRequest.Controls.Add(searchOptions); while (true) { SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest); Assert.Equal(1, searchResponse.Controls.Length); Assert.True(searchResponse.Controls[0] is PageResultResponseControl); PageResultResponseControl pageResponse = (PageResultResponseControl)searchResponse.Controls[0]; if (pageResponse.Cookie.Length == 0) { break; } pageRequest.Cookie = pageResponse.Cookie; } } finally { for (int i = 0; i < 20; i++) { DeleteEntry(connection, "ou=ProtocolsSubGroup8." + i + "," + dn); } DeleteEntry(connection, dn); } } }
public static void GetResponse(LdapConnection conn, string filter, SearchScope scope, string[] attrsToReturn, string dn, string printOption = null, string spnName = null) //Dictionary<string, string> myNames = null) { var request = new SearchRequest(dn, filter, scope, attrsToReturn); // the size of each page var pageReqControl = new PageResultRequestControl(500); // turn off referral chasing so that data // from other partitions is not returned //var searchControl = new SearchOptionsControl(SearchOption.DomainScope); //Unhandled Exception: System.ComponentModel.InvalidEnumArgumentException: //The value of argument 'value' (0) is invalid for Enum type 'SearchOption'. var searchControl = new SearchOptionsControl(); request.Controls.Add(pageReqControl); request.Controls.Add(searchControl); SearchResponse response; PageResultResponseControl pageResControl; // loop through each page while (true) { try { response = (SearchResponse)conn.SendRequest(request); if (response.Controls.Length != 1 || !(response.Controls[0] is PageResultResponseControl)) { Console.WriteLine("The server does not support this advanced search operation"); return; } pageResControl = (PageResultResponseControl)response.Controls[0]; //Console.WriteLine("\nThis page contains {0} response entries:\n", response.Entries.Count); switch (printOption) { //if there's only one attribute needs to be returned //and this attribute is a single-valued attribute case "single": Outputs.PrintSingle(response, attrsToReturn[0]); break; //if there's only one attribute needs to be returned //and this attribute is a multi-valued attribute case "multi": Outputs.PrintMulti(response, attrsToReturn[0]); break; ////Use specified name paris //case "mynames": //Outputs.PrintMyName(response, myNames); //break; case "gpo": Outputs.PrintGPO(response); break; case "spn": Outputs.PrintSPNs(response, spnName); break; case "domain": Outputs.PrintDomainAttrs(response); break; //case "attrname": //Outputs.PrintAttrName(response); //break; //default: print all attributesToReturned default: Outputs.PrintAll(response); break; } if (pageResControl.Cookie.Length == 0) { break; } pageReqControl.Cookie = pageResControl.Cookie; } catch (Exception e) { Console.WriteLine("Unexpected error: {0}", e.Message); break; } } }
private List <string> GetAllGroupNames() { List <string> groups = new List <string>(); LdapConnection conn = null; int defaultADPageSize = 500; int pageCount = 0; try { string ActiveDirectoryGroupFilterQuery2 = "(|(objectClass=msExchDynamicDistributionList)(objectClass=group))"; string[] propertiesToQuery = { "distinguishedname", "objectguid", "member", "memberof", "objectClass" }; SearchRequest request = new SearchRequest( null, ActiveDirectoryGroupFilterQuery2, System.DirectoryServices.Protocols.SearchScope.Subtree, propertiesToQuery); // Set the result page size SearchRequest searchRequestDistinguishedName = new SearchRequest { Scope = SearchScope.Subtree, Filter = ActiveDirectoryGroupFilterQuery2 }; SearchOptionsControl searchOptions = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.PhantomRoot); searchRequestDistinguishedName.Controls.Add(searchOptions); //PageResultRequestControl requestPageSize = new PageResultRequestControl(defaultADPageSize); //request.Controls.Add(requestPageSize); while (true) { PageResultResponseControl pageResponse = null; SearchResponse results = (SearchResponse)_ldapConnectionUsers.SendRequest(searchRequestDistinguishedName); if (null == results) { break; } pageCount++; // verify support for this advanced search operation if (results.Controls.Length != 1 || !(results.Controls[0] is PageResultResponseControl)) { break; } // cast the diretory control into a PageResultResponseControl object. pageResponse = (PageResultResponseControl)results.Controls[0]; if (results.Entries.Count > 0) { foreach (SearchResultEntry searchResult in results.Entries) { SearchResultAttributeCollection attColl = searchResult.Attributes; groups.Add(attColl["distinguishedname"][0].ToString()); } // if this is true, there are no more pages to request if (pageResponse != null && pageResponse.Cookie.Length == 0) { break; } // set the cookie of the pageRequest equal to the cookie of the pageResponse to // request the next page of data in the send request if (pageResponse != null) { //requestPageSize.Cookie = pageResponse.Cookie; } } } } catch (Exception ex) { } finally { if (conn != null) { conn.Dispose(); } } return(groups); }