private void StatusBox_Load(object sender, EventArgs e) { Domain curDom = Domain.GetCurrentDomain(); domBox.Text = curDom.Name; dcBox.Text = curDom.FindDomainController().Name; siteBox.Text = ActiveDirectorySite.GetComputerSite().Name; userBox.Text = Environment.UserName; dnBox.Text = Environment.UserDomainName; }
private void LoadDomainContext() { Policies = new List <LDAPPasswordPolicy>(); Users = new List <UserInfo>(); if ((!string.IsNullOrEmpty(Config.DomainUsername)) && (!string.IsNullOrEmpty(Config.DomainPassword))) { if (string.IsNullOrEmpty(Config.DomainController)) { Config.DomainController = FindDomainController(); } if (!string.IsNullOrEmpty(Config.DomainController)) { DirectoryContext = new DirectoryContext( DirectoryContextType.DirectoryServer, Config.DomainController, Config.DomainUsername, Config.DomainPassword ); AuthPrincipalContext = true; DirectoryEntry = new DirectoryEntry($"LDAP://{Config.DomainName}"); } else { _logger.Log("[-] Cannot find domain controller from domain name."); Environment.Exit(0); } } else { if (ContextHelper.IsInDomain()) { Config.DomainName = IPGlobalProperties.GetIPGlobalProperties().DomainName; Config.DomainController = ActiveDirectorySite.GetComputerSite().InterSiteTopologyGenerator.Name; _logger.Log($"[-] Retrieved domain and controller: {Config.DomainName} / {Config.DomainController}"); DirectoryContext = new DirectoryContext( DirectoryContextType.DirectoryServer, Config.DomainController ); AuthPrincipalContext = false; DirectoryEntry = new DirectoryEntry($"LDAP://{Config.DomainController}"); } else { _logger.Log("[-] Not joined to a domain and no username/password provided."); Environment.Exit(0); } } }
public void TestForestSites() { using (Forest forest = Forest.GetForest(ActiveDirectoryContext)) { Assert.True(forest.Sites.Count > 0); using (ActiveDirectorySite site = forest.Sites[0]) { Assert.True(forest.Sites.Contains(site)); Assert.Equal(0, forest.Sites.IndexOf(site)); } } }
public void TestSites() { using (Forest forest = Forest.GetForest(ActiveDirectoryContext)) { using (ActiveDirectorySite site = forest.Sites[0]) using (ActiveDirectorySite s = ActiveDirectorySite.FindByName(ActiveDirectoryContext, site.Name)) { Assert.Equal(site.Name, s.Name); Assert.True(s.Domains.Contains(forest.RootDomain)); Assert.NotNull(s.AdjacentSites); Assert.NotNull(s.BridgeheadServers); Assert.NotNull(s.PreferredRpcBridgeheadServers); Assert.NotNull(s.PreferredSmtpBridgeheadServers); Assert.NotNull(s.Subnets); Assert.True(s.SiteLinks.Count > 0); using (ActiveDirectorySiteLink adsl = s.SiteLinks[0]) { Assert.True(s.SiteLinks.Contains(adsl)); Assert.Equal(0, s.SiteLinks.IndexOf(adsl)); Assert.True(adsl.Sites.Contains(s)); Assert.True(adsl.Cost >= 0); Assert.True(adsl.TransportType == ActiveDirectoryTransportType.Rpc || adsl.TransportType == ActiveDirectoryTransportType.Smtp); } Assert.True(s.Servers.Contains(s.InterSiteTopologyGenerator)); using (DirectoryServer ds = s.Servers[0]) { Assert.NotNull(ds.InboundConnections); Assert.NotNull(ds.OutboundConnections); Assert.True(ds.IPAddress.IndexOf('.') >= 0); Assert.Equal(s.Name, ds.SiteName); Assert.True(ds.Partitions.Count > 0); string firstPartition = ds.Partitions[0]; Assert.True(ds.Partitions.Contains(firstPartition)); Assert.Equal(0, ds.Partitions.IndexOf(firstPartition)); string [] partitions = new string[0]; Assert.Throws <ArgumentException>(() => ds.Partitions.CopyTo(partitions, 0)); Assert.Throws <ArgumentNullException>(() => ds.Partitions.CopyTo(null, 0)); Assert.Throws <ArgumentOutOfRangeException>(() => ds.Partitions.CopyTo(partitions, -1)); partitions = new string[ds.Partitions.Count]; ds.Partitions.CopyTo(partitions, 0); Assert.True(partitions.Contains(firstPartition)); } } } }
/// <summary> /// Get the local site name. /// </summary> /// <returns>Name of the local site.</returns> private string GetSiteName() { try { using (ActiveDirectorySite site = ActiveDirectorySite.GetComputerSite()) { return(site.Name); } } catch (Exception) { return(null); } }
/// <summary> /// Get the local site name. /// </summary> /// <returns>Name of the local site.</returns> private string GetSiteName() { try { using (ActiveDirectorySite site = ActiveDirectorySite.GetComputerSite()) { return(site.Name); } } catch (ActiveDirectoryObjectNotFoundException) // object not found in directory store { return(null); } catch (ActiveDirectoryOperationException) // underlying directory operation failed { return(null); } catch (ActiveDirectoryServerDownException) // server unavailable { return(null); } }
// TryAddSCPResults // This function does an SCP lookup for a specific domain and adds the results // to the list. // NOTE: This will only work for domain-joined computers. // // Parameters: // ldapPath: A string that specifies the LDAP server. Can be null. // domain: A string that specifies the domain to match. // // Returns: // None. // private void TryAddSCPResults(string ldapPath, string domain) { SearchResultCollection scpEntries = null; string rootDSEPath = ldapPath == null ? "LDAP://RootDSE": ldapPath + "/RootDSE"; try { // Get the root directory entry. DirectoryEntry rootDSE = new DirectoryEntry(rootDSEPath); // Get the configuration path. string configPath = rootDSE.Properties["configurationNamingContext"].Value as string; // Get the configuration entry. DirectoryEntry configEntry = new DirectoryEntry("LDAP://" + configPath); // Create a search object for the configuration entry. DirectorySearcher configSearch = new DirectorySearcher(configEntry); // Set the search filter to find SCP URLs and SCP pointers. configSearch.Filter = "(&(objectClass=serviceConnectionPoint)" + "(|(keywords=" + ScpPtrGuidString + ")(keywords=" + ScpUrlGuidString + ")))"; // Specify which properties you want to retrieve. configSearch.PropertiesToLoad.Add("keywords"); configSearch.PropertiesToLoad.Add("serviceBindingInformation"); scpEntries = configSearch.FindAll(); } catch (Exception e) { Tracing.WriteLine("SCP lookup failed with:"); Tracing.WriteLine(e.ToString()); } // If no SCP entries were found, then exit. if (scpEntries == null || scpEntries.Count <= 0) { Tracing.WriteLine("No SCP records found."); return; } string fallBackLdapPath = null; // Check for SCP pointers. foreach (SearchResult scpEntry in scpEntries) { ResultPropertyValueCollection entryKeywords = scpEntry.Properties["keywords"]; if (CollectionContainsExactValue(entryKeywords, ScpPtrGuidString)) { string ptrLdapPath = scpEntry.Properties["serviceBindingInformation"][0] as string; // Check to determine whether this pointer is scoped to the user's domain. if (CollectionContainsExactValue(entryKeywords, "Domain=" + domain)) { Tracing.WriteLine("Found SCP pointer for " + domain + " in " + scpEntry.Path); // Only restart SCP lookup if this is the first time you've found an entry // scoped to the user's domain. This is to avoid endless redirection. if (ldapPath == null) { Tracing.WriteLine("Restarting SCP lookup in " + ptrLdapPath); TryAddSCPResults(ptrLdapPath, domain); return; } else { Tracing.WriteLine("Skipping SCP lookup in " + ptrLdapPath); } } else { // Save the first SCP pointer that is not scoped to a domain as a fallback. if (entryKeywords.Count == 1 && string.IsNullOrEmpty(fallBackLdapPath)) { fallBackLdapPath = ptrLdapPath; Tracing.WriteLine("Saved fallback SCP pointer: " + fallBackLdapPath); } } } } string computerSiteName = null; try { // Get the name of the ActiveDirectorySite the computer // belongs to (if it belongs to one). ActiveDirectorySite site = ActiveDirectorySite.GetComputerSite(); computerSiteName = site.Name; Tracing.WriteLine("Local computer in site: " + computerSiteName); } catch (Exception e) { Tracing.WriteLine("Unable to get computer site name."); Tracing.WriteLine(e.ToString()); } if (!string.IsNullOrEmpty(computerSiteName)) { // Scan the search results for SCP URLs. // SCP URLs fit into three tiers: // Priority 1: The URL is scoped to the computer's Active Directory site. // Priority 2: The URL is not scoped to any Active Directory site. // Priority 3: The URL is scoped to a different Active Directory site. // Temporary lists to hold priority 2 and 3 URLs. List <string> priorityTwoUrls = new List <string>(); List <string> priorityThreeUrls = new List <string>(); foreach (SearchResult scpEntry in scpEntries) { ResultPropertyValueCollection entryKeywords = scpEntry.Properties["keywords"]; // Check for SCP URLs. if (CollectionContainsExactValue(entryKeywords, ScpUrlGuidString)) { string scpUrl = scpEntry.Properties["serviceBindingInformation"][0] as string; scpUrl = scpUrl.ToLower(); // Determine whether this entry is scoped to the computer's site. if (CollectionContainsExactValue(entryKeywords, "Site=" + computerSiteName)) { // Priority 1. Tracing.WriteLine("Found priority 1 SCP URL: " + scpUrl); AddUrl(scpUrl); } else { // Determine whether this is a priority 2 or 3 URL. if (CollectionContainsPrefixValue(entryKeywords, "Site=")) { // Priority 3. if (!priorityThreeUrls.Contains(scpUrl)) { Tracing.WriteLine("Found priority 3 SCP URL: " + scpUrl); priorityThreeUrls.Add(scpUrl); } } else { // Priority 2. if (!priorityTwoUrls.Contains(scpUrl)) { Tracing.WriteLine("Found priority 2 SCP URL: " + scpUrl); priorityTwoUrls.Insert(0, scpUrl); } } } } } // Now add the priority 2 URLs into the main list. foreach (string priorityTwoUrl in priorityTwoUrls) { AddUrl(priorityTwoUrl); } // Now add the priority 3 URLs into the main list. foreach (string priorityThreeUrl in priorityThreeUrls) { AddUrl(priorityThreeUrl); } // If after all this, you still have no URLs in your list, // try the fallback SCP pointer, if you have one. if (this.Count == 0 && fallBackLdapPath != null) { TryAddSCPResults(fallBackLdapPath, domain); } } }
public void Remove(ActiveDirectorySite site) { }
// Methods public int Add(ActiveDirectorySite site) { }
public void Insert(int index, ActiveDirectorySite site) { }
public int IndexOf(ActiveDirectorySite site) { }
public bool Contains(ActiveDirectorySite site) { }
List <string> GetScpUrls(string ldapServer, string domain) { // Create a new list to return. List <string> scpUrlList = new List <string>(); string rootDSEPath = null; // If ldapServer is null/empty, use LDAP://RootDSE to // connect to Active Directory Domain Services (AD DS). Otherwise, use // LDAP://SERVERNAME/RootDSE to connect to a specific server. if (string.IsNullOrEmpty(ldapServer)) { rootDSEPath = "LDAP://RootDSE"; } else { rootDSEPath = ldapServer + "/RootDSE"; } SearchResultCollection scpEntries = null; try { // Get the root directory entry. DirectoryEntry rootDSE = new DirectoryEntry(rootDSEPath); // Get the configuration path. string configPath = rootDSE.Properties["configurationNamingContext"].Value as string; // Get the configuration entry. DirectoryEntry configEntry = new DirectoryEntry("LDAP://" + configPath); // Create a search object for the configuration entry. DirectorySearcher configSearch = new DirectorySearcher(configEntry); // Set the search filter to find SCP URLs and SCP pointers. configSearch.Filter = "(&(objectClass=serviceConnectionPoint)" + "(|(keywords=" + ScpPtrGuidString + ")(keywords=" + ScpUrlGuidString + ")))"; // Specify which properties you want to retrieve. configSearch.PropertiesToLoad.Add("keywords"); configSearch.PropertiesToLoad.Add("serviceBindingInformation"); scpEntries = configSearch.FindAll(); } catch (Exception ex) { oLog.AppendFormat("SCP lookup failed with: \r\n\r\n"); oLog.AppendFormat(ex.ToString() + "n"); } // If no SCP entries were found, then exit. if (scpEntries == null || scpEntries.Count <= 0) { oLog.AppendFormat("No SCP records found.\r\n\r\n"); return(null); } string fallBackLdapPath = null; // Check for SCP pointers. foreach (SearchResult scpEntry in scpEntries) { ResultPropertyValueCollection entryKeywords = scpEntry.Properties["keywords"]; if (CollectionContainsExactValue(entryKeywords, ScpPtrGuidString)) { string ptrLdapPath = scpEntry.Properties["serviceBindingInformation"][0] as string; // Determine whether this pointer is scoped to the user's domain. if (CollectionContainsExactValue(entryKeywords, "Domain=" + domain)) { oLog.AppendFormat("Found SCP pointer for " + domain + " in " + scpEntry.Path + "\r\n\r\n"); // Restart SCP lookup with the server assigned for the domain. oLog.AppendFormat("Restarting SCP lookup in {0}\r\n\r\n", ptrLdapPath); return(GetScpUrls(ptrLdapPath, domain)); } else { // Save the first SCP pointer that is not scoped to a domain as a fallback // in case you do not get any results from this server. if (entryKeywords.Count == 1 && string.IsNullOrEmpty(fallBackLdapPath)) { fallBackLdapPath = ptrLdapPath; oLog.AppendFormat("Saved fallback SCP pointer: {0}\r\n\r\n", fallBackLdapPath); } } } } string computerSiteName = null; try { // Get the name of the ActiveDirectorySite the computer // belongs to (if it belongs to one). ActiveDirectorySite site = ActiveDirectorySite.GetComputerSite(); computerSiteName = site.Name; oLog.AppendFormat("Local computer in site: {0}\r\n\r\n", computerSiteName); } catch (Exception ex) { oLog.AppendFormat("Unable to get computer site name.\n"); oLog.AppendFormat(ex.ToString() + "\r\n\r\n"); } if (!string.IsNullOrEmpty(computerSiteName)) { // Scan the search results for SCP URLs. // SCP URLs fit into three tiers: // Priority 1: The URL is scoped to the computer's Active Directory site. // Priority 2: The URL is not scoped to any Active Directory site. // Priority 3: The URL is scoped to a different Active Directory site. // Temporary lists to hold priority 2 and 3 URLs. List <string> priorityTwoUrls = new List <string>(); List <string> priorityThreeUrls = new List <string>(); foreach (SearchResult scpEntry in scpEntries) { ResultPropertyValueCollection entryKeywords = scpEntry.Properties["keywords"]; // Check for SCP URLs. if (CollectionContainsExactValue(entryKeywords, ScpUrlGuidString)) { string scpUrlPath = scpEntry.Properties["adsPath"][0] as string; oLog.AppendFormat("SCP URL found at: {0}\r\n\r\n", scpUrlPath); string scpUrl = scpEntry.Properties["serviceBindingInformation"][0] as string; scpUrl = scpUrl.ToLower(); // Determine whether this entry is scoped to the computer's site. if (CollectionContainsExactValue(entryKeywords, "Site=" + computerSiteName)) { // Priority 1. if (!scpUrlList.Contains(scpUrl.ToLower())) { oLog.AppendFormat("Adding priority 1 SCP URL: {0}\r\n\r\n", scpUrl.ToLower()); scpUrlList.Add(scpUrl); } else { oLog.AppendFormat("Priority 1 SCP URL already found: {0}\r\n\r\n", scpUrl); } } else { // Determine whether this is a priority 2 or 3 URL. if (CollectionContainsPrefixValue(entryKeywords, "Site=")) { // Priority 3. if (!priorityThreeUrls.Contains(scpUrl)) { oLog.AppendFormat("Adding priority 3 SCP URL: {0}\r\n\r\n", scpUrl); priorityThreeUrls.Add(scpUrl); } else { oLog.AppendFormat("Priority 3 SCP URL already found: {0}\r\n\r\n", scpUrl); } } else { // Priority 2. if (!priorityTwoUrls.Contains(scpUrl)) { oLog.AppendFormat("Adding priority 2 SCP URL: {0}\r\n\r\n", scpUrl); priorityTwoUrls.Add(scpUrl); } else { oLog.AppendFormat("Priority 2 SCP URL already found: {0}\r\n\r\n", scpUrl); } } } } } // Now add the priority 2 URLs into the main list. foreach (string priorityTwoUrl in priorityTwoUrls) { // If the URL is already in the list as a priority 1, // don't add it again. if (!scpUrlList.Contains(priorityTwoUrl)) { scpUrlList.Add(priorityTwoUrl); } } // Now add the priority 3 URLs into the main list. foreach (string priorityThreeUrl in priorityThreeUrls) { // If the URL is already in the list as a priority 1 // or priority 2, don't add it again. if (!scpUrlList.Contains(priorityThreeUrl)) { scpUrlList.Add(priorityThreeUrl); } } // If after all this, you still have no URLs in your list, // try the fallback SCP pointer, if you have one. if (scpUrlList.Count == 0 && fallBackLdapPath != null) { return(GetScpUrls(fallBackLdapPath, domain)); } } return(scpUrlList); }
public void CopyTo(ActiveDirectorySite[] array, int index) {}
public void CopyTo(ActiveDirectorySite[] sites, int index) { }
public ActiveDirectorySite FindSite(string Name) { var site = ActiveDirectorySite.FindByName(_context, Name); return(site); }
// Methods public int Add(ActiveDirectorySite site) {}
public void Remove(ActiveDirectorySite site) {}
public void Insert(int index, ActiveDirectorySite site) {}
public static void GetAppliedGPOs(LdapConnection connection, string rootDn, string name, bool isPC = false) { //if it is a computer account or a user account string nFilter = isPC ? @"(&(sAMAccountType=805306369)(name=" + name + "))" : @"(&(sAMAccountType=805306368)(name=" + name + "))"; string[] nAttrs = { "distingushiedName" }; //get the account distingushied name string Dn = GetSingleValue(connection, nFilter, SearchScope.Subtree, nAttrs, rootDn); Console.WriteLine(" * DN: {0}\n", Dn); //If Last OU/Domain blocks inheritance bool isBlocking = false; string dn = "CN=" + name + ","; string ou = Dn.Replace(dn, ""); //OU will not be affected by the block rule on itself int blockCounter = 0; try { while (ou.Contains(",")) { using (var entry = new DirectoryEntry("LDAP://" + ou)) { isBlocking = Outputs.PrintGplink(entry, ou, isBlocking, blockCounter); if (isBlocking) { blockCounter += 1; } } if (ou.Contains(",")) { ou = ou.Substring(ou.IndexOf(",") + 1); } else { break; } } }catch (Exception e) { Console.WriteLine(e.Message); } //get GPO applied on the site if (isPC) { try { string site = ActiveDirectorySite.GetComputerSite().Name; string siteDn = "CN=" + site + ",CN=Sites,CN=Configuration," + rootDn; using (var entry = new DirectoryEntry("LDAP://" + siteDn)) { Outputs.PrintGplink(entry, siteDn, isBlocking, blockCounter); } } catch { } } }
public void CreateNewSubnet(string Name, ActiveDirectorySite Site) { ActiveDirectorySubnet newsub = new ActiveDirectorySubnet(this._context, Name, Site.Name); newsub.Save(); }
public void AddRange(ActiveDirectorySite[] sites) {}
public int IndexOf(ActiveDirectorySite site) {}
public bool Contains(ActiveDirectorySite site) {}
static void Main() { try { string targetName = "fabrikam.com"; string subnetName1 = "154.55.0.0/16"; string subnetName2 = "154.56.0.0/16"; string siteName = "myNewSite"; string siteLinkName = "DEFAULTIPSITELINK"; string defaultSiteName = "Default-First-Site-Name"; DirectoryContext domainContext = new DirectoryContext( DirectoryContextType.Domain, targetName); DirectoryContext forestContext = new DirectoryContext( DirectoryContextType.Forest, targetName); Forest forest = Forest.GetForest(forestContext); // create new site ActiveDirectorySite site = new ActiveDirectorySite(forestContext, siteName); site.Options = ActiveDirectorySiteOptions.GroupMembershipCachingEnabled; site.Save(); Console.WriteLine("\nSite \"{0}\" is created successfully", site); // create new subnets ActiveDirectorySubnet subnet1 = new ActiveDirectorySubnet(forestContext, subnetName1); subnet1.Location = "Bellevue"; subnet1.Site = site; subnet1.Save(); Console.WriteLine("\nSubnet \"{0}\" is created successfully", subnet1); ActiveDirectorySubnet subnet2 = new ActiveDirectorySubnet(forestContext, subnetName2, siteName); subnet2.Location = "Redmond"; subnet2.Save(); Console.WriteLine("\nSubnet \"{0}\" is created successfully", subnet2); Console.WriteLine("\nSite \"{0}\" contains subnet:", site.Name); foreach (ActiveDirectorySubnet subnet in site.Subnets) { Console.WriteLine("\tSubnet \"{0}\", location is {1}", subnet.Name, subnet.Location); } // add new site to an existing site link ActiveDirectorySiteLink link = ActiveDirectorySiteLink.FindByName( forestContext, siteLinkName); Console.WriteLine("\nAdd site \"{0}\" to site link \"{1}\"", site.Name, link.Name); link.Sites.Add(site); link.Save(); Console.WriteLine("\nSiteLink \"{0}\" has site: ", link); foreach (ActiveDirectorySite s in link.Sites) { Console.WriteLine("\tSite \"{0}\"", s); } // delete site and subnets site.Delete(); subnet1.Delete(); subnet2.Delete(); Console.WriteLine("\nSite and subnets are deleted successfully\n"); // existing site management // preferred RPC bridgehead server ActiveDirectorySite defaultSite = ActiveDirectorySite.FindByName( forestContext, defaultSiteName); Console.WriteLine("\nExisting PreferredRpcBridgeheadServers is:"); foreach (DirectoryServer s in defaultSite.PreferredRpcBridgeheadServers) { Console.WriteLine("\tServer {0}", s.Name); } Console.WriteLine("\nAdd PreferredRpcBridgeheadServers"); DomainControllerCollection col = Domain.GetDomain(domainContext). FindAllDomainControllers(defaultSiteName); foreach (DirectoryServer s in col) { defaultSite.PreferredRpcBridgeheadServers.Add(s); } defaultSite.Save(); Console.WriteLine("\nAfter updating, PreferredRpcBridgeheadServers is:"); foreach (DirectoryServer s in defaultSite.PreferredRpcBridgeheadServers) { Console.WriteLine("\tServer {0}", s.Name); } defaultSite.PreferredRpcBridgeheadServers.Clear(); defaultSite.Save(); Console.WriteLine("\nAfter Clear call, PreferredRpcBridgeheadServers is:"); foreach (DirectoryServer s in defaultSite.PreferredRpcBridgeheadServers) { Console.WriteLine("\tServer {0}", s.Name); } } catch (Exception e) { Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType().Name + ":" + e.Message); } }