public Task StartAsync(CancellationToken cancellationToken) { if (_httpListener.IsListening) { throw new InvalidOperationException("The listener is already active"); } var listenerUri = ListenerUris[0]; var prefix = listenerUri.ToString(); prefix = prefix .Replace($"{UriSchemeWebSocket}:", $"{Uri.UriSchemeHttp}:") .Replace($"{UriSchemeWebSocketSecure}:", $"{Uri.UriSchemeHttps}:") .Replace("://localhost", "://*"); _httpListener.Prefixes.Add(prefix); if (_bindCertificateToPort && _tlsCertificate != null && listenerUri.Scheme.Equals(UriSchemeWebSocketSecure)) { var ipPort = new IPEndPoint(IPAddress.Parse("0.0.0.0"), listenerUri.Port); var config = new CertificateBindingConfiguration(); config.Bind( new CertificateBinding( _tlsCertificate.Thumbprint, _tlsCertificate.Store, ipPort, _applicationId)); } _httpListener.Start(); _acceptTransportCts?.Dispose(); _acceptTransportCts = new CancellationTokenSource(); _acceptTransportTask = Task.Run(AcceptTransportsAsync); return(Task.CompletedTask); }
private static void Main(string[] args) { var configuration = new CertificateBindingConfiguration(); string command = args.Length > 0 ? args[0].ToLowerInvariant() : string.Empty; switch (command) { case "show": Show(args, configuration); break; case "bind": Bind(args, configuration); break; case "delete": Delete(args, configuration); break; default: Console.WriteLine("Use \r\n'show [<IP:port>]' command to show all SSL Certificate bindings, \r\n'delete <IP:port>' to remove a binding and \r\n'bind <certificateThumbprint> <certificateStoreName> <IP:port> <appId>' to add or update a binding."); break; } }
public void QueryOne() { var ipPort = GetEndpointWithFreeRandomPort(); var appId = Guid.NewGuid(); CertConfigCmd.Add(new CertConfigCmd.Options { ipport = ipPort, certhash = _testingCertThumbprint, appid = appId, certstorename = null, }); var config = new CertificateBindingConfiguration(); var bindingsByIpPort = config.Query(ipPort); Assert.AreEqual(1, bindingsByIpPort.Length); var binding = bindingsByIpPort[0]; Assert.AreEqual(appId, binding.AppId); Assert.AreEqual(ipPort, binding.IpPort); Assert.AreEqual("MY", binding.StoreName); Assert.AreEqual(_testingCertThumbprint, binding.Thumbprint); Assert.AreEqual(false, binding.Options.DoNotPassRequestsToRawFilters); Assert.AreEqual(false, binding.Options.DoNotVerifyCertificateRevocation); Assert.AreEqual(false, binding.Options.EnableRevocationFreshnessTime); Assert.AreEqual(false, binding.Options.NegotiateCertificate); Assert.AreEqual(false, binding.Options.NoUsageCheck); Assert.AreEqual(TimeSpan.Zero, binding.Options.RevocationFreshnessTime); Assert.AreEqual(TimeSpan.Zero, binding.Options.RevocationUrlRetrievalTimeout); Assert.AreEqual(null, binding.Options.SslCtlIdentifier); Assert.AreEqual(null, binding.Options.SslCtlStoreName); Assert.AreEqual(false, binding.Options.UseDsMappers); Assert.AreEqual(false, binding.Options.VerifyRevocationWithCachedCertificateOnly); }
public void AddWithDefaultOptions() { var ipPort = GetEndpointWithFreeRandomPort(); var appId = Guid.NewGuid(); var configuration = new CertificateBindingConfiguration(); var updated = configuration.Bind(new CertificateBinding(_testingCertThumbprint, StoreName.My, ipPort, appId)); Assert.IsFalse(updated); var result = CertConfigCmd.Show(ipPort); Assert.IsTrue(result.IsSuccessfull); var expectedOutput = string.Format( @" IP:port : {0} Certificate Hash : {1} Application ID : {2} Certificate Store Name : My Verify Client Certificate Revocation : Enabled Verify Revocation Using Cached Client Certificate Only : Disabled Usage Check : Enabled Revocation Freshness Time : 0 URL Retrieval Timeout : 0 Ctl Identifier : (null) Ctl Store Name : (null) DS Mapper Usage : Disabled Negotiate Client Certificate : Disabled " , ipPort, _testingCertThumbprint, appId.ToString("B")); Assert.IsTrue(result.Output.ToLowerInvariant().Contains(expectedOutput.ToLowerInvariant())); }
public static void NetshAddSslCert(string certificateHash, ushort port) { NetshDeleteSslCert(port); var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var cert = store .Certificates .Cast <X509Certificate2>() .FirstOrDefault(x => x.GetCertHashString().Equals(certificateHash)); if (cert == null) { throw new Exception(string.Format("Cannot found certificate [{0}]", certificateHash)); } var appid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value; var certificateBindingConfiguration = new CertificateBindingConfiguration(); certificateBindingConfiguration.Bind( new CertificateBinding( certificateHash, StoreName.My, new IPEndPoint(new IPAddress(new byte[] { 0, 0, 0, 0 }), port), Guid.Parse(appid)) ); }
public void DeleteMany() { var ipPort1 = GetEndpointWithFreeRandomPort(); Thread.Sleep(500); var appId1 = Guid.NewGuid(); CertConfigCmd.Add(new CertConfigCmd.Options { ipport = ipPort1, certhash = _testingCertThumbprint, appid = appId1, }); var ipPort2 = GetEndpointWithFreeRandomPort(); var appId2 = Guid.NewGuid(); CertConfigCmd.Add(new CertConfigCmd.Options { ipport = ipPort2, certhash = _testingCertThumbprint, appid = appId2, }); var config = new CertificateBindingConfiguration(); config.Delete(new[] { ipPort1, ipPort2 }); Assert.IsFalse(CertConfigCmd.IpPortIsPresentInConfig(ipPort1)); Assert.IsFalse(CertConfigCmd.IpPortIsPresentInConfig(ipPort2)); }
private static void Bind(string[] args, CertificateBindingConfiguration configuration) { var endPoint = ParseIpEndPoint(args[3]); var updated = configuration.Bind(new CertificateBinding(args[1], args[2], endPoint, Guid.Parse(args[4]))); Console.WriteLine(updated ? "The binding record has been successfully updated." : "The binding record has been successfully added."); }
private static void Delete(string[] args, CertificateBindingConfiguration configuration) { var endPoint = ParseIpEndPoint(args[1]); configuration.Delete(endPoint); Console.WriteLine("The binding record has been successfully removed."); }
// 测试命令行 // netsh http show sslcert ipport=0.0.0.0:53963 // netsh http add sslcert ipport=0.0.0.0:53963 appid={51D241DB-BFFB-4674-8E9E-D6428CF6539D} certhash=A553937A733BDD9B3A4663C6497484D0C17ECDF4 // netsh http show sslcert ipport=0.0.0.0:53963 // netsh http delete sslcert ipport = 0.0.0.0:53963 /// <summary> /// 判断指定的端口是否存在HTTPS的绑定。 /// 注意:在WindowsXP中,如果是非管理员,没有查询SSL相关的权限 /// </summary> /// <param name="httpsPort"></param> /// <returns></returns> public static bool BindIsExist(int httpsPort) { var configuration = new CertificateBindingConfiguration(); IPEndPoint sslPort = new IPEndPoint(IPAddress.Any, httpsPort); var certificateBindings = configuration.Query(sslPort); return(certificateBindings.Length > 0); }
private List <CertificateBinding> GetCertificateBindings() { CertificateBindingConfiguration config = new CertificateBindingConfiguration(); CertificateBinding[] results = config.Query(); return(results.ToList()); }
/// <summary> /// 删除指定端口的HTTPS绑定 /// </summary> /// <param name="httpsPort"></param> public static void RemoveBind(int httpsPort) { UserHelper.CheckIsAdministrator(); var configuration = new CertificateBindingConfiguration(); IPEndPoint sslPort = new IPEndPoint(IPAddress.Any, httpsPort); configuration.Delete(sslPort); }
private static void ShowUrlAcl(string[] args, CertificateBindingConfiguration configuration) { var format = "{0,-40} {1,-39}"; Console.WriteLine(format, "Prefix", "SDDL"); Console.WriteLine("{0} {1}", new string('-', 40), new string('-', 39)); foreach (var urlAcl in UrlAcl.GetAllBindings()) { Console.WriteLine(format, urlAcl.Prefix, urlAcl.Sddl); } }
private CertificateBinding GetCertificateBinding(CertificateBindingConfiguration config) { foreach (CertificateBinding binding in config.Query()) { if (binding.AppId == HttpSysHostingOptions.AppId) { return(binding); } } return(null); }
public void Update() { var ipPort = GetEndpointWithFreeRandomPort(); var appId = Guid.NewGuid(); CertConfigCmd.Add(new CertConfigCmd.Options { ipport = ipPort, certhash = _testingCertThumbprint, appid = appId, certstorename = StoreName.AuthRoot.ToString(), }); var configuration = new CertificateBindingConfiguration(); var binding = new CertificateBinding(_testingCertThumbprint, StoreName.My, ipPort, appId, new BindingOptions { DoNotPassRequestsToRawFilters = true, DoNotVerifyCertificateRevocation = true, EnableRevocationFreshnessTime = true, NegotiateCertificate = true, NoUsageCheck = true, RevocationFreshnessTime = TimeSpan.FromMinutes(1), RevocationUrlRetrievalTimeout = TimeSpan.FromSeconds(5), UseDsMappers = true, VerifyRevocationWithCachedCertificateOnly = true, }); var updated = configuration.Bind(binding); Assert.IsTrue(updated); var result = CertConfigCmd.Show(ipPort); Assert.IsTrue(result.IsSuccessfull); var expectedOutput = string.Format( @" IP:port : {0} Certificate Hash : {1} Application ID : {2} Certificate Store Name : My Verify Client Certificate Revocation : Disabled Verify Revocation Using Cached Client Certificate Only : Enabled Usage Check : Disabled Revocation Freshness Time : 60 URL Retrieval Timeout : 5000 Ctl Identifier : (null) Ctl Store Name : (null) DS Mapper Usage : Enabled Negotiate Client Certificate : Enabled " , ipPort, _testingCertThumbprint, appId.ToString("B")); Assert.IsTrue(result.Output.ToLowerInvariant().Contains(expectedOutput.ToLowerInvariant())); }
/// <summary> /// 将指定的SSL证书绑定到指定的端口,并与应用程序关联 /// </summary> /// <param name="httpsPort"></param> /// <param name="sslCert"></param> /// <param name="appId"></param> public static void BindCertToIP(int httpsPort, X509Certificate2 sslCert, Guid appId) { if (sslCert == null) { throw new ArgumentNullException(nameof(sslCert)); } // netsh http add sslcert ipport=0.0.0.0:53963 appid={A24092A5-F73D-4033-9F40-1BF9004A41A1} certhash=DF51794312354DE531D8B2E6414864F433A2769B // netsh http add sslcert hostnameport=www.fish-test.com:53963 appid={A24092A5-F73D-4033-9F40-1BF9004A41A1} certhash=DC4C95714651C086D325FF481F4E217A5C431A74 certstorename=MY var configuration = new CertificateBindingConfiguration(); IPEndPoint sslPort = new IPEndPoint(IPAddress.Any, httpsPort); CertificateBinding binding = new CertificateBinding(sslCert.Thumbprint, StoreName.My, sslPort, appId); configuration.Bind(binding); }
public void DeleteOne() { var ipPort = GetEndpointWithFreeRandomPort(); var appId = Guid.NewGuid(); CertConfigCmd.Add(new CertConfigCmd.Options { ipport = ipPort, certhash = _testingCertThumbprint, appid = appId, certstorename = null, }); var config = new CertificateBindingConfiguration(); config.Delete(ipPort); Assert.IsFalse(CertConfigCmd.IpPortIsPresentInConfig(ipPort)); }
public void UpdateCertificateBinding(string thumbprint, int httpsPort, List <Action> rollbackActions) { CertificateBindingConfiguration bindingConfiguration = new CertificateBindingConfiguration(); CertificateBinding originalBinding = this.GetCertificateBinding(bindingConfiguration); if (originalBinding != null) { bindingConfiguration.Delete(originalBinding.IpPort); rollbackActions.Add(() => bindingConfiguration.Bind(originalBinding)); } CertificateBinding binding = new CertificateBinding(thumbprint, "My", new IPEndPoint(IPAddress.Parse("0.0.0.0"), httpsPort), HttpSysHostingOptions.AppId, new BindingOptions()); bindingConfiguration.Bind(binding); rollbackActions.Add(() => bindingConfiguration.Delete(binding.IpPort)); this.registryProvider.CertBinding = binding.IpPort.ToString(); rollbackActions.Add(() => this.registryProvider.CertBinding = originalBinding?.IpPort?.ToString()); }
private static void Show(string[] args, CertificateBindingConfiguration configuration) { Console.WriteLine("SSL Certificate bindings:\r\n-------------------------\r\n"); var stores = new Dictionary <string, X509Store>(); var ipEndPoint = args.Length > 1 ? ParseIpEndPoint(args[1]) : null; var certificateBindings = configuration.Query(ipEndPoint); foreach (var info in certificateBindings) { X509Store store; if (!stores.TryGetValue(info.StoreName, out store)) { store = new X509Store(info.StoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); stores.Add(info.StoreName, store); } var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, info.Thumbprint, false)[0]; string certStr = String.Format( @" IP:port : {2} Thumbprint : {0} Subject : {4} Issuer : {5} Application ID : {3} Store Name : {1} Verify Client Certificate Revocation : {6} Verify Revocation Using Cached Client Certificate Only : {7} Usage Check : {8} Revocation Freshness Time : {9} URL Retrieval Timeout : {10} Ctl Identifier : {11} Ctl Store Name : {12} DS Mapper Usage : {13} Negotiate Client Certificate: {14} ", info.Thumbprint, info.StoreName, info.IpPort, info.AppId, certificate.Subject, certificate.Issuer, !info.Options.DoNotVerifyCertificateRevocation, info.Options.VerifyRevocationWithCachedCertificateOnly, !info.Options.NoUsageCheck, info.Options.RevocationFreshnessTime + (info.Options.EnableRevocationFreshnessTime ? string.Empty : " (disabled)"), info.Options.RevocationUrlRetrievalTimeout, info.Options.SslCtlIdentifier, info.Options.SslCtlStoreName, info.Options.UseDsMappers, info.Options.NegotiateCertificate); Console.WriteLine(certStr); } }
private static void Main(string[] args) { var configuration = new CertificateBindingConfiguration(); string command = args.Length > 0 ? args[0].ToLowerInvariant() : string.Empty; switch (command){ case "show": Show(args, configuration); break; case "bind": Bind(args, configuration); break; case "delete": Delete(args, configuration); break; default: Console.WriteLine("Use \r\n'show [<IP:port>]' command to show all SSL Certificate bindings, \r\n'delete <IP:port>' to remove a binding and \r\n'bind <certificateThumbprint> <certificateStoreName> <IP:port> <appId>' to add or update a binding."); break; } }
private static void Show(string[] args, CertificateBindingConfiguration configuration) { Console.WriteLine("SSL Certificate bindings:\r\n-------------------------\r\n"); var stores = new Dictionary<string, X509Store>(); var ipEndPoint = args.Length > 1 ? ParseIpEndPoint(args[1]) : null; var certificateBindings = configuration.Query(ipEndPoint); foreach (var info in certificateBindings){ X509Store store; if (!stores.TryGetValue(info.StoreName, out store)){ store = new X509Store(info.StoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); stores.Add(info.StoreName, store); } var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, info.Thumbprint, false)[0]; string certStr = String.Format( @" IP:port : {2} Thumbprint : {0} Subject : {4} Issuer : {5} Application ID : {3} Store Name : {1} Verify Client Certificate Revocation : {6} Verify Revocation Using Cached Client Certificate Only : {7} Usage Check : {8} Revocation Freshness Time : {9} URL Retrieval Timeout : {10} Ctl Identifier : {11} Ctl Store Name : {12} DS Mapper Usage : {13} Negotiate Client Certificate: {14} ", info.Thumbprint, info.StoreName, info.IpPort, info.AppId, certificate.Subject, certificate.Issuer, !info.Options.DoNotVerifyCertificateRevocation, info.Options.VerifyRevocationWithCachedCertificateOnly, !info.Options.NoUsageCheck, info.Options.RevocationFreshnessTime + (info.Options.EnableRevocationFreshnessTime ? string.Empty : " (disabled)"), info.Options.RevocationUrlRetrievalTimeout, info.Options.SslCtlIdentifier, info.Options.SslCtlStoreName, info.Options.UseDsMappers, info.Options.NegotiateCertificate); Console.WriteLine(certStr); } }
private static void Bind(string[] args, CertificateBindingConfiguration configuration){ var endPoint = ParseIpEndPoint(args[3]); var updated = configuration.Bind(new CertificateBinding(args[1], args[2], endPoint, Guid.Parse(args[4]))); Console.WriteLine(updated ? "The binding record has been successfully updated." : "The binding record has been successfully added."); }
public void QueryAll() { var ipPort1 = GetEndpointWithFreeRandomPort(); var appId1 = Guid.NewGuid(); CertConfigCmd.Add(new CertConfigCmd.Options { ipport = ipPort1, certhash = _testingCertThumbprint, appid = appId1, certstorename = StoreName.My.ToString(), }); var ipPort2 = GetEndpointWithFreeRandomPort(); var appId2 = Guid.NewGuid(); CertConfigCmd.Add(new CertConfigCmd.Options { ipport = ipPort2, certhash = _testingCertThumbprint, appid = appId2, certstorename = StoreName.AuthRoot.ToString(), clientcertnegotiation = true, revocationfreshnesstime = 100, usagecheck = false, verifyrevocationwithcachedclientcertonly = true, }); var config = new CertificateBindingConfiguration(); var allBindings = config.Query(); var addedBindings = allBindings.Where(b => b.IpPort.Equals(ipPort1) || b.IpPort.Equals(ipPort2)).ToArray(); Assert.AreEqual(2, addedBindings.Length); var binding1 = addedBindings[0]; Assert.AreEqual(appId1, binding1.AppId); Assert.AreEqual(ipPort1, binding1.IpPort); Assert.AreEqual(StoreName.My.ToString(), binding1.StoreName); Assert.AreEqual(_testingCertThumbprint, binding1.Thumbprint); Assert.AreEqual(false, binding1.Options.DoNotPassRequestsToRawFilters); Assert.AreEqual(false, binding1.Options.DoNotVerifyCertificateRevocation); Assert.AreEqual(false, binding1.Options.EnableRevocationFreshnessTime); Assert.AreEqual(false, binding1.Options.NegotiateCertificate); Assert.AreEqual(false, binding1.Options.NoUsageCheck); Assert.AreEqual(TimeSpan.Zero, binding1.Options.RevocationFreshnessTime); Assert.AreEqual(TimeSpan.Zero, binding1.Options.RevocationUrlRetrievalTimeout); Assert.AreEqual(null, binding1.Options.SslCtlIdentifier); Assert.AreEqual(null, binding1.Options.SslCtlStoreName); Assert.AreEqual(false, binding1.Options.UseDsMappers); Assert.AreEqual(false, binding1.Options.VerifyRevocationWithCachedCertificateOnly); var binding2 = addedBindings[1]; Assert.AreEqual(appId2, binding2.AppId); Assert.AreEqual(ipPort2, binding2.IpPort); Assert.AreEqual(StoreName.AuthRoot.ToString(), binding2.StoreName); Assert.AreEqual(_testingCertThumbprint, binding2.Thumbprint); Assert.AreEqual(false, binding2.Options.DoNotPassRequestsToRawFilters); Assert.AreEqual(false, binding2.Options.DoNotVerifyCertificateRevocation); Assert.AreEqual(true, binding2.Options.EnableRevocationFreshnessTime); Assert.AreEqual(true, binding2.Options.NegotiateCertificate); Assert.AreEqual(true, binding2.Options.NoUsageCheck); Assert.AreEqual(TimeSpan.FromSeconds(100), binding2.Options.RevocationFreshnessTime); Assert.AreEqual(TimeSpan.Zero, binding2.Options.RevocationUrlRetrievalTimeout); Assert.AreEqual(null, binding2.Options.SslCtlIdentifier); Assert.AreEqual(null, binding2.Options.SslCtlStoreName); Assert.AreEqual(false, binding2.Options.UseDsMappers); Assert.AreEqual(true, binding2.Options.VerifyRevocationWithCachedCertificateOnly); }
private static void Delete(string[] args, CertificateBindingConfiguration configuration){ var endPoint = ParseIpEndPoint(args[1]); configuration.Delete(endPoint); Console.WriteLine("The binding record has been successfully removed."); }