From cc0b4fda216728ba6320d2ef5519f395ca9935a4 Mon Sep 17 00:00:00 2001 From: Steve Harter Date: Tue, 19 Nov 2024 13:53:26 -0600 Subject: [PATCH] Avoid exception when parsing AD path for port number --- .../AccountManagement/AD/ADStoreCtx.cs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs index e1a28506696cc..fb844377ea4c6 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs @@ -2405,6 +2405,9 @@ protected enum StoreCapabilityMap // Must be called inside of lock(domainInfoLock) protected virtual void LoadDomainInfo() { + const int LdapDefaultPort = 389; + const int LdapsDefaultPort = 636; + GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "LoadComputerInfo"); Debug.Assert(this.ctxBase != null); @@ -2418,12 +2421,22 @@ protected virtual void LoadDomainInfo() this.dnsHostName = ADUtils.GetServerName(this.ctxBase); // Pull the requested port number - Uri ldapUri = new Uri(this.ctxBase.Path); - int port = ldapUri.Port != -1 ? ldapUri.Port : (ldapUri.Scheme.ToUpperInvariant() == "LDAPS" ? 636 : 389); + int port = LdapDefaultPort; + if (Uri.TryCreate(ctxBase.Path, UriKind.Absolute, out Uri ldapUri)) + { + if (ldapUri.Port != -1) + { + port = ldapUri.Port; + } + else if (string.Equals(ldapUri.Scheme, "LDAPS", StringComparison.OrdinalIgnoreCase)) + { + port = LdapsDefaultPort; + } + } string dnsDomainName = ""; - using (DirectoryEntry rootDse = new DirectoryEntry("LDAP://" + this.dnsHostName + ":" + port + "/rootDse", "", "", AuthenticationTypes.Anonymous)) + using (DirectoryEntry rootDse = new DirectoryEntry($"LDAP://{this.dnsHostName}:{port}/rootDse", "", "", AuthenticationTypes.Anonymous)) { this.defaultNamingContext = (string)rootDse.Properties["defaultNamingContext"][0]; this.contextBasePartitionDN = this.defaultNamingContext;