internal ReplicationConnection(DirectoryContext context, DirectoryEntry connectionEntry, string name) { this.context = context; this.cachedDirectoryEntry = connectionEntry; this.connectionName = name; this.existingConnection = true; }
public ApplicationPartition(DirectoryContext context, string distinguishedName) { this.appType = ApplicationPartitionType.Unknown; this.committed = true; this.ValidateApplicationPartitionParameters(context, distinguishedName, null, false); this.CreateApplicationPartition(distinguishedName, "domainDns"); }
//private NativeComInterfaces.IAdsPathname pathCracker; internal DirectoryEntryManager(DirectoryContext context) { this.directoryEntries = new Hashtable(); this.context = context; //this.pathCracker = (NativeComInterfaces.IAdsPathname)(new NativeComInterfaces.Pathname()); //this.pathCracker.EscapedMode = 2; }
// Internal Constructors internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, ApplicationPartitionType appType, DirectoryEntryManager directoryEntryMgr) : base(context, distinguishedName) { this.directoryEntryMgr = directoryEntryMgr; _appType = appType; _dnsName = dnsName; }
internal ForestTrustRelationshipInformation(DirectoryContext context, string source, DS_DOMAIN_TRUSTS unmanagedTrust, TrustType type) { string tmpDNSName = null; string tmpNetBIOSName = null; // security context this.context = context; // source this.source = source; // target if (unmanagedTrust.DnsDomainName != (IntPtr)0) tmpDNSName = Marshal.PtrToStringUni(unmanagedTrust.DnsDomainName); if (unmanagedTrust.NetbiosDomainName != (IntPtr)0) tmpNetBIOSName = Marshal.PtrToStringUni(unmanagedTrust.NetbiosDomainName); this.target = (tmpDNSName == null ? tmpNetBIOSName : tmpDNSName); // direction if ((unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND) != 0 && (unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND) != 0) direction = TrustDirection.Bidirectional; else if ((unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND) != 0) direction = TrustDirection.Outbound; else if ((unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND) != 0) direction = TrustDirection.Inbound; // type this.type = type; }
protected void Page_Load(object sender, EventArgs e) { // TODO this todo was here for ages var dc = new DirectoryContext(DirectoryContextType.Domain, "ptsecurity.ru"); var address = Request.Params["address"]; var filter = "Address=" + address; var result = ""; var domain = Domain.GetDomain(dc); // this is our vulnerabilitiy of LDAP injection *in this file* // FIXED: AI issue #3, High, LDAP Injection, https://github.com/SDLTestAccount/IT/issues/3 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx?address=%7bfilter%7d+%3d+* HTTP/1.1 // Host:localhost var ds = new DirectorySearcher(domain.GetDirectoryEntry());//, filter); using (var src = ds.FindAll()) { // TODO it was edit here by developer 1 year ago foreach (var res in src) { result = res.ToString(); } } // let's go // this is our first vulnerability of XSS in this file // we will demonstrate False Positive scenario here (FP Marker) // FP: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1 // Host:localhost // (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>")) Response.Write(result); // this is our second vulnerability of XSS in this file // we will demonstrate what happen if developer fails with his fix (VERIFY Marker) // FIXED: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1 // Host:localhost // (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>")) Response.Write("result"); // this is our third vulnerability of XSS in this file // we will demonstrate what happen if we really fix vulnerability (VERIFY Marker) // FIXED: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1 // Host:localhost // (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>")) Response.Write("result"); // this is our fourth vulnerability of XSS in this file // we will demonstrate what happen if developer want to cheat (FIXED Marker) // FIXED: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1 // Host:localhost // (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>")) Response.Write("result"); }
public static void CreateAdamSite(string targetName, string newSiteName) { try { // assemble the connection string using the host name and the port assigned to ADAM string adamConnectionString = targetName; DirectoryContext adamContext = new DirectoryContext( DirectoryContextType.DirectoryServer, adamConnectionString); ActiveDirectorySite site = new ActiveDirectorySite(adamContext, newSiteName); // set site options site.Options = ActiveDirectorySiteOptions.GroupMembershipCachingEnabled; // commit the site to the directory site.Save(); Console.WriteLine("\nSite \"{0}\" was created successfully", site); } catch (Exception e) { Console.WriteLine("\r\nUnexpected exception occured:\n\t{0}\n{1}", e.GetType().Name, e.Message); } }
public ActiveDirectorySchemaProperty(DirectoryContext context, string ldapDisplayName) { this.syntax = ~ActiveDirectorySyntax.CaseExactString; this.rangeLower = null; this.rangeUpper = null; this.linkId = null; if (context == null) { throw new ArgumentNullException("context"); } if ((context.Name == null) && !context.isRootDomain()) { throw new ArgumentException(Res.GetString("ContextNotAssociatedWithDomain"), "context"); } if (((context.Name != null) && !context.isRootDomain()) && (!context.isADAMConfigSet() && !context.isServer())) { throw new ArgumentException(Res.GetString("NotADOrADAM"), "context"); } if (ldapDisplayName == null) { throw new ArgumentNullException("ldapDisplayName"); } if (ldapDisplayName.Length == 0) { throw new ArgumentException(Res.GetString("EmptyStringParameter"), "ldapDisplayName"); } this.context = new DirectoryContext(context); this.schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.SchemaNamingContext); this.schemaEntry.Bind(true); this.ldapDisplayName = ldapDisplayName; this.commonName = ldapDisplayName; this.isBound = false; }
internal ActiveDirectorySubnetCollection(DirectoryContext context, string siteDN) { this.context = context; this.siteDN = siteDN; Hashtable table = new Hashtable(); this.changeList = Hashtable.Synchronized(table); }
public ActiveDirectorySubnet(DirectoryContext context, string subnetName) { ValidateArgument(context, subnetName); context = new DirectoryContext(context); this.context = context; this.name = subnetName; DirectoryEntry directoryEntry = null; try { directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string str = (string) PropertyManager.GetPropertyValue(context, directoryEntry, PropertyManager.ConfigurationNamingContext); string dn = "CN=Subnets,CN=Sites," + str; directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, dn); string escapedPath = Utils.GetEscapedPath("cn=" + this.name); this.cachedEntry = directoryEntry.Children.Add(escapedPath, "subnet"); } catch (COMException exception) { ExceptionHelper.GetExceptionFromCOMException(context, exception); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryOperationException(Res.GetString("ADAMInstanceNotFoundInConfigSet", new object[] { context.Name })); } finally { if (directoryEntry != null) { directoryEntry.Dispose(); } } }
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectorySchedule schedule, ActiveDirectoryTransportType transport) { ValidateArgument(context, name); if (sourceServer == null) { throw new ArgumentNullException("sourceServer"); } if ((transport < ActiveDirectoryTransportType.Rpc) || (transport > ActiveDirectoryTransportType.Smtp)) { throw new InvalidEnumArgumentException("value", (int) transport, typeof(ActiveDirectoryTransportType)); } context = new DirectoryContext(context); this.ValidateTargetAndSourceServer(context, sourceServer); this.context = context; this.connectionName = name; this.transport = transport; DirectoryEntry directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { string str = (string) PropertyManager.GetPropertyValue(context, directoryEntry, PropertyManager.ServerName); string dn = "CN=NTDS Settings," + str; directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, dn); string escapedPath = Utils.GetEscapedPath("cn=" + this.connectionName); this.cachedDirectoryEntry = directoryEntry.Children.Add(escapedPath, "nTDSConnection"); DirectoryContext context2 = sourceServer.Context; directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context2, WellKnownDN.RootDSE); string str4 = (string) PropertyManager.GetPropertyValue(context2, directoryEntry, PropertyManager.ServerName); str4 = "CN=NTDS Settings," + str4; this.cachedDirectoryEntry.Properties["fromServer"].Add(str4); if (schedule != null) { this.cachedDirectoryEntry.Properties["schedule"].Value = schedule.GetUnmanagedSchedule(); } string dNFromTransportType = Utils.GetDNFromTransportType(this.TransportType, context); directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, dNFromTransportType); try { directoryEntry.Bind(true); } catch (COMException exception) { if (((exception.ErrorCode == -2147016656) && Utils.CheckCapability(DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE), Capability.ActiveDirectoryApplicationMode)) && (transport == ActiveDirectoryTransportType.Smtp)) { throw new NotSupportedException(Res.GetString("NotSupportTransportSMTP")); } throw ExceptionHelper.GetExceptionFromCOMException(context, exception); } this.cachedDirectoryEntry.Properties["transportType"].Add(dNFromTransportType); this.cachedDirectoryEntry.Properties["enabledConnection"].Value = false; this.cachedDirectoryEntry.Properties["options"].Value = 0; } catch (COMException exception2) { throw ExceptionHelper.GetExceptionFromCOMException(context, exception2); } finally { directoryEntry.Close(); } }
internal TrustRelationshipInformation(DirectoryContext context, string source, TrustObject obj) { string netbiosDomainName; this.context = context; this.source = source; TrustRelationshipInformation trustRelationshipInformation = this; if (obj.DnsDomainName == null) { netbiosDomainName = obj.NetbiosDomainName; } else { netbiosDomainName = obj.DnsDomainName; } trustRelationshipInformation.target = netbiosDomainName; if ((obj.Flags & 2) == 0 || (obj.Flags & 32) == 0) { if ((obj.Flags & 2) == 0) { if ((obj.Flags & 32) != 0) { this.direction = TrustDirection.Inbound; } } else { this.direction = TrustDirection.Outbound; } } else { this.direction = TrustDirection.Bidirectional; } this.type = obj.TrustType; }
public ApplicationPartition(DirectoryContext context, string distinguishedName, string objectClass) { this.appType = ApplicationPartitionType.Unknown; this.committed = true; this.ValidateApplicationPartitionParameters(context, distinguishedName, objectClass, true); this.CreateApplicationPartition(distinguishedName, objectClass); }
// it seems it may return null? public static ReplicationConnection FindByName(DirectoryContext context, string name) { Contract.Requires(context != null); Contract.Requires(!string.IsNullOrEmpty(name)); return default(ReplicationConnection); }
internal ConfigurationSet(DirectoryContext context, string configSetName, DirectoryEntryManager directoryEntryMgr) { this.cachedSecurityLevel = ~ReplicationSecurityLevel.NegotiatePassThrough; this.context = context; this.configSetName = configSetName; this.directoryEntryMgr = directoryEntryMgr; }
public static string FriendlyDomainToLdapDomain(string friendlyDomainName) { DirectoryContext objContext = new DirectoryContext(DirectoryContextType.Domain, friendlyDomainName); Domain domain = Domain.GetDomain(objContext); return domain.Name; }
public static DomainControllerCollection FindAll(DirectoryContext context) { Contract.Requires(context != null); Contract.Requires(context.ContextType == DirectoryContextType.Domain); return default(DomainControllerCollection); }
public ApplicationPartition(DirectoryContext context, string distinguishedName, string objectClass) { // validate the parameters ValidateApplicationPartitionParameters(context, distinguishedName, objectClass, true); // call private function for creating the application partition CreateApplicationPartition(distinguishedName, objectClass); }
internal ActiveDirectorySiteLinkBridge(DirectoryContext context, string bridgeName, ActiveDirectoryTransportType transport, bool existing) { this.links = new ActiveDirectorySiteLinkCollection(); this.context = context; this.name = bridgeName; this.transport = transport; this.existing = existing; }
public static ActiveDirectoryInterSiteTransport FindByTransportType(DirectoryContext context, ActiveDirectoryTransportType transport) { Contract.Requires(context != null); Contract.Ensures(Contract.Result<ActiveDirectoryInterSiteTransport>() != null); return default(ActiveDirectoryInterSiteTransport); }
// Public Constructors public ApplicationPartition(DirectoryContext context, string distinguishedName) { // validate the parameters ValidateApplicationPartitionParameters(context, distinguishedName, null, false); // call private function for creating the application partition CreateApplicationPartition(distinguishedName, "domainDns"); }
public static ActiveDirectorySchemaClass FindByName(DirectoryContext context, string ldapDisplayName) { Contract.Requires(context != null); Contract.Ensures(Contract.Result<ActiveDirectorySchemaClass>() != null); return default(System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaClass); }
public static System.DirectoryServices.ActiveDirectory.DomainController FindOne(DirectoryContext context, string siteName) { Contract.Requires(context != null); Contract.Requires(context.ContextType == DirectoryContextType.Domain); Contract.Requires(siteName != null); return default(System.DirectoryServices.ActiveDirectory.DomainController); }
internal ActiveDirectorySubnetCollection(DirectoryContext context, string siteDN) { _context = context; _siteDN = siteDN; Hashtable tempTable = new Hashtable(); changeList = Hashtable.Synchronized(tempTable); }
internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, ApplicationPartitionType appType, DirectoryEntryManager directoryEntryMgr) : base(context, distinguishedName) { this.appType = ApplicationPartitionType.Unknown; this.committed = true; base.directoryEntryMgr = directoryEntryMgr; this.appType = appType; this.dnsName = dnsName; }
public ActiveDirectorySiteLink(DirectoryContext context, string siteLinkName, ActiveDirectoryTransportType transport, ActiveDirectorySchedule schedule) { DirectoryEntry directoryEntry; this.systemDefaultInterval = new TimeSpan(0, 15, 0); this.sites = new ActiveDirectorySiteCollection(); ValidateArgument(context, siteLinkName, transport); context = new DirectoryContext(context); this.context = context; this.name = siteLinkName; this.transport = transport; try { directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string str = (string) PropertyManager.GetPropertyValue(context, directoryEntry, PropertyManager.ConfigurationNamingContext); string dn = null; if (transport == ActiveDirectoryTransportType.Rpc) { dn = "CN=IP,CN=Inter-Site Transports,CN=Sites," + str; } else { dn = "CN=SMTP,CN=Inter-Site Transports,CN=Sites," + str; } directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, dn); } catch (COMException exception) { throw ExceptionHelper.GetExceptionFromCOMException(context, exception); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryOperationException(Res.GetString("ADAMInstanceNotFoundInConfigSet", new object[] { context.Name })); } try { string escapedPath = Utils.GetEscapedPath("cn=" + this.name); this.cachedEntry = directoryEntry.Children.Add(escapedPath, "siteLink"); this.cachedEntry.Properties["cost"].Value = 100; this.cachedEntry.Properties["replInterval"].Value = 180; if (schedule != null) { this.cachedEntry.Properties["schedule"].Value = schedule.GetUnmanagedSchedule(); } } catch (COMException exception2) { if (((exception2.ErrorCode == -2147016656) && Utils.CheckCapability(DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE), Capability.ActiveDirectoryApplicationMode)) && (transport == ActiveDirectoryTransportType.Smtp)) { throw new NotSupportedException(Res.GetString("NotSupportTransportSMTP")); } throw ExceptionHelper.GetExceptionFromCOMException(context, exception2); } finally { directoryEntry.Dispose(); } }
public static System.DirectoryServices.ActiveDirectory.ActiveDirectorySiteLink FindByName(DirectoryContext context, string siteLinkName) { Contract.Requires(context != null); Contract.Requires(siteLinkName != null); Contract.Ensures(Contract.Result<ActiveDirectorySiteLink>() != null); return default(System.DirectoryServices.ActiveDirectory.ActiveDirectorySiteLink); }
internal DirectoryServerCollection(DirectoryContext context, string siteDN, string transportName) { Hashtable tempTable = new Hashtable(); changeList = Hashtable.Synchronized(tempTable); this.context = context; this.siteDN = siteDN; this.transportDN = transportName; }
internal Forest(DirectoryContext context, string forestDnsName, DirectoryEntryManager directoryEntryMgr) { this.dsHandle = IntPtr.Zero; this.authIdentity = IntPtr.Zero; this.currentForestMode = ~System.DirectoryServices.ActiveDirectory.ForestMode.Windows2000Forest; this.context = context; this.directoryEntryMgr = directoryEntryMgr; this.forestDnsName = forestDnsName; }
public static Forest GetForest(DirectoryContext dc) { Forest fr = new Forest(); fr.fName = dc.Name; fr.DC = dc; return fr; }
public ActiveDirectorySiteLinkBridge(DirectoryContext context, string bridgeName) : this(context, bridgeName, ActiveDirectoryTransportType.Rpc) { }
public static ConfigurationSet GetConfigurationSet(DirectoryContext context) { // check that the argument is not null if (context == null) { throw new ArgumentNullException(nameof(context)); } // target should ConfigurationSet or DirectoryServer if ((context.ContextType != DirectoryContextType.ConfigurationSet) && (context.ContextType != DirectoryContextType.DirectoryServer)) { throw new ArgumentException(SR.TargetShouldBeServerORConfigSet, nameof(context)); } // target should be an adam config set or server if (((!context.isServer()) && (!context.isADAMConfigSet()))) { // the target should be a server or an ADAM Config Set if (context.ContextType == DirectoryContextType.ConfigurationSet) { throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ConfigurationSet), context.Name); } else { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound, context.Name), typeof(ConfigurationSet), null); } } // work with copy of the context context = new DirectoryContext(context); // // bind to rootdse of an adam instance (if target is already a server, verify that it is an adam instance) // DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry? rootDSE = null; string configSetName; try { rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryApplicationMode))) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound, context.Name), typeof(ConfigurationSet), null); } configSetName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.ConfigurationNamingContext) !; } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked ((int)0x8007203a)) { if (context.ContextType == DirectoryContextType.ConfigurationSet) { throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ConfigurationSet), context.Name); } else { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound, context.Name), typeof(ConfigurationSet), null); } } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } catch (ActiveDirectoryObjectNotFoundException) { if (context.ContextType == DirectoryContextType.ConfigurationSet) { // this is the case when we could not find an ADAM instance in that config set throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ConfigurationSet), context.Name); } else { throw; } } // return config set object return(new ConfigurationSet(context, configSetName, directoryEntryMgr)); }
internal ReplicationCursorCollection ConstructReplicationCursors(IntPtr dsHandle, bool advanced, IntPtr info, string partition, DirectoryServer server, LoadLibrarySafeHandle libHandle) { int context = 0; int count = 0; ReplicationCursorCollection collection = new ReplicationCursorCollection(server); // construct the collection if (advanced) { // using paging to get all the results while (true) { try { if (info != (IntPtr)0) { DS_REPL_CURSORS_3 cursors = new DS_REPL_CURSORS_3(); Marshal.PtrToStructure(info, cursors); count = cursors.cNumCursors; if (count > 0) { collection.AddHelper(partition, cursors, advanced, info); } context = cursors.dwEnumerationContext; // we already get all the results or there is no result if (context == -1 || count == 0) { break; } } else { // should not happen, treat as no result is returned. break; } } finally { FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_3_FOR_NC, info, libHandle); } // get the next batch of results info = GetReplicationInfoHelper(dsHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_3_FOR_NC, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_FOR_NC, partition, ref advanced, context, libHandle); } } else { try { if (info != (IntPtr)0) { // structure of DS_REPL_CURSORS_3 and DS_REPL_CURSORS actually are the same DS_REPL_CURSORS cursors = new DS_REPL_CURSORS(); Marshal.PtrToStructure(info, cursors); collection.AddHelper(partition, cursors, advanced, info); } } finally { FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_FOR_NC, info, libHandle); } } return(collection); }
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectorySchedule schedule) : this(context, name, sourceServer, schedule, ActiveDirectoryTransportType.Rpc) { }
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectorySchedule schedule, ActiveDirectoryTransportType transport) { ValidateArgument(context, name); if (sourceServer == null) { throw new ArgumentNullException("sourceServer"); } if (transport < ActiveDirectoryTransportType.Rpc || transport > ActiveDirectoryTransportType.Smtp) { throw new InvalidEnumArgumentException("value", (int)transport, typeof(ActiveDirectoryTransportType)); } // work with copy of the context context = new DirectoryContext(context); ValidateTargetAndSourceServer(context, sourceServer); this.context = context; _connectionName = name; _transport = transport; DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName); string connectionContainer = "CN=NTDS Settings," + serverDN; de = DirectoryEntryManager.GetDirectoryEntry(context, connectionContainer); // create the connection entry string rdn = "cn=" + _connectionName; rdn = Utils.GetEscapedPath(rdn); cachedDirectoryEntry = de.Children.Add(rdn, "nTDSConnection"); // set all the properties // sourceserver property DirectoryContext sourceServerContext = sourceServer.Context; de = DirectoryEntryManager.GetDirectoryEntry(sourceServerContext, WellKnownDN.RootDSE); string serverName = (string)PropertyManager.GetPropertyValue(sourceServerContext, de, PropertyManager.ServerName); serverName = "CN=NTDS Settings," + serverName; cachedDirectoryEntry.Properties["fromServer"].Add(serverName); // schedule property if (schedule != null) { cachedDirectoryEntry.Properties["schedule"].Value = schedule.GetUnmanagedSchedule(); } // transporttype property string transportPath = Utils.GetDNFromTransportType(TransportType, context); // verify that the transport is supported de = DirectoryEntryManager.GetDirectoryEntry(context, transportPath); try { de.Bind(true); } catch (COMException e) { if (e.ErrorCode == unchecked ((int)0x80072030)) { // if it is ADAM and transport type is SMTP, throw NotSupportedException. DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp) { throw new NotSupportedException(SR.NotSupportTransportSMTP); } } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } cachedDirectoryEntry.Properties["transportType"].Add(transportPath); // enabledConnection property cachedDirectoryEntry.Properties["enabledConnection"].Value = false; // options cachedDirectoryEntry.Properties["options"].Value = 0; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { de.Close(); } }
internal static DirectoryEntry GetDirectoryEntry(DirectoryContext context, WellKnownDN dn) { return(GetDirectoryEntry(context, ExpandWellKnownDN(context, dn))); }
internal ActiveDirectoryInterSiteTransport(DirectoryContext context, ActiveDirectoryTransportType transport, DirectoryEntry entry) { this.context = context; this.transport = transport; this.cachedEntry = entry; }
public static ActiveDirectoryInterSiteTransport FindByTransportType(DirectoryContext context, ActiveDirectoryTransportType transport) { DirectoryEntry directoryEntry; if (context == null) { throw new ArgumentNullException("context"); } if ((context.Name == null) && !context.isRootDomain()) { throw new ArgumentException(Res.GetString("ContextNotAssociatedWithDomain"), "context"); } if (((context.Name != null) && !context.isRootDomain()) && (!context.isServer() && !context.isADAMConfigSet())) { throw new ArgumentException(Res.GetString("NotADOrADAM"), "context"); } if ((transport < ActiveDirectoryTransportType.Rpc) || (transport > ActiveDirectoryTransportType.Smtp)) { throw new InvalidEnumArgumentException("value", (int)transport, typeof(ActiveDirectoryTransportType)); } context = new DirectoryContext(context); try { directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string str = (string)PropertyManager.GetPropertyValue(context, directoryEntry, PropertyManager.ConfigurationNamingContext); string dn = "CN=Inter-Site Transports,CN=Sites," + str; if (transport == ActiveDirectoryTransportType.Rpc) { dn = "CN=IP," + dn; } else { dn = "CN=SMTP," + dn; } directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, dn); } catch (COMException exception) { throw ExceptionHelper.GetExceptionFromCOMException(context, exception); } catch (ActiveDirectoryObjectNotFoundException) { throw new ActiveDirectoryOperationException(Res.GetString("ADAMInstanceNotFoundInConfigSet", new object[] { context.Name })); } try { directoryEntry.RefreshCache(new string[] { "options" }); } catch (COMException exception2) { if (exception2.ErrorCode != -2147016656) { throw ExceptionHelper.GetExceptionFromCOMException(context, exception2); } if (Utils.CheckCapability(DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE), Capability.ActiveDirectoryApplicationMode) && (transport == ActiveDirectoryTransportType.Smtp)) { throw new NotSupportedException(Res.GetString("NotSupportTransportSMTP")); } throw new ActiveDirectoryObjectNotFoundException(Res.GetString("TransportNotFound", new object[] { transport.ToString() }), typeof(ActiveDirectoryInterSiteTransport), transport.ToString()); } return(new ActiveDirectoryInterSiteTransport(context, transport, directoryEntry)); }
internal static Exception GetExceptionFromCOMException(DirectoryContext context, COMException e) { Exception exception; int errorCode = e.ErrorCode; string errorMessage = e.Message; // // Check if we can throw a more specific exception // if (errorCode == unchecked ((int)0x80070005)) { // // Access Denied // exception = new UnauthorizedAccessException(errorMessage, e); } else if (errorCode == unchecked ((int)0x8007052e)) { // // Logon Failure // exception = new AuthenticationException(errorMessage, e); } else if (errorCode == unchecked ((int)0x8007202f)) { // // Constraint Violation // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked ((int)0x80072035)) { // // Unwilling to perform // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked ((int)0x80071392)) { // // Object already exists // exception = new ActiveDirectoryObjectExistsException(errorMessage, e); } else if (errorCode == unchecked ((int)0x80070008)) { // // No Memory // exception = new OutOfMemoryException(); } else if ((errorCode == unchecked ((int)0x8007203a)) || (errorCode == unchecked ((int)0x8007200e)) || (errorCode == unchecked ((int)0x8007200f))) { // // ServerDown/Unavailable/Busy // if (context != null) { exception = new ActiveDirectoryServerDownException(errorMessage, e, errorCode, context.GetServerName()); } else { exception = new ActiveDirectoryServerDownException(errorMessage, e, errorCode, null); } } else { // // Wrap the exception in a generic OperationException // exception = new ActiveDirectoryOperationException(errorMessage, e, errorCode); } return(exception); }
public static ActiveDirectorySchema GetSchema(DirectoryContext context) { if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be Forest, DirectoryServer or ConfigurationSet if ((context.ContextType != DirectoryContextType.Forest) && (context.ContextType != DirectoryContextType.ConfigurationSet) && (context.ContextType != DirectoryContextType.DirectoryServer)) { throw new ArgumentException(SR.NotADOrADAM, "context"); } if ((context.Name == null) && (!context.isRootDomain())) { throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(ActiveDirectorySchema), null); } if (context.Name != null) { // the target should be a valid forest name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer()))) { if (context.ContextType == DirectoryContextType.Forest) { throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(ActiveDirectorySchema), context.Name); } else if (context.ContextType == DirectoryContextType.ConfigurationSet) { throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name); } else { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound, context.Name), typeof(ActiveDirectorySchema), null); } } } // work with copy of the context context = new DirectoryContext(context); DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context); string schemaNC = null; try { DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryOrADAM))) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound, context.Name), typeof(ActiveDirectorySchema), null); } schemaNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.SchemaNamingContext); } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked ((int)0x8007203a)) { if (context.ContextType == DirectoryContextType.Forest) { throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(ActiveDirectorySchema), context.Name); } else if (context.ContextType == DirectoryContextType.ConfigurationSet) { throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name); } else { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound, context.Name), typeof(ActiveDirectorySchema), null); } } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } catch (ActiveDirectoryObjectNotFoundException) { if (context.ContextType == DirectoryContextType.ConfigurationSet) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name); } else { throw; } } return(new ActiveDirectorySchema(context, schemaNC, directoryEntryMgr)); }
internal static ReadOnlyActiveDirectorySchemaPropertyCollection GetAllProperties(DirectoryContext context, DirectoryEntry schemaEntry, string filter) { ArrayList propertyList = new ArrayList(); string[] propertiesToLoad = new string[3]; propertiesToLoad[0] = PropertyManager.LdapDisplayName; propertiesToLoad[1] = PropertyManager.Cn; propertiesToLoad[2] = PropertyManager.IsDefunct; ADSearcher searcher = new ADSearcher(schemaEntry, filter, propertiesToLoad, SearchScope.OneLevel); SearchResultCollection resCol = null; try { resCol = searcher.FindAll(); foreach (SearchResult res in resCol) { string ldapDisplayName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.LdapDisplayName); DirectoryEntry directoryEntry = res.GetDirectoryEntry(); directoryEntry.AuthenticationType = Utils.DefaultAuthType; directoryEntry.Username = context.UserName; directoryEntry.Password = context.Password; bool isDefunct = false; if ((res.Properties[PropertyManager.IsDefunct] != null) && (res.Properties[PropertyManager.IsDefunct].Count > 0)) { isDefunct = (bool)res.Properties[PropertyManager.IsDefunct][0]; } if (isDefunct) { string commonName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.Cn); propertyList.Add(new ActiveDirectorySchemaProperty(context, commonName, ldapDisplayName, directoryEntry, schemaEntry)); } else { propertyList.Add(new ActiveDirectorySchemaProperty(context, ldapDisplayName, directoryEntry, schemaEntry)); } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { // dispose off the result collection if (resCol != null) { resCol.Dispose(); } } return(new ReadOnlyActiveDirectorySchemaPropertyCollection(propertyList)); }
internal ActiveDirectorySchema(DirectoryContext context, string distinguishedName, DirectoryEntryManager directoryEntryMgr) : base(context, distinguishedName) { this.directoryEntryMgr = directoryEntryMgr; _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, distinguishedName); }
public static ActiveDirectorySiteLinkBridge FindByName(DirectoryContext context, string bridgeName) { return(FindByName(context, bridgeName, ActiveDirectoryTransportType.Rpc)); }
internal static string ExpandWellKnownDN(DirectoryContext context, WellKnownDN dn) { string?distinguishedName = null; switch (dn) { case WellKnownDN.RootDSE: { distinguishedName = "RootDSE"; break; } case WellKnownDN.RootDomainNamingContext: { DirectoryEntry rootDSE = GetDirectoryEntry(context, "RootDSE"); try { distinguishedName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.RootDomainNamingContext) !; } finally { rootDSE.Dispose(); } break; } case WellKnownDN.DefaultNamingContext: { DirectoryEntry rootDSE = GetDirectoryEntry(context, "RootDSE"); try { distinguishedName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DefaultNamingContext) !; } finally { rootDSE.Dispose(); } break; } case WellKnownDN.SchemaNamingContext: { DirectoryEntry rootDSE = GetDirectoryEntry(context, "RootDSE"); try { distinguishedName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.SchemaNamingContext) !; } finally { rootDSE.Dispose(); } break; } case WellKnownDN.ConfigurationNamingContext: { DirectoryEntry rootDSE = GetDirectoryEntry(context, "RootDSE"); try { distinguishedName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.ConfigurationNamingContext) !; } finally { rootDSE.Dispose(); } break; } case WellKnownDN.PartitionsContainer: { distinguishedName = "CN=Partitions," + ExpandWellKnownDN(context, WellKnownDN.ConfigurationNamingContext); break; } case WellKnownDN.SitesContainer: { distinguishedName = "CN=Sites," + ExpandWellKnownDN(context, WellKnownDN.ConfigurationNamingContext); break; } case WellKnownDN.SystemContainer: { distinguishedName = "CN=System," + ExpandWellKnownDN(context, WellKnownDN.DefaultNamingContext); break; } case WellKnownDN.RidManager: { distinguishedName = "CN=RID Manager$," + ExpandWellKnownDN(context, WellKnownDN.SystemContainer); break; } case WellKnownDN.Infrastructure: { distinguishedName = "CN=Infrastructure," + ExpandWellKnownDN(context, WellKnownDN.DefaultNamingContext); break; } default: // should not happen throw new InvalidEnumArgumentException(nameof(dn), (int)dn, typeof(WellKnownDN)); } return(distinguishedName); }
public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) { string propertyValue = null; DirectoryEntryManager directoryEntryManager = null; if (context != null) { if (context.ContextType == DirectoryContextType.DirectoryServer) { if (context.isServer()) { context = new DirectoryContext(context); try { directoryEntryManager = new DirectoryEntryManager(context); DirectoryEntry directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (Utils.CheckCapability(directoryEntry, Capability.ActiveDirectory)) { propertyValue = (string)PropertyManager.GetPropertyValue(context, directoryEntry, PropertyManager.DnsHostName); bool flag = bool.Parse((string)PropertyManager.GetPropertyValue(context, directoryEntry, PropertyManager.IsGlobalCatalogReady)); if (!flag) { object[] name = new object[1]; name[0] = context.Name; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("GCNotFound", name), typeof(GlobalCatalog), context.Name); } } else { object[] objArray = new object[1]; objArray[0] = context.Name; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("GCNotFound", objArray), typeof(GlobalCatalog), context.Name); } } catch (COMException cOMException1) { COMException cOMException = cOMException1; int errorCode = cOMException.ErrorCode; if (errorCode != -2147016646) { throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException); } else { object[] name1 = new object[1]; name1[0] = context.Name; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("GCNotFound", name1), typeof(GlobalCatalog), context.Name); } } return(new GlobalCatalog(context, propertyValue, directoryEntryManager)); } else { object[] objArray1 = new object[1]; objArray1[0] = context.Name; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("GCNotFound", objArray1), typeof(GlobalCatalog), context.Name); } } else { throw new ArgumentException(Res.GetString("TargetShouldBeGC"), "context"); } } else { throw new ArgumentNullException("context"); } }
internal static GlobalCatalog FindOneWithCredentialValidation(DirectoryContext context, string siteName, LocatorOptions flag) { bool flag1 = false; bool flag2 = false; context = new DirectoryContext(context); GlobalCatalog globalCatalog = GlobalCatalog.FindOneInternal(context, context.Name, siteName, flag); using (globalCatalog) { if (flag2) { try { DomainController.ValidateCredential(globalCatalog, context); } catch (COMException cOMException1) { COMException cOMException = cOMException1; if (cOMException.ErrorCode != -2147016646) { throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException); } else { if ((flag & LocatorOptions.ForceRediscovery) != 0) { object[] name = new object[1]; name[0] = context.Name; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("GCNotFoundInForest", name), typeof(GlobalCatalog), null); } else { flag1 = true; } } } } } if (flag1) { flag2 = false; globalCatalog = GlobalCatalog.FindOneInternal(context, context.Name, siteName, flag | LocatorOptions.ForceRediscovery); using (globalCatalog) { if (flag2) { try { DomainController.ValidateCredential(globalCatalog, context); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; if (cOMException2.ErrorCode != -2147016646) { throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException2); } else { object[] objArray = new object[1]; objArray[0] = context.Name; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("GCNotFoundInForest", objArray), typeof(GlobalCatalog), null); } } } } } return(globalCatalog); }
internal static DirectoryEntry GetDirectoryEntryInternal(DirectoryContext context, string path) { return(Bind(path, context.UserName, context.Password, context.useServerBind())); }
internal new static GlobalCatalog FindOneInternal(DirectoryContext context, string forestName, string siteName, LocatorOptions flag) { DomainControllerInfo domainControllerInfo = null; DomainControllerInfo domainControllerInfo1 = null; int num = 0; if (siteName == null || siteName.Length != 0) { if (((int)flag & -23554) == 0) { if (forestName == null) { int num1 = Locator.DsGetDcNameWrapper(null, DirectoryContext.GetLoggedOnDomain(), null, (long)16, out domainControllerInfo1); if (num1 != 0x54b) { if (num1 == 0) { forestName = domainControllerInfo1.DnsForestName; } else { throw ExceptionHelper.GetExceptionFromErrorCode(num); } } else { throw new ActiveDirectoryObjectNotFoundException(Res.GetString("ContextNotAssociatedWithDomain"), typeof(GlobalCatalog), null); } } num = Locator.DsGetDcNameWrapper(null, forestName, siteName, (int)flag | 80, out domainControllerInfo); if (num != 0x54b) { if (num != 0x3ec) { if (num == 0) { string str = domainControllerInfo.DomainControllerName.Substring(2); DirectoryContext newDirectoryContext = Utils.GetNewDirectoryContext(str, DirectoryContextType.DirectoryServer, context); return(new GlobalCatalog(newDirectoryContext, str)); } else { throw ExceptionHelper.GetExceptionFromErrorCode(num); } } else { throw new ArgumentException(Res.GetString("InvalidFlags"), "flag"); } } else { object[] objArray = new object[1]; objArray[0] = forestName; throw new ActiveDirectoryObjectNotFoundException(Res.GetString("GCNotFoundInForest", objArray), typeof(GlobalCatalog), null); } } else { throw new ArgumentException(Res.GetString("InvalidFlags"), "flag"); } } else { throw new ArgumentException(Res.GetString("EmptyStringParameter"), "siteName"); } }
public static ActiveDirectorySubnet FindByName(DirectoryContext context, string subnetName) { ValidateArgument(context, subnetName); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext) !; string subnetdn = "CN=Subnets,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, subnetdn); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } try { ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=subnet)(objectCategory=subnet)(name=" + Utils.GetEscapedFilterValue(subnetName) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* don't need paged search */ false /* don't need to cache result */); SearchResult?srchResult = adSearcher.FindOne(); if (srchResult == null) { // no such subnet object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySubnet), subnetName); throw e; } else { string? siteName = null; DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry(); // try to get the site that this subnet lives in if (connectionEntry.Properties.Contains("siteObject")) { NativeComInterfaces.IAdsPathname pathCracker = (NativeComInterfaces.IAdsPathname) new NativeComInterfaces.Pathname(); // need to turn off the escaping for name pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_OFF_EX; string tmp = (string)connectionEntry.Properties["siteObject"][0] !; // escaping manipulation pathCracker.Set(tmp, NativeComInterfaces.ADS_SETTYPE_DN); string rdn = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); Debug.Assert(rdn != null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); siteName = rdn.Substring(3); } // it is an existing subnet object ActiveDirectorySubnet?subnet = null; if (siteName == null) { subnet = new ActiveDirectorySubnet(context, subnetName, null, true); } else { subnet = new ActiveDirectorySubnet(context, subnetName, siteName, true); } subnet.cachedEntry = connectionEntry; return(subnet); } } catch (COMException e) { if (e.ErrorCode == unchecked ((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySubnet), subnetName); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { if (de != null) { de.Dispose(); } } }
private void ValidateTargetAndSourceServer(DirectoryContext context, DirectoryServer sourceServer) { bool targetIsDC = false; DirectoryEntry targetDE = null; DirectoryEntry sourceDE = null; // first find out target is a dc or ADAM instance targetDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { if (Utils.CheckCapability(targetDE, Capability.ActiveDirectory)) { targetIsDC = true; } else if (!Utils.CheckCapability(targetDE, Capability.ActiveDirectoryApplicationMode)) { // if it is also not an ADAM instance, it is invalid then throw new ArgumentException(SR.DirectoryContextNeedHost, "context"); } if (targetIsDC && !(sourceServer is DomainController)) { // target and sourceServer are not of the same type throw new ArgumentException(SR.ConnectionSourcServerShouldBeDC, "sourceServer"); } else if (!targetIsDC && (sourceServer is DomainController)) { // target and sourceServer are not of the same type throw new ArgumentException(SR.ConnectionSourcServerShouldBeADAM, "sourceServer"); } sourceDE = DirectoryEntryManager.GetDirectoryEntry(sourceServer.Context, WellKnownDN.RootDSE); // now if they are both dc, we need to check whether they come from the same forest if (targetIsDC) { string targetRoot = (string)PropertyManager.GetPropertyValue(context, targetDE, PropertyManager.RootDomainNamingContext); string sourceRoot = (string)PropertyManager.GetPropertyValue(sourceServer.Context, sourceDE, PropertyManager.RootDomainNamingContext); if (Utils.Compare(targetRoot, sourceRoot) != 0) { throw new ArgumentException(SR.ConnectionSourcServerSameForest, "sourceServer"); } } else { string targetRoot = (string)PropertyManager.GetPropertyValue(context, targetDE, PropertyManager.ConfigurationNamingContext); string sourceRoot = (string)PropertyManager.GetPropertyValue(sourceServer.Context, sourceDE, PropertyManager.ConfigurationNamingContext); if (Utils.Compare(targetRoot, sourceRoot) != 0) { throw new ArgumentException(SR.ConnectionSourcServerSameConfigSet, "sourceServer"); } } } catch (COMException e) { ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { if (targetDE != null) { targetDE.Close(); } if (sourceDE != null) { sourceDE.Close(); } } }
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectoryTransportType transport) : this(context, name, sourceServer, null, transport) { }
public static System.DirectoryServices.ActiveDirectory.Domain Get_Domain(Args_Get_Domain args = null) { if (args == null) { args = new Args_Get_Domain(); } if (args.Credential != null) { Logger.Write_Verbose("[Get-Domain] Using alternate credentials for Get-Domain"); string TargetDomain; if (args.Domain.IsNotNullOrEmpty()) { TargetDomain = args.Domain; } else { // if no domain is supplied, extract the logon domain from the PSCredential passed TargetDomain = args.Credential.Domain; Logger.Write_Verbose("[Get-Domain] Extracted domain '$TargetDomain' from -Credential"); } var DomainContext = new System.DirectoryServices.ActiveDirectory.DirectoryContext(System.DirectoryServices.ActiveDirectory.DirectoryContextType.Domain, TargetDomain, args.Credential.UserName, args.Credential.Password); try { return(System.DirectoryServices.ActiveDirectory.Domain.GetDomain(DomainContext)); } catch (Exception e) { Logger.Write_Verbose($"[Get-Domain] The specified domain '{TargetDomain}' does not exist, could not be contacted, there isn't an existing trust, or the specified credentials are invalid: {e}"); } } else if (args.Domain.IsNotNullOrEmpty()) { var DomainContext = new System.DirectoryServices.ActiveDirectory.DirectoryContext(System.DirectoryServices.ActiveDirectory.DirectoryContextType.Domain, args.Domain); try { return(System.DirectoryServices.ActiveDirectory.Domain.GetDomain(DomainContext)); } catch (Exception e) { Logger.Write_Verbose($"[Get-Domain] The specified domain '{args.Domain}' does not exist, could not be contacted, or there isn't an existing trust : {e}"); } } else { try { return(System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain()); } catch (ActiveDirectoryOperationException err) { Logger.Write_Verbose($"[Get-Domain] Error retrieving the current domain, Maybe not in domain"); } catch (Exception e) { Logger.Write_Verbose($"[Get-Domain] Error retrieving the current domain: {e}"); } } return(null); }
internal GlobalCatalog(DirectoryContext context, string globalCatalogName, DirectoryEntryManager directoryEntryMgr) : base(context, globalCatalogName, directoryEntryMgr) { }
public ActiveDirectorySiteLinkBridge(DirectoryContext context, string bridgeName, ActiveDirectoryTransportType transport) { ValidateArgument(context, bridgeName, transport); // work with copy of the context context = new DirectoryContext(context); this.context = context; _name = bridgeName; _transport = transport; // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string parentDN = null; if (transport == ActiveDirectoryTransportType.Rpc) { parentDN = "CN=IP,CN=Inter-Site Transports,CN=Sites," + config; } else { parentDN = "CN=SMTP,CN=Inter-Site Transports,CN=Sites," + config; } de = DirectoryEntryManager.GetDirectoryEntry(context, parentDN); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } try { string rdn = "cn=" + _name; rdn = Utils.GetEscapedPath(rdn); cachedEntry = de.Children.Add(rdn, "siteLinkBridge"); } catch (COMException e) { if (e.ErrorCode == unchecked ((int)0x80072030)) { // if it is ADAM and transport type is SMTP, throw NotSupportedException. DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp) { throw new NotSupportedException(SR.NotSupportTransportSMTP); } } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { de.Dispose(); } }
public static ForestEx Get_Forest(Args_Get_Forest args = null) { if (args == null) { args = new Args_Get_Forest(); } var ForestObject = new ForestEx(); if (args.Credential != null) { Logger.Write_Verbose(@"[Get-Forest] Using alternate credentials for Get-Forest"); string TargetForest = null; if (args.Forest.IsNotNullOrEmpty()) { TargetForest = args.Forest; } else { // if no domain is supplied, extract the logon domain from the PSCredential passed TargetForest = args.Credential.Domain; Logger.Write_Verbose(@"[Get-Forest] Extracted domain '$Forest' from -Credential"); } var ForestContext = new System.DirectoryServices.ActiveDirectory.DirectoryContext(System.DirectoryServices.ActiveDirectory.DirectoryContextType.Forest, TargetForest, args.Credential.UserName, args.Credential.Password); try { ForestObject.Forest = System.DirectoryServices.ActiveDirectory.Forest.GetForest(ForestContext); } catch (Exception e) { Logger.Write_Verbose($@"[Get-Forest] The specified forest '{TargetForest}' does not exist, could not be contacted, there isn't an existing trust, or the specified credentials are invalid: {e}"); } } else if (args.Forest.IsNotNullOrEmpty()) { var ForestContext = new System.DirectoryServices.ActiveDirectory.DirectoryContext(System.DirectoryServices.ActiveDirectory.DirectoryContextType.Forest, args.Forest); try { ForestObject.Forest = System.DirectoryServices.ActiveDirectory.Forest.GetForest(ForestContext); } catch (Exception e) { Logger.Write_Verbose($@"[Get-Forest] The specified forest '{args.Forest}' does not exist, could not be contacted, or there isn't an existing trust: {e}"); } } else { // otherwise use the current forest ForestObject.Forest = System.DirectoryServices.ActiveDirectory.Forest.GetCurrentForest(); } if (ForestObject.Forest != null) { // get the SID of the forest root string ForestSid = null; if (args.Credential != null) { ForestSid = (GetDomainUser.Get_DomainUser(new Args_Get_DomainUser { Identity = new[] { @"krbtgt" }, Domain = ForestObject.Forest.RootDomain.Name, Credential = args.Credential }).First() as LDAPProperty).objectsid?.First(); } else { ForestSid = (GetDomainUser.Get_DomainUser(new Args_Get_DomainUser { Identity = new[] { @"krbtgt" }, Domain = ForestObject.Forest.RootDomain.Name }).First() as LDAPProperty).objectsid?.First(); } var Parts = ForestSid.Split('-'); ForestSid = string.Join(@"-", Parts.Take(Parts.Length - 2 + 1)); ForestObject.RootDomainSid = ForestSid; return(ForestObject); } return(null); }
internal GlobalCatalog(DirectoryContext context, string globalCatalogName) : base(context, globalCatalogName) { }
internal AdamInstance(DirectoryContext context, string adamInstanceName) : this(context, adamInstanceName, new DirectoryEntryManager(context), true) { }
internal DirectoryEntryManager(DirectoryContext context) { _context = context; _pathCracker = (NativeComInterfaces.IAdsPathname) new NativeComInterfaces.Pathname(); _pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_ON; }
internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string sourceServer, int option, LoadLibrarySafeHandle libHandle) { int structSize = Marshal.SizeOf(typeof(Guid)); IntPtr unmanagedGuid = (IntPtr)0; Guid guid = Guid.Empty; AdamInstance adamServer = null; DomainController dcServer = null; unmanagedGuid = Marshal.AllocHGlobal(structSize); try { if (sourceServer != null) { DirectoryContext newContext = Utils.GetNewDirectoryContext(sourceServer, DirectoryContextType.DirectoryServer, context); if (isADAM) { adamServer = AdamInstance.GetAdamInstance(newContext); guid = adamServer.NtdsaObjectGuid; } else { dcServer = DomainController.GetDomainController(newContext); guid = dcServer.NtdsaObjectGuid; } Marshal.StructureToPtr(guid, unmanagedGuid, false); } // call DsReplicaSyncW IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } UnsafeNativeMethods.DsReplicaSyncW dsReplicaSyncW = (UnsafeNativeMethods.DsReplicaSyncW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaSyncW)); int result = dsReplicaSyncW(dsHandle, partition, unmanagedGuid, (int)option); // check the result if (result != 0) { if (!Partitions.Contains(partition)) { throw new ArgumentException(SR.ServerNotAReplica, nameof(partition)); } string serverDownName = null; // this is the error returned when the server that we want to sync from is down if (result == ExceptionHelper.RPC_S_SERVER_UNAVAILABLE) { serverDownName = sourceServer; } // this is the error returned when the server that we want to get synced is down else if (result == ExceptionHelper.RPC_S_CALL_FAILED) { serverDownName = Name; } throw ExceptionHelper.GetExceptionFromErrorCode(result, serverDownName); } } finally { if (unmanagedGuid != (IntPtr)0) { Marshal.FreeHGlobal(unmanagedGuid); } if (adamServer != null) { adamServer.Dispose(); } if (dcServer != null) { dcServer.Dispose(); } } }
public static ActiveDirectorySiteLinkBridge FindByName(DirectoryContext context, string bridgeName, ActiveDirectoryTransportType transport) { ValidateArgument(context, bridgeName, transport); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string containerDN = "CN=Inter-Site Transports,CN=Sites," + config; if (transport == ActiveDirectoryTransportType.Rpc) { containerDN = "CN=IP," + containerDN; } else { containerDN = "CN=SMTP," + containerDN; } de = DirectoryEntryManager.GetDirectoryEntry(context, containerDN); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } try { ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=siteLinkBridge)(objectCategory=SiteLinkBridge)(name=" + Utils.GetEscapedFilterValue(bridgeName) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* don't need paged search */ false /* don't need to cache result */); SearchResult srchResult = adSearcher.FindOne(); if (srchResult == null) { // no such site link bridge object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLinkBridge), bridgeName); throw e; } else { DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry(); // it is an existing site link bridge object ActiveDirectorySiteLinkBridge bridge = new ActiveDirectorySiteLinkBridge(context, bridgeName, transport, true); bridge.cachedEntry = connectionEntry; return(bridge); } } catch (COMException e) { if (e.ErrorCode == unchecked ((int)0x80072030)) { // if it is ADAM and transport type is SMTP, throw NotSupportedException. DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp) { throw new NotSupportedException(SR.NotSupportTransportSMTP); } else { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLinkBridge), bridgeName); } } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { de.Dispose(); } }