private static void GetTreeDomains(AD.Domain startDomain, List <AD.Domain> treeDomainsWithChildren, List <string> unavailableDomains) { var domainTrusts = startDomain.GetAllTrustRelationships(); List <AD.Domain> treeDomains = new List <AD.Domain>(); foreach (TrustRelationshipInformation domainTrust in domainTrusts) { if (domainTrust.TrustType.Equals(TrustType.TreeRoot)) { try { var treeDomain = AD.Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, domainTrust.TargetName)); treeDomains.Add(treeDomain); } catch { unavailableDomains.Add(domainTrust.TargetName); } } } foreach (var treeDomain in treeDomains) { AddAllChildDomains(treeDomain, treeDomainsWithChildren, unavailableDomains); } }
private DirectoryEntry GetDirectoryEntry() { System.DirectoryServices.ActiveDirectory.Domain domain = GetSelectedDomain(); DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://" + domain.Name); return(directoryEntry); }
private static Domain GetDomainObject(string domain) { var key = domain ?? NullKey; if (DomainObjectMap.TryGetValue(key, out var domainObj)) { return(domainObj); } try { if (key == NullKey) { domainObj = Domain.GetCurrentDomain(); } else { var context = new DirectoryContext(DirectoryContextType.Domain, domain); domainObj = Domain.GetDomain(context); } DomainObjectMap.TryAdd(key, domainObj); return(domainObj); } catch { DomainObjectMap.TryAdd(key, null); return(domainObj); } }
public Domain() : base() { trustCollection = null; parent = null; children = new DomainCollection(); }
public int IndexOf(Domain domain) { Contract.Requires(domain != null); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < this.Count); return default(int); }
public static Domain GetDomain(DirectoryContext dc) { Domain domain = new Domain(); domain.dName = dc.Name; domain.DC = dc; return domain; }
public ADDomain(ActiveDirectoryContext Context, Domain Domain) { this.context = Context; this.Domain = Domain; this.SearchContainers = null; this.domainControllers = null; this.domainMaintenanceNext = DateTime.Now.AddMinutes(DomainMaintanceIntervalMinutes); this.Initialize(); }
public bool Contains(Domain domain) { if (domain == null) throw new ArgumentNullException("domain"); for (int i = 0; i < InnerList.Count; i++) { Domain tmp = (Domain)InnerList[i]; if (Utils.Compare(tmp.Name, domain.Name) == 0) { return true; } } return false; }
public int IndexOf(Domain domain) { if (domain == null) throw new ArgumentNullException("domain"); for (int i = 0; i < InnerList.Count; i++) { Domain tmp = (Domain)InnerList[i]; if (Utils.Compare(tmp.Name, domain.Name) == 0) { return i; } } return -1; }
private static void AddAllChildDomains(AD.Domain root, List <AD.Domain> domains, List <string> unavailableDomains) { domains.Add(root); for (var i = 0; i < root.Children.Count; ++i) { try { var subDomain = AD.Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, root.Children[i].Name)); AddAllChildDomains(subDomain, domains, unavailableDomains); } catch { unavailableDomains.Add(root.Children[i].Name); } } }
/// <summary> /// Gets the name of the forest associate with the domain /// </summary> /// <param name="domain"></param> /// <returns></returns> internal static string GetForestName(string domain = null) { try { if (domain == null) { return(Forest.GetCurrentForest().Name); } var domainObject = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, domain)); return(domainObject.Forest.Name); } catch { return(domain); } }
public int IndexOf(Domain domain) { if (domain != null) { int num = 0; while (num < base.InnerList.Count) { Domain item = (Domain)base.InnerList[num]; if (Utils.Compare(item.Name, domain.Name) != 0) { num++; } else { return num; } } return -1; } else { throw new ArgumentNullException("domain"); } }
public bool Contains(Domain domain) { if (domain != null) { int num = 0; while (num < base.InnerList.Count) { Domain item = (Domain)base.InnerList[num]; if (Utils.Compare(item.Name, domain.Name) != 0) { num++; } else { return true; } } return false; } else { throw new ArgumentNullException("domain"); } }
public void CreateTrustRelationship(Domain targetDomain, TrustDirection direction) { base.CheckIfDisposed(); if (targetDomain == null) { throw new ArgumentNullException("targetDomain"); } if ((direction < TrustDirection.Inbound) || (direction > TrustDirection.Bidirectional)) { throw new InvalidEnumArgumentException("direction", (int) direction, typeof(TrustDirection)); } string password = TrustHelper.CreateTrustPassword(); TrustHelper.CreateTrust(base.context, base.Name, targetDomain.GetDirectoryContext(), targetDomain.Name, false, direction, password); int num = 0; if ((direction & TrustDirection.Inbound) != ((TrustDirection) 0)) { num |= 2; } if ((direction & TrustDirection.Outbound) != ((TrustDirection) 0)) { num |= 1; } TrustHelper.CreateTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, base.context, base.Name, false, (TrustDirection) num, password); }
public void RepairTrustRelationship(Domain targetDomain) { TrustDirection direction = TrustDirection.Bidirectional; CheckIfDisposed(); if (targetDomain == null) throw new ArgumentNullException("targetDomain"); // first try to reset the secure channel try { direction = GetTrustRelationship(targetDomain.Name).TrustDirection; // verify outbound trust first if ((direction & TrustDirection.Outbound) != 0) { TrustHelper.VerifyTrust(context, Name, targetDomain.Name, false /*not forest*/, TrustDirection.Outbound, true /*reset secure channel*/, null /* no need to go to specific server*/); } // verify inbound trust if ((direction & TrustDirection.Inbound) != 0) { TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false /*not forest*/, TrustDirection.Outbound, true/*reset secure channel*/, null /* no need to go to specific server*/); } } catch (ActiveDirectoryOperationException) { // secure channel setup fails RepairTrustHelper(targetDomain, direction); } catch (UnauthorizedAccessException) { // trust password does not match RepairTrustHelper(targetDomain, direction); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null); } }
public void UpdateTrustRelationship(Domain targetDomain, TrustDirection newTrustDirection) { CheckIfDisposed(); if (targetDomain == null) throw new ArgumentNullException("targetDomain"); if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional) throw new InvalidEnumArgumentException("newTrustDirection", (int)newTrustDirection, typeof(TrustDirection)); // no we generate trust password string password = TrustHelper.CreateTrustPassword(); TrustHelper.UpdateTrustDirection(context, Name, targetDomain.Name, password, false /* not a forest */, newTrustDirection); // then create trust on remote side TrustDirection reverseDirection = 0; if ((newTrustDirection & TrustDirection.Inbound) != 0) reverseDirection |= TrustDirection.Outbound; if ((newTrustDirection & TrustDirection.Outbound) != 0) reverseDirection |= TrustDirection.Inbound; TrustHelper.UpdateTrustDirection(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, password, false /* not a forest */, reverseDirection); }
public void CreateTrustRelationship(Domain targetDomain, TrustDirection direction) { CheckIfDisposed(); if (targetDomain == null) throw new ArgumentNullException("targetDomain"); if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) throw new InvalidEnumArgumentException("direction", (int)direction, typeof(TrustDirection)); string password = TrustHelper.CreateTrustPassword(); // first create trust on local side TrustHelper.CreateTrust(context, Name, targetDomain.GetDirectoryContext(), targetDomain.Name, false, direction, password); // then create trust on remote side int reverseDirection = 0; if ((direction & TrustDirection.Inbound) != 0) reverseDirection |= (int)TrustDirection.Outbound; if ((direction & TrustDirection.Outbound) != 0) reverseDirection |= (int)TrustDirection.Inbound; TrustHelper.CreateTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, context, Name, false, (TrustDirection)reverseDirection, password); }
private void GetDomains() { if (!this.IsADAM) { string currentServerName = this.servers[0].Name; //TODO: REVIEW: this.cachedEntry.Options.GetCurrentServerName(); DomainController domainController = DomainController.GetDomainController(Utils.GetNewDirectoryContext(currentServerName, DirectoryContextType.DirectoryServer, this.context)); IntPtr handle = domainController.Handle; IntPtr intPtr = (IntPtr)0; IntPtr procAddress = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW"); if (procAddress != (IntPtr)0) { UnsafeNativeMethods.DsListDomainsInSiteW delegateForFunctionPointer = (UnsafeNativeMethods.DsListDomainsInSiteW)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(UnsafeNativeMethods.DsListDomainsInSiteW)); int propertyValue = delegateForFunctionPointer(handle, (string)PropertyManager.GetPropertyValue(this.context, this.cachedEntry, PropertyManager.DistinguishedName), ref intPtr); if (propertyValue == 0) { try { DS_NAME_RESULT dSNAMERESULT = new DS_NAME_RESULT(); Marshal.PtrToStructure(intPtr, dSNAMERESULT); int num = dSNAMERESULT.cItems; IntPtr intPtr1 = dSNAMERESULT.rItems; if (num > 0) { Marshal.ReadInt32(intPtr1); for (int i = 0; i < num; i++) { IntPtr intPtr2 = (IntPtr)((long)intPtr1 + (long)(Marshal.SizeOf(typeof(DS_NAME_RESULT_ITEM)) * i)); DS_NAME_RESULT_ITEM dSNAMERESULTITEM = new DS_NAME_RESULT_ITEM(); Marshal.PtrToStructure(intPtr2, dSNAMERESULTITEM); if (dSNAMERESULTITEM.status == DS_NAME_ERROR.DS_NAME_NO_ERROR || dSNAMERESULTITEM.status == DS_NAME_ERROR.DS_NAME_ERROR_DOMAIN_ONLY) { string stringUni = Marshal.PtrToStringUni(dSNAMERESULTITEM.pName); if (stringUni != null && stringUni.Length > 0) { string dnsNameFromDN = Utils.GetDnsNameFromDN(stringUni); Domain domain = new Domain(Utils.GetNewDirectoryContext(dnsNameFromDN, DirectoryContextType.Domain, this.context), dnsNameFromDN); this.domains.Add(domain); } } } } } finally { procAddress = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (procAddress != (IntPtr)0) { UnsafeNativeMethods.DsFreeNameResultW dsFreeNameResultW = (UnsafeNativeMethods.DsFreeNameResultW)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(UnsafeNativeMethods.DsFreeNameResultW)); dsFreeNameResultW(intPtr); } else { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } } } else { throw ExceptionHelper.GetExceptionFromErrorCode(propertyValue, currentServerName); } } else { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } } }
public void RepairTrustRelationship (Domain targetDomain) { throw new NotImplementedException (); }
public void CopyTo(Domain[] domains, int index) { Contract.Requires(domains != null); }
private void RepairTrustHelper(Domain targetDomain, TrustDirection direction) { string str = TrustHelper.CreateTrustPassword(); string str1 = TrustHelper.UpdateTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, base.Name, str, false); string str2 = TrustHelper.UpdateTrust(this.context, base.Name, targetDomain.Name, str, false); if ((direction & TrustDirection.Outbound) != 0) { try { TrustHelper.VerifyTrust(this.context, base.Name, targetDomain.Name, false, TrustDirection.Outbound, true, str1); } catch (ActiveDirectoryObjectNotFoundException activeDirectoryObjectNotFoundException) { object[] name = new object[3]; name[0] = base.Name; name[1] = targetDomain.Name; name[2] = direction; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("WrongTrustDirection", name), typeof(TrustRelationshipInformation), null); } } if ((direction & TrustDirection.Inbound) != 0) { try { TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, base.Name, false, TrustDirection.Outbound, true, str2); } catch (ActiveDirectoryObjectNotFoundException activeDirectoryObjectNotFoundException1) { object[] objArray = new object[3]; objArray[0] = base.Name; objArray[1] = targetDomain.Name; objArray[2] = direction; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("WrongTrustDirection", objArray), typeof(TrustRelationshipInformation), null); } } }
private void FindParentDomain() { DirectoryEntry rootDse = new DirectoryEntry(string.Format("LDAP://{0}/RootDSE", dName), dc.UserName, dc.Password); string configureName = rootDse.DirContext.ConfigurationNamingContext; if (configureName == null || configureName == "") { parent = null; return; } DirectoryEntry sys = new DirectoryEntry(string.Format("LDAP://{0}/CN=Partitions,{1}", SDSUtils.DNToDomainName(configureName), configureName), dc.UserName, dc.Password); DirectorySearcher ds = new DirectorySearcher(sys); ds.Filter = "(objectClass=crossRef)"; ds.SearchScope = SearchScope.OneLevel; SearchResultCollection src = ds.FindAll(); if (src != null && src.Count > 0) { foreach (SearchResult sr in src) { string sProtocol, sServer, sCNs, sDCs; SDSUtils.CrackPath(sr.Path, out sProtocol, out sServer, out sCNs, out sDCs); DirectoryEntry partEntry = new DirectoryEntry(sr.Path, dc.UserName, dc.Password); string partName = partEntry.Properties["nCName"].Value as string; if (dName.Equals(SDSUtils.DNToDomainName(partName), StringComparison.InvariantCultureIgnoreCase)) { string parentDomainDN = partEntry.Properties["trustParent"].Value as string; if (parentDomainDN != null && parentDomainDN != "") { parent = new Domain(SDSUtils.DNToDomainName(parentDomainDN)); break; } } } } return; }
public void VerifyTrustRelationship(Domain targetDomain, TrustDirection direction) { base.CheckIfDisposed(); if (targetDomain == null) { throw new ArgumentNullException("targetDomain"); } if ((direction < TrustDirection.Inbound) || (direction > TrustDirection.Bidirectional)) { throw new InvalidEnumArgumentException("direction", (int) direction, typeof(TrustDirection)); } if ((direction & TrustDirection.Outbound) != ((TrustDirection) 0)) { try { TrustHelper.VerifyTrust(base.context, base.Name, targetDomain.Name, false, TrustDirection.Outbound, false, null); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryObjectNotFoundException(Res.GetString("WrongTrustDirection", new object[] { base.Name, targetDomain.Name, direction }), typeof(TrustRelationshipInformation), null); } } if ((direction & TrustDirection.Inbound) != ((TrustDirection) 0)) { try { TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, base.Name, false, TrustDirection.Outbound, false, null); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryObjectNotFoundException(Res.GetString("WrongTrustDirection", new object[] { base.Name, targetDomain.Name, direction }), typeof(TrustRelationshipInformation), null); } } }
public void VerifyTrustRelationship (Domain targetDomain, TrustDirection direction) { throw new NotImplementedException (); }
public bool Contains(Domain domain) { Contract.Requires(domain != null); return(default(bool)); }
private void GetDomains() { // for ADAM, there is no concept of domain, we just return empty collection which is good enough if (!IsADAM) { string serverName = cachedEntry.Options.GetCurrentServerName(); DomainController dc = DomainController.GetDomainController(Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context)); IntPtr handle = dc.Handle; Debug.Assert(handle != (IntPtr)0); IntPtr info = (IntPtr)0; // call DsReplicaSyncAllW IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } UnsafeNativeMethods.DsListDomainsInSiteW dsListDomainsInSiteW = (UnsafeNativeMethods.DsListDomainsInSiteW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsListDomainsInSiteW)); int result = dsListDomainsInSiteW(handle, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), ref info); if (result != 0) throw ExceptionHelper.GetExceptionFromErrorCode(result, serverName); try { DS_NAME_RESULT names = new DS_NAME_RESULT(); Marshal.PtrToStructure(info, names); int count = names.cItems; IntPtr val = names.rItems; if (count > 0) { Debug.Assert(val != (IntPtr)0); int status = Marshal.ReadInt32(val); IntPtr tmpPtr = (IntPtr)0; for (int i = 0; i < count; i++) { tmpPtr = IntPtr.Add(val, Marshal.SizeOf(typeof(DS_NAME_RESULT_ITEM)) * i); DS_NAME_RESULT_ITEM nameResult = new DS_NAME_RESULT_ITEM(); Marshal.PtrToStructure(tmpPtr, nameResult); if (nameResult.status == DS_NAME_ERROR.DS_NAME_NO_ERROR || nameResult.status == DS_NAME_ERROR.DS_NAME_ERROR_DOMAIN_ONLY) { string domainName = Marshal.PtrToStringUni(nameResult.pName); if (domainName != null && domainName.Length > 0) { string d = Utils.GetDnsNameFromDN(domainName); Domain domain = new Domain(Utils.GetNewDirectoryContext(d, DirectoryContextType.Domain, context), d); _domains.Add(domain); } } } } } finally { // call DsFreeNameResultW functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } UnsafeNativeMethods.DsFreeNameResultW dsFreeNameResultW = (UnsafeNativeMethods.DsFreeNameResultW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsFreeNameResultW)); dsFreeNameResultW(info); } } }
public static void Main(string[] args) { int argumentsize = args.Length; string help = "To query for the existing properties of a GPO in Active Directory, use: \n- metronome.exe query <Target GUID> \n\nTo add an immediate scheduled task to a GPO, use:\n- metronome.exe itask <Target GUID> <LDAP Path to GPO> <Original gpcMachineExtensionNames> <Original versionnumber> <task author> <task name> <command> <arguments>\n\nTo deploy a file using a GPO, use:\n- metronome.exe file <Target GUID> <LDAP Path to GPO> <Original gpcMachineExtensionNames> <Original versionnumber> <source file and path> <destination file> <destination path (with no trailing \\)>\n\nTo revert a GPO to its original properties or set the properties to different values, use:\n- metronome.exe set <Target GUID> <LDAP Path to GPO> <Original gpcMachineExtensionNames> <Original versionnumber>\n\nTo only increment the versionnumber field, use:\n- metronome.exe versionset <Target GUID> <LDAP Path to GPO> <Original versionnumber>\n\nTo enable or disable a GPO, use:\n- metronome.exe enable\\disable <Target GUID> <LDAP Path to GPO> <Original versionnumber>"; string guid_filter = ""; string guid_LDAP = ""; string gpcMacExtName = ""; string new_gpcMacExtName = ""; string schtask_gpcMacExtName = "[{AADCED64-746C-4633-A97C-D61349046527}{CAB54552-DEEA-4691-817E-ED4A4D1AFC72}]"; string file_gpcMacExtName = "[{7150F9BF-48AD-4DA4-A49C-29EF4A8369BA}{3BAE7E51-E3F4-41D0-853D9BB9FD47605F}]"; string immediateScheduledTaskString = ""; string immediateFileXMLString = ""; string path = ""; string author = ""; string task_name = ""; string command = ""; string arguments = ""; string version_string = ""; string domain_string = ""; string start = ""; string end = ""; string source_file_path = ""; string dest_file = ""; string dest_path = ""; string dest_file_path = ""; System.DirectoryServices.ActiveDirectory.Domain domain = null; int versionnumber = 0; int new_versionnumber = 0; int enable_flag = 0; int disable_flag = 3; try { if (argumentsize > 0) { if (args[0].Equals("help")) { Console.WriteLine(help); } else if (args[0].Equals("query")) { guid_filter = args[1]; DirectoryEntry de = new DirectoryEntry(); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = "(&(objectCategory=groupPolicyContainer)(name=" + guid_filter + "))"; ds.PropertiesToLoad.Add("displayname"); ds.PropertiesToLoad.Add("gpcMachineExtensionNames"); ds.PageSize = 1000; ds.SizeLimit = 100; ds.PropertiesToLoad.Add("versionnumber"); ds.PropertiesToLoad.Add("flags"); ds.SearchScope = SearchScope.Subtree; SearchResultCollection src = ds.FindAll(); string results = ""; foreach (SearchResult sr in src) { ResultPropertyCollection myResultPropColl = sr.Properties; foreach (string myKey in myResultPropColl.PropertyNames) { foreach (Object myCollection in myResultPropColl[myKey]) { results += myKey + ": " + myCollection + "\n\n"; } } } Console.WriteLine(results); } else if (args[0].Equals("itask")) { domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain(); domain_string = domain.Name; guid_filter = args[1]; guid_LDAP = args[2]; gpcMacExtName = args[3]; version_string = args[4]; author = args[5]; task_name = args[6]; command = args[7]; arguments = args[8]; path = @"\\" + domain_string + "\\sysvol\\" + domain_string + "\\policies\\" + guid_filter; start = @"<?xml version=""1.0"" encoding=""utf-8""?><ScheduledTasks clsid=""{CC63F200-7309-4ba0-B154-A71CD118DBCC}"">" ; end = @"</ScheduledTasks>"; immediateScheduledTaskString = string.Format(@"<ImmediateTaskV2 clsid=""{{9756B581-76EC-4169-9AFC-0CA8D43ADB5F}}"" name=""{1}"" image=""0"" changed=""2019-03-30 23:04:20"" uid=""{4}""><Properties action=""C"" name=""{1}"" runAs=""NT AUTHORITY\System"" logonType=""S4U""><Task version=""1.3""><RegistrationInfo><Author>{0}</Author><Description></Description></RegistrationInfo><Principals><Principal id=""Author""><UserId>NT AUTHORITY\System</UserId><LogonType>S4U</LogonType><RunLevel>HighestAvailable</RunLevel></Principal></Principals><Settings><IdleSettings><Duration>PT10M</Duration><WaitTimeout>PT1H</WaitTimeout><StopOnIdleEnd>true</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>true</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><StartWhenAvailable>true</StartWhenAvailable><RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable><AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled><Hidden>false</Hidden><RunOnlyIfIdle>false</RunOnlyIfIdle><WakeToRun>false</WakeToRun><ExecutionTimeLimit>P3D</ExecutionTimeLimit><Priority>7</Priority><DeleteExpiredTaskAfter>PT0S</DeleteExpiredTaskAfter></Settings><Triggers><TimeTrigger><StartBoundary>%LocalTimeXmlEx%</StartBoundary><EndBoundary>%LocalTimeXmlEx%</EndBoundary><Enabled>true</Enabled></TimeTrigger></Triggers><Actions Context=""Author""><Exec><Command>{2}</Command><Arguments>{3}</Arguments></Exec></Actions></Task></Properties></ImmediateTaskV2>", author, task_name, command, arguments, Guid.NewGuid().ToString()); versionnumber = Convert.ToInt32(version_string); new_gpcMacExtName = gpcMacExtName + schtask_gpcMacExtName; new_versionnumber = versionnumber + 5; if (Directory.Exists(path)) { path += "\\Machine\\Preferences\\ScheduledTasks\\"; } else { Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Red; Console.Write("!"); Console.ResetColor(); Console.WriteLine("] Could not find the specified GPO path!"); } if (!Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } path += "ScheduledTasks.xml"; if (File.Exists(path)) { Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Red; Console.Write("!"); Console.ResetColor(); Console.WriteLine("] Warning, the GPO you are targetting already has a ScheduledTask.xml. At this time, download the XML at " + path + " and manually insert your task in for execution."); } else { Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Green; Console.Write("+"); Console.ResetColor(); Console.WriteLine("] Creating file " + path); System.IO.File.WriteAllText(path, start + immediateScheduledTaskString + end); DirectoryEntry de = new DirectoryEntry(guid_LDAP); de.Properties["gpcMachineExtensionNames"].Clear(); de.Properties["gpcMachineExtensionNames"].Add(new_gpcMacExtName); de.Properties["versionnumber"].Clear(); de.Properties["versionnumber"].Add(new_versionnumber); de.CommitChanges(); de.Close(); DirectoryEntry de_check = new DirectoryEntry(); DirectorySearcher ds = new DirectorySearcher(de_check); ds.Filter = "(&(objectCategory=groupPolicyContainer)(name=" + guid_filter + "))"; ds.PageSize = 1000; ds.SizeLimit = 100; ds.PropertiesToLoad.Add("displayname"); ds.PropertiesToLoad.Add("gpcMachineExtensionNames"); ds.PropertiesToLoad.Add("versionnumber"); ds.SearchScope = SearchScope.Subtree; SearchResultCollection src = ds.FindAll(); string results = ""; foreach (SearchResult sr in src) { ResultPropertyCollection myResultPropColl = sr.Properties; foreach (string myKey in myResultPropColl.PropertyNames) { foreach (Object myCollection in myResultPropColl[myKey]) { results += myKey + ": " + myCollection + "\n"; } } } Console.Write("["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Green; Console.Write("+"); Console.ResetColor(); Console.WriteLine("] New Active Directory properties for GPO " + guid_filter + " are: \n\n" + results); } } else if (args[0].Equals("file")) { domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain(); domain_string = domain.Name; guid_filter = args[1]; guid_LDAP = args[2]; gpcMacExtName = args[3]; version_string = args[4]; source_file_path = args[5]; dest_file = args[6]; dest_path = args[7]; dest_file_path = dest_path + "\\" + dest_file; path = @"\\" + domain_string + "\\sysvol\\" + domain_string + "\\policies\\" + guid_filter; start = @"<?xml version=""1.0"" encoding=""utf-8""?><Files clsid=""{215B2E53-57CE-475c-80FE-9EEC14635851}"">"; end = @"</Files>"; immediateFileXMLString = string.Format(@"<File clsid=""{{50BE44C8-567A-4ED1-B1D0-9234FE1F38AF}}"" name=""{1}"" status=""{1}"" image=""0"" changed=""2019-03-30 23:04:20"" uid=""{4}""><Properties action=""C"" fromPath=""{3}"" targetPath=""{2}"" readOnly=""0"" archive=""0"" hidden=""1""/></File>", dest_file, dest_file, dest_file_path, source_file_path, Guid.NewGuid().ToString()); versionnumber = Convert.ToInt32(version_string); new_gpcMacExtName = gpcMacExtName + file_gpcMacExtName; new_versionnumber = versionnumber + 5; if (Directory.Exists(path)) { path += "\\Machine\\Preferences\\Files\\"; } else { Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Red; Console.Write("!"); Console.ResetColor(); Console.WriteLine("] Could not find the specified GPO path!"); } if (!Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } path += "Files.xml"; if (File.Exists(path)) { Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Red; Console.Write("!"); Console.ResetColor(); Console.WriteLine("] Warning, the GPO you are targetting already has a Files.xml. At this time, download the XML at " + path + " and manually insert your file in for creation."); } else { Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Green; Console.Write("+"); Console.ResetColor(); Console.WriteLine("] Creating file " + path); System.IO.File.WriteAllText(path, start + immediateFileXMLString + end); DirectoryEntry de = new DirectoryEntry(guid_LDAP); de.Properties["gpcMachineExtensionNames"].Clear(); de.Properties["gpcMachineExtensionNames"].Add(new_gpcMacExtName); de.Properties["versionnumber"].Clear(); de.Properties["versionnumber"].Add(new_versionnumber); de.CommitChanges(); de.Close(); DirectoryEntry de_check = new DirectoryEntry(); DirectorySearcher ds = new DirectorySearcher(de_check); ds.Filter = "(&(objectCategory=groupPolicyContainer)(name=" + guid_filter + "))"; ds.PageSize = 1000; ds.SizeLimit = 100; ds.PropertiesToLoad.Add("displayname"); ds.PropertiesToLoad.Add("gpcMachineExtensionNames"); ds.PropertiesToLoad.Add("versionnumber"); ds.SearchScope = SearchScope.Subtree; SearchResultCollection src = ds.FindAll(); string results = ""; foreach (SearchResult sr in src) { ResultPropertyCollection myResultPropColl = sr.Properties; foreach (string myKey in myResultPropColl.PropertyNames) { foreach (Object myCollection in myResultPropColl[myKey]) { results += myKey + ": " + myCollection + "\n"; } } } Console.Write("["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Green; Console.Write("+"); Console.ResetColor(); Console.WriteLine("] New Active Directory properties for GPO " + guid_filter + " are: \n\n" + results); } } else if (args[0].Equals("set")) { guid_filter = args[1]; guid_LDAP = args[2]; gpcMacExtName = args[3]; version_string = args[4]; versionnumber = Convert.ToInt32(version_string); DirectoryEntry de = new DirectoryEntry(guid_LDAP); de.Properties["gpcMachineExtensionNames"].Clear(); de.Properties["gpcMachineExtensionNames"].Add(gpcMacExtName); de.Properties["versionnumber"].Clear(); de.Properties["versionnumber"].Add(versionnumber); de.CommitChanges(); de.Close(); DirectoryEntry de_check = new DirectoryEntry(); DirectorySearcher ds = new DirectorySearcher(de_check); ds.Filter = "(&(objectCategory=groupPolicyContainer)(name=" + guid_filter + "))"; ds.PageSize = 1000; ds.SizeLimit = 100; ds.PropertiesToLoad.Add("displayname"); ds.PropertiesToLoad.Add("gpcMachineExtensionNames"); ds.PropertiesToLoad.Add("versionnumber"); ds.SearchScope = SearchScope.Subtree; SearchResultCollection src = ds.FindAll(); string results = ""; foreach (SearchResult sr in src) { ResultPropertyCollection myResultPropColl = sr.Properties; foreach (string myKey in myResultPropColl.PropertyNames) { foreach (Object myCollection in myResultPropColl[myKey]) { results += myKey + ": " + myCollection + "\n"; } } } Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Green; Console.Write("+"); Console.ResetColor(); Console.WriteLine("] New Active Directory properties for GPO " + guid_filter + " are: \n\n" + results); } else if (args[0].Equals("versionset")) { guid_filter = args[1]; guid_LDAP = args[2]; version_string = args[3]; versionnumber = Convert.ToInt32(version_string); new_versionnumber = versionnumber + 5; DirectoryEntry de = new DirectoryEntry(guid_LDAP); de.Properties["versionnumber"].Clear(); de.Properties["versionnumber"].Add(new_versionnumber); de.CommitChanges(); de.Close(); DirectoryEntry de_check = new DirectoryEntry(); DirectorySearcher ds = new DirectorySearcher(de_check); ds.Filter = "(&(objectCategory=groupPolicyContainer)(name=" + guid_filter + "))"; ds.PageSize = 1000; ds.SizeLimit = 100; ds.PropertiesToLoad.Add("displayname"); ds.PropertiesToLoad.Add("versionnumber"); ds.SearchScope = SearchScope.Subtree; SearchResultCollection src = ds.FindAll(); string results = ""; foreach (SearchResult sr in src) { ResultPropertyCollection myResultPropColl = sr.Properties; foreach (string myKey in myResultPropColl.PropertyNames) { foreach (Object myCollection in myResultPropColl[myKey]) { results += myKey + ": " + myCollection + "\n"; } } } Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Green; Console.Write("+"); Console.ResetColor(); Console.WriteLine("] New Active Directory properties for GPO " + guid_filter + " are: \n\n" + results); } else if (args[0].Equals("enable")) { guid_filter = args[1]; guid_LDAP = args[2]; version_string = args[3]; versionnumber = Convert.ToInt32(version_string); new_versionnumber = versionnumber + 5; DirectoryEntry de = new DirectoryEntry(guid_LDAP); de.Properties["versionnumber"].Clear(); de.Properties["versionnumber"].Add(new_versionnumber); de.Properties["flags"].Clear(); de.Properties["flags"].Add(enable_flag); de.CommitChanges(); de.Close(); DirectoryEntry de_check = new DirectoryEntry(); DirectorySearcher ds = new DirectorySearcher(de_check); ds.Filter = "(&(objectCategory=groupPolicyContainer)(name=" + guid_filter + "))"; ds.PageSize = 1000; ds.SizeLimit = 100; ds.PropertiesToLoad.Add("displayname"); ds.PropertiesToLoad.Add("versionnumber"); ds.PropertiesToLoad.Add("flags"); ds.SearchScope = SearchScope.Subtree; SearchResultCollection src = ds.FindAll(); string results = ""; foreach (SearchResult sr in src) { ResultPropertyCollection myResultPropColl = sr.Properties; foreach (string myKey in myResultPropColl.PropertyNames) { foreach (Object myCollection in myResultPropColl[myKey]) { results += myKey + ": " + myCollection + "\n"; } } } Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Green; Console.Write("+"); Console.ResetColor(); Console.WriteLine("] Success! New Active Directory properties for GPO " + guid_filter + " are: \n\n" + results); } else if (args[0].Equals("disable")) { guid_filter = args[1]; guid_LDAP = args[2]; version_string = args[3]; versionnumber = Convert.ToInt32(version_string); new_versionnumber = versionnumber + 5; DirectoryEntry de = new DirectoryEntry(guid_LDAP); de.Properties["versionnumber"].Clear(); de.Properties["versionnumber"].Add(new_versionnumber); de.Properties["flags"].Clear(); de.Properties["flags"].Add(disable_flag); de.CommitChanges(); de.Close(); DirectoryEntry de_check = new DirectoryEntry(); DirectorySearcher ds = new DirectorySearcher(de_check); ds.Filter = "(&(objectCategory=groupPolicyContainer)(name=" + guid_filter + "))"; ds.PageSize = 1000; ds.SizeLimit = 100; ds.PropertiesToLoad.Add("displayname"); ds.PropertiesToLoad.Add("versionnumber"); ds.PropertiesToLoad.Add("flags"); ds.SearchScope = SearchScope.Subtree; SearchResultCollection src = ds.FindAll(); string results = ""; foreach (SearchResult sr in src) { ResultPropertyCollection myResultPropColl = sr.Properties; foreach (string myKey in myResultPropColl.PropertyNames) { foreach (Object myCollection in myResultPropColl[myKey]) { results += myKey + ": " + myCollection + "\n"; } } } Console.Write("["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Green; Console.Write("+"); Console.ResetColor(); Console.WriteLine("] Success! New Active Directory properties for GPO " + guid_filter + " are: \n\n" + results); } else { Console.WriteLine(help); } } else { Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Red; Console.Write("!"); Console.ResetColor(); Console.WriteLine("] Error: Not enough arguments. Type help to see usage."); } } catch (System.Runtime.InteropServices.COMException excep) { string error = excep.ToString(); if (error.Contains("\nAccess is denied")) { Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Red; Console.Write("!"); Console.ResetColor(); Console.WriteLine("] Access is denied"); } else if (error.Contains("\nA referral was returned from the server")) { Console.Write("\n["); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Red; Console.Write("!"); Console.ResetColor(); Console.WriteLine("] Invalid LDAP path."); } else { Console.WriteLine(error); } System.Environment.Exit(-1); } }
public void UpdateTrustRelationship(Domain targetDomain, TrustDirection newTrustDirection) { base.CheckIfDisposed(); if (targetDomain != null) { if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional) { throw new InvalidEnumArgumentException("newTrustDirection", (int)newTrustDirection, typeof(TrustDirection)); } else { string str = TrustHelper.CreateTrustPassword(); TrustHelper.UpdateTrustDirection(this.context, base.Name, targetDomain.Name, str, false, newTrustDirection); TrustDirection trustDirection = 0; if ((newTrustDirection & TrustDirection.Inbound) != 0) { trustDirection = trustDirection | TrustDirection.Outbound; } if ((newTrustDirection & TrustDirection.Outbound) != 0) { trustDirection = trustDirection | TrustDirection.Inbound; } TrustHelper.UpdateTrustDirection(targetDomain.GetDirectoryContext(), targetDomain.Name, base.Name, str, false, trustDirection); return; } } else { throw new ArgumentNullException("targetDomain"); } }
public bool Contains(Domain domain) { Contract.Requires(domain != null); return default(bool); }
public void CreateTrustRelationship(Domain targetDomain, TrustDirection direction) { base.CheckIfDisposed(); if (targetDomain != null) { if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) { throw new InvalidEnumArgumentException("direction", (int)direction, typeof(TrustDirection)); } else { string str = TrustHelper.CreateTrustPassword(); TrustHelper.CreateTrust(this.context, base.Name, targetDomain.GetDirectoryContext(), targetDomain.Name, false, direction, str); int num = 0; if ((direction & TrustDirection.Inbound) != 0) { num = num | 2; } if ((direction & TrustDirection.Outbound) != 0) { num = num | 1; } TrustHelper.CreateTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, this.context, base.Name, false, (TrustDirection)num, str); return; } } else { throw new ArgumentNullException("targetDomain"); } }
static void Main(string[] args) { string domain = ""; string domainController = ""; string searchScope = ""; string searchBase = ""; bool verbose = false; var Options = new Options(); if (CommandLineParser.Default.ParseArguments(args, Options)) { if (Options.help == true) { PrintHelp(); return; } if (!string.IsNullOrEmpty(Options.domain)) { domain = Options.domain; } if (string.IsNullOrEmpty(Options.searchScope)) { searchScope = "SubTree"; } else { searchScope = Options.searchScope; } if (!string.IsNullOrEmpty(Options.domainController)) { domainController = Options.domainController; } if (Options.verbose) { verbose = true; } if (!string.IsNullOrEmpty(Options.searchBase)) { searchBase = Options.searchBase; } } var listEnableLUA = new List <string>(); var listFilterAdministratorToken = new List <string>(); var listLocalAccountTokenFilterPolicy = new List <string>(); var listSeDenyNetworkLogonRight = new List <string>(); var listSeDenyRemoteInteractiveLogonRight = new List <string>(); var computerPolicyEnableLUA = new List <string>(); var computerPolicyFilterAdministratorToken = new List <string>(); var computerPolicyLocalAccountTokenFilterPolicy = new List <string>(); var computerPolicySeDenyNetworkLogonRight = new List <string>(); var computerPolicySeDenyRemoteInteractiveLogonRight = new List <string>(); //discover current domain System.DirectoryServices.ActiveDirectory.Domain current_domain = null; if (string.IsNullOrEmpty(domain)) { try { current_domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain(); domain = current_domain.Name; } catch { Console.WriteLine("[!] Cannot enumerate domain.\n"); return; } } else { DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, domain); try { current_domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext); } catch { Console.WriteLine("\n[!] The specified domain does not exist or cannot be contacted. Exiting...\n"); return; } } if (string.IsNullOrEmpty(Options.domainController)) { domainController = current_domain.FindDomainController().Name; } else { var ldapId = new LdapDirectoryIdentifier(Options.domainController); using (var testConnection = new LdapConnection(ldapId)) { try { testConnection.Bind(); } catch { Console.WriteLine("\n[!] The specified domain controller cannot be contacted. Exiting...\n"); return; } } } domain = domain.ToLower(); String[] DC_array = null; String distinguished_name = null; distinguished_name = "CN=Policies,CN=System"; DC_array = domain.Split('.'); foreach (String DC in DC_array) { distinguished_name += ",DC=" + DC; } System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(domainController, 389); System.DirectoryServices.Protocols.LdapConnection connection = null; connection = new System.DirectoryServices.Protocols.LdapConnection(identifier); connection.SessionOptions.Sealing = true; connection.SessionOptions.Signing = true; try { connection.Bind(); } catch { Console.WriteLine("The domain controller cannot be contacted. Exiting...\n"); return; } SearchRequest requestGUID = null; if (string.Equals(searchScope, "SubTree")) { requestGUID = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "cn=*", System.DirectoryServices.Protocols.SearchScope.Subtree, null); } else if (string.Equals(searchScope, "OneLevel")) { requestGUID = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "cn=*", System.DirectoryServices.Protocols.SearchScope.OneLevel, null); } else if (string.Equals(searchScope, "Base")) { requestGUID = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "cn=*", System.DirectoryServices.Protocols.SearchScope.Base, null); } SearchResponse responseGUID = null; try { responseGUID = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(requestGUID); } catch { Console.WriteLine("\n[!] Search scope is not valid. Exiting...\n"); return; } if (!string.IsNullOrEmpty(Options.searchBase)) { string adPath = "LDAP://" + domain + searchBase; if (!DirectoryEntry.Exists(adPath)) { Console.WriteLine("\n[!] Search base {0} is not valid. Exiting...\n", adPath); return; } } Console.WriteLine("\n[-] Domain Controller is: {0}\n[-] Domain is: {1}\n", domainController, domain); foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in responseGUID.Entries) { try { var requestAttributes = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "cn=" + entry.Attributes["cn"][0].ToString(), System.DirectoryServices.Protocols.SearchScope.OneLevel, null); var responseAttributes = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(requestAttributes); foreach (System.DirectoryServices.Protocols.SearchResultEntry attribute in responseAttributes.Entries) { try { string displayName = entry.Attributes["displayName"][0].ToString(); string name = entry.Attributes["name"][0].ToString(); string gpcfilesyspath = entry.Attributes["gpcfilesyspath"][0].ToString(); string uncPathGptTmpl = gpcfilesyspath + @"\Machine\Microsoft\Windows NT\SecEdit\GptTmpl.inf"; bool enableLUA = CheckEnableLUA(uncPathGptTmpl); if (enableLUA) { if (verbose) { Console.WriteLine("[+] The following GPO enables pass-the-hash by disabling EnableLUA: {0} {1}", displayName, name); } listEnableLUA.Add(name); } bool FilterAdministratorToken = CheckFilterAdministratorToken(uncPathGptTmpl); if (FilterAdministratorToken) { if (verbose) { Console.WriteLine("[+] The following GPO exempts the RID 500 account from UAC protection by disabling FilterAdministratorToken: {0} {1}", displayName, name); } listFilterAdministratorToken.Add(name); } string uncPathRegistryXML = gpcfilesyspath + @"\MACHINE\Preferences\Registry\Registry.xml"; bool LocalAccountTokenFilterPolicy = CheckLocalAccountTokenFilterPolicy(uncPathRegistryXML); if (LocalAccountTokenFilterPolicy) { if (verbose) { Console.WriteLine("[+] The following GPO enables pass-the-hash by enabling LocalAccountTokenFilterPolicy: {0} {1}", displayName, name); } listLocalAccountTokenFilterPolicy.Add(name); } bool SeDenyNetworkLogonRight = CheckSeDenyNetworkLogonRight(uncPathGptTmpl); if (SeDenyNetworkLogonRight) { if (verbose) { Console.WriteLine("[+] The following GPO includes the built-in Administrators group within the SeDenyNetworkLogonRight: {0} {1}", displayName, name); } listSeDenyNetworkLogonRight.Add(name); } bool SeDenyRemoteInteractiveLogonRight = CheckSeDenyRemoteInteractiveLogonRight(uncPathGptTmpl); if (SeDenyRemoteInteractiveLogonRight) { if (verbose) { Console.WriteLine("[+] The following GPO includes the built-in Administrators group within the SeDenyRemoteInteractiveLogonRight: {0} {1}\n", displayName, name); } listSeDenyRemoteInteractiveLogonRight.Add(name); } } catch { Console.WriteLine("[!] It was not possible to retrieve the displayname, name and gpcfilesypath...\n"); return; } } } catch { Console.WriteLine("[!] It was not possible to retrieve GPO Policies...\n"); return; } } Console.Write("\n[+] EnableLUA: \t\t\t\t"); foreach (var guid in listEnableLUA) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicyEnableLUA.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicyEnableLUA.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } //Console.Write("\n"); Console.Write("\n[+] FilterAdministratorToken: \t\t"); foreach (var guid in listFilterAdministratorToken) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicyFilterAdministratorToken.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicyFilterAdministratorToken.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.Write("\n"); Console.Write("[+] LocalAccountTokenFilterPolicy: \t"); foreach (var guid in listLocalAccountTokenFilterPolicy) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicyLocalAccountTokenFilterPolicy.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicyLocalAccountTokenFilterPolicy.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.Write("\n"); Console.Write("[+] SeDenyNetworkLogonRight: \t\t"); foreach (var guid in listSeDenyNetworkLogonRight) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicySeDenyNetworkLogonRight.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicySeDenyNetworkLogonRight.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.Write("\n"); Console.Write("[+] SeDenyRemoteInteractiveLogonRight: \t"); foreach (var guid in listSeDenyRemoteInteractiveLogonRight) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicySeDenyRemoteInteractiveLogonRight.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicySeDenyRemoteInteractiveLogonRight.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.Write("\n"); }
public void UpdateTrustRelationship (Domain targetDomain, TrustDirection newTrustDirection) { throw new NotImplementedException (); }
public void RepairTrustRelationship(Domain targetDomain) { TrustDirection trustDirection = TrustDirection.Bidirectional; base.CheckIfDisposed(); if (targetDomain != null) { try { trustDirection = this.GetTrustRelationship(targetDomain.Name).TrustDirection; if ((trustDirection & TrustDirection.Outbound) != 0) { TrustHelper.VerifyTrust(this.context, base.Name, targetDomain.Name, false, TrustDirection.Outbound, true, null); } if ((trustDirection & TrustDirection.Inbound) != 0) { TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, base.Name, false, TrustDirection.Outbound, true, null); } } catch (ActiveDirectoryOperationException activeDirectoryOperationException) { this.RepairTrustHelper(targetDomain, trustDirection); } catch (UnauthorizedAccessException unauthorizedAccessException) { this.RepairTrustHelper(targetDomain, trustDirection); } catch (ActiveDirectoryObjectNotFoundException activeDirectoryObjectNotFoundException) { object[] name = new object[3]; name[0] = base.Name; name[1] = targetDomain.Name; name[2] = trustDirection; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("WrongTrustDirection", name), typeof(TrustRelationshipInformation), null); } return; } else { throw new ArgumentNullException("targetDomain"); } }
internal int Add(Domain domain) => InnerList.Add(domain);
public void VerifyTrustRelationship(Domain targetDomain, TrustDirection direction) { base.CheckIfDisposed(); if (targetDomain != null) { if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) { throw new InvalidEnumArgumentException("direction", (int)direction, typeof(TrustDirection)); } else { if ((direction & TrustDirection.Outbound) != 0) { try { TrustHelper.VerifyTrust(this.context, base.Name, targetDomain.Name, false, TrustDirection.Outbound, false, null); } catch (ActiveDirectoryObjectNotFoundException activeDirectoryObjectNotFoundException) { object[] name = new object[3]; name[0] = base.Name; name[1] = targetDomain.Name; name[2] = direction; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("WrongTrustDirection", name), typeof(TrustRelationshipInformation), null); } } if ((direction & TrustDirection.Inbound) != 0) { try { TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, base.Name, false, TrustDirection.Outbound, false, null); } catch (ActiveDirectoryObjectNotFoundException activeDirectoryObjectNotFoundException1) { object[] objArray = new object[3]; objArray[0] = base.Name; objArray[1] = targetDomain.Name; objArray[2] = direction; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("WrongTrustDirection", objArray), typeof(TrustRelationshipInformation), null); } } return; } } else { throw new ArgumentNullException("targetDomain"); } }
private void RepairTrustHelper(Domain targetDomain, TrustDirection direction) { // now we try changing trust password on both sides string password = TrustHelper.CreateTrustPassword(); // first reset trust password on remote side string targetServerName = TrustHelper.UpdateTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, password, false); // then reset trust password on local side string sourceServerName = TrustHelper.UpdateTrust(context, Name, targetDomain.Name, password, false); // last we reset the secure channel again to make sure info is replicated and trust is indeed ready now // verify outbound trust first if ((direction & TrustDirection.Outbound) != 0) { try { TrustHelper.VerifyTrust(context, Name, targetDomain.Name, false /*not forest*/, TrustDirection.Outbound, true /*reset secure channel*/, targetServerName /* need to specify which target server */); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null); } } // verify inbound trust if ((direction & TrustDirection.Inbound) != 0) { try { TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false /*not forest*/, TrustDirection.Outbound, true/*reset secure channel*/, sourceServerName /* need to specify which target server */); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null); } } }
public void DeleteTrustRelationship(Domain targetDomain) { base.CheckIfDisposed(); if (targetDomain != null) { TrustHelper.DeleteTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, base.Name, false); TrustHelper.DeleteTrust(this.context, base.Name, targetDomain.Name, false); return; } else { throw new ArgumentNullException("targetDomain"); } }
public void DeleteTrustRelationship(Domain targetDomain) { CheckIfDisposed(); if (targetDomain == null) throw new ArgumentNullException("targetDomain"); // first delete the trust on the remote side TrustHelper.DeleteTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false); // then delete the local side trust TrustHelper.DeleteTrust(context, Name, targetDomain.Name, false); }
/// <summary> /// Gets domain computer objects for which remote access policies are applied via GPO. /// </summary> /// <author>Dennis Panagiotopoulos (@den_n1s)</author> /// <param name="Domain">pecifies the domain to use for the query, defaults to the current domain.</param> /// <param name="DomainController">Specifies an Active Directory server (domain controller) to bind to.</param> /// <param name="SearchScope">Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).</param> /// <param name="SearchBase">The LDAP source to search through, e.g. /OU=Workstations,DC=domain,DC=local. Useful for OU queries.</param> /// <returns>True if execution succeeds, false otherwise.</returns> /// <remarks> /// Credits to Jon Cave (@joncave) and William Knowles (@william_knows) for their PowerShell implementation. /// https://labs.mwrinfosecurity.com/blog/enumerating-remote-access-policies-through-gpo/ /// </remarks> public static bool GetRemoteAccessPolicies(string Domain, string DomainController, string SearchScope, string SearchBase) { if (string.IsNullOrEmpty(SearchScope)) { SearchScope = "SubTree"; } if (string.IsNullOrEmpty(SearchBase)) { SearchBase = ""; } var listEnableLUA = new List <string>(); var listFilterAdministratorToken = new List <string>(); var listLocalAccountTokenFilterPolicy = new List <string>(); var listSeDenyNetworkLogonRight = new List <string>(); var listSeDenyRemoteInteractiveLogonRight = new List <string>(); var computerPolicyEnableLUA = new List <string>(); var computerPolicyFilterAdministratorToken = new List <string>(); var computerPolicyLocalAccountTokenFilterPolicy = new List <string>(); var computerPolicySeDenyNetworkLogonRight = new List <string>(); var computerPolicySeDenyRemoteInteractiveLogonRight = new List <string>(); //discover current domain System.DirectoryServices.ActiveDirectory.Domain current_domain = null; if (string.IsNullOrEmpty(Domain)) { try { current_domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain(); Domain = current_domain.Name; } catch { Console.Error.WriteLine("[!] Cannot enumerate domain.\n"); return(false); } } else { DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, Domain); try { current_domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext); } catch { Console.Error.WriteLine("[!] The specified domain does not exist or cannot be contacted.\n"); return(false); } } //retrieve domain controller if (string.IsNullOrEmpty(DomainController)) { DomainController = current_domain.FindDomainController().Name; } else { var ldapId = new LdapDirectoryIdentifier(DomainController); using (var testConnection = new LdapConnection(ldapId)) { try { testConnection.Bind(); } catch { Console.Error.WriteLine("[!] The specified domain controller cannot be contacted.\n"); return(false); } } } Domain = Domain.ToLower(); String[] DC_array = null; String distinguished_name = null; distinguished_name = "CN=Policies,CN=System"; DC_array = Domain.Split('.'); foreach (String DC in DC_array) { distinguished_name += ",DC=" + DC; } LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(DomainController, 389); LdapConnection connection = null; //make the connection to the domain controller connection = new LdapConnection(identifier); connection.SessionOptions.Sealing = true; connection.SessionOptions.Signing = true; try { connection.Bind(); } catch { Console.Error.WriteLine("Domain controller cannot be contacted.\n"); return(false); } SearchRequest requestGUID = null; if (string.Equals(SearchScope, "SubTree")) { requestGUID = new SearchRequest(distinguished_name, "cn=*", System.DirectoryServices.Protocols.SearchScope.Subtree, null); } else if (string.Equals(SearchScope, "OneLevel")) { requestGUID = new SearchRequest(distinguished_name, "cn=*", System.DirectoryServices.Protocols.SearchScope.OneLevel, null); } else if (string.Equals(SearchScope, "Base")) { requestGUID = new SearchRequest(distinguished_name, "cn=*", System.DirectoryServices.Protocols.SearchScope.Base, null); } SearchResponse responseGUID = null; try { responseGUID = (SearchResponse)connection.SendRequest(requestGUID); } catch { Console.Error.WriteLine("Search scope is not valid.\n"); return(false); } if (!string.IsNullOrEmpty(SearchBase)) { string adPath = "LDAP://" + Domain + SearchBase; if (!DirectoryEntry.Exists(adPath)) { Console.Error.WriteLine("[!] Search base is not valid.\n"); return(false); } } foreach (SearchResultEntry entry in responseGUID.Entries) { try { var requestAttributes = new SearchRequest(distinguished_name, "cn=" + entry.Attributes["cn"][0].ToString(), System.DirectoryServices.Protocols.SearchScope.OneLevel, null); var responseAttributes = (SearchResponse)connection.SendRequest(requestAttributes); foreach (SearchResultEntry attribute in responseAttributes.Entries) { try { string displayName = entry.Attributes["displayName"][0].ToString(); string name = entry.Attributes["name"][0].ToString(); string gpcfilesyspath = entry.Attributes["gpcfilesyspath"][0].ToString(); string uncPathGptTmpl = gpcfilesyspath + @"\Machine\Microsoft\Windows NT\SecEdit\GptTmpl.inf"; bool enableLUA = GetEnableLua(uncPathGptTmpl); if (enableLUA) { listEnableLUA.Add(name); } bool FilterAdministratorToken = GetFilterAdministratorToken(uncPathGptTmpl); if (FilterAdministratorToken) { listFilterAdministratorToken.Add(name); } string uncPathRegistryXML = gpcfilesyspath + @"\MACHINE\Preferences\Registry\Registry.xml"; bool LocalAccountTokenFilterPolicy = GetLocalAccountTokenFilterPolicy(uncPathRegistryXML); if (LocalAccountTokenFilterPolicy) { listLocalAccountTokenFilterPolicy.Add(name); } bool SeDenyNetworkLogonRight = GetSeDenyNetworkLogonRight(uncPathGptTmpl); if (SeDenyNetworkLogonRight) { listSeDenyNetworkLogonRight.Add(name); } bool SeDenyRemoteInteractiveLogonRight = GetSeDenyRemoteInteractiveLogonRight(uncPathGptTmpl); if (SeDenyRemoteInteractiveLogonRight) { listSeDenyRemoteInteractiveLogonRight.Add(name); } } catch { Console.Error.WriteLine("[!] It was not possible to retrieve the displayname, name and gpcfilesypath\n"); return(false); } } } catch { Console.Error.WriteLine("[!] It was not possible to retrieve GPO Policies\n"); return(false); } } Console.Write("[+] EnableLUA: \t\t\t\t"); foreach (var guid in listEnableLUA) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(SearchBase)) { startingPoint = new DirectoryEntry("LDAP://" + Domain); } else { startingPoint = new DirectoryEntry("LDAP://" + Domain + SearchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicyEnableLUA.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicyEnableLUA.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.WriteLine(); Console.Write("[+] FilterAdministratorToken: \t\t"); foreach (var guid in listFilterAdministratorToken) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(SearchBase)) { startingPoint = new DirectoryEntry("LDAP://" + Domain); } else { startingPoint = new DirectoryEntry("LDAP://" + Domain + SearchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicyFilterAdministratorToken.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicyFilterAdministratorToken.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.WriteLine(); Console.Write("[+] LocalAccountTokenFilterPolicy: \t"); foreach (var guid in listLocalAccountTokenFilterPolicy) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(SearchBase)) { startingPoint = new DirectoryEntry("LDAP://" + Domain); } else { startingPoint = new DirectoryEntry("LDAP://" + Domain + SearchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicyLocalAccountTokenFilterPolicy.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicyLocalAccountTokenFilterPolicy.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.WriteLine(); Console.Write("[+] SeDenyNetworkLogonRight: \t\t"); foreach (var guid in listSeDenyNetworkLogonRight) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(SearchBase)) { startingPoint = new DirectoryEntry("LDAP://" + Domain); } else { startingPoint = new DirectoryEntry("LDAP://" + Domain + SearchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicySeDenyNetworkLogonRight.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicySeDenyNetworkLogonRight.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.WriteLine(); Console.Write("[+] SeDenyRemoteInteractiveLogonRight: \t"); foreach (var guid in listSeDenyRemoteInteractiveLogonRight) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(SearchBase)) { startingPoint = new DirectoryEntry("LDAP://" + Domain); } else { startingPoint = new DirectoryEntry("LDAP://" + Domain + SearchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicySeDenyRemoteInteractiveLogonRight.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicySeDenyRemoteInteractiveLogonRight.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.WriteLine(); Console.WriteLine("[-] Enumeration finished"); return(true); }
public void VerifyTrustRelationship(Domain targetDomain, TrustDirection direction) { CheckIfDisposed(); if (targetDomain == null) throw new ArgumentNullException("targetDomain"); if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional) throw new InvalidEnumArgumentException("direction", (int)direction, typeof(TrustDirection)); // verify outbound trust first if ((direction & TrustDirection.Outbound) != 0) { try { TrustHelper.VerifyTrust(context, Name, targetDomain.Name, false/*not forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null); } } // verify inbound trust if ((direction & TrustDirection.Inbound) != 0) { try { TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false/*not forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.WrongTrustDirection, Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null); } } }