public void SetupSSLCertificateWithPassword() { string originalPath = Environment.CurrentDirectory; Environment.CurrentDirectory = Environment.CurrentDirectory + "\\..\\..\\..\\SSL examples\\WithPassword"; string sslPath = Environment.CurrentDirectory; Environment.CurrentDirectory = originalPath; SSLCertificate sslCertificate = _application.Settings.SSLCertificates.Add(); sslCertificate.Name = "Example"; sslCertificate.CertificateFile = sslPath + "\\server.crt"; sslCertificate.PrivateKeyFile = sslPath + "\\server.key"; sslCertificate.Save(); TCPIPPort port = _application.Settings.TCPIPPorts.Add(); port.Address = "0.0.0.0"; port.PortNumber = 251; port.UseSSL = true; port.SSLCertificateID = sslCertificate.ID; port.Protocol = eSessionType.eSTSMTP; port.Save(); _application.Stop(); _application.Start(); TestSetup.AssertReportedError(); SingletonProvider <TestSetup> .Instance.DoBasicSetup(); }
protected void InstallPfxFromClient(int webSiteId) { if (upPFX.HasFile.Equals(false)) { messageBox.ShowErrorMessage("WEB_SSL_NOFILE"); return; } byte[] pfx = upPFX.FileBytes; string certPassword = txtPFXInstallPassword.Text; ResultObject result = ES.Services.WebServers.InstallPfx(pfx, webSiteId, txtPFXInstallPassword.Text); // SSLCertificate certificate = ES.Services.WebServers.GetSiteCert(webSiteId); // Check the operation status if (result.IsSuccess.Equals(false)) { messageBox.ShowErrorMessage("WEB_INSTALL_CSR"); RefreshControlLayout(); return; } // messageBox.ShowSuccessMessage("WEB_INSTALL_CSR"); SSLNotInstalled.Visible = false; tabInstalled.Visible = true; RefreshControlLayout(); }
protected void RenewCertificate(SSLCertificate cert) { TabContainer1.ActiveTab = TabContainer1.Tabs[1]; SSLNotInstalled.Visible = false; pnlCSR.Visible = true; tabCSR.HeaderText = GetLocalizedString("SSLGenereateRenewal.HeaderText"); string hostname = cert.Hostname; // Check if it is a wildcard certificate if (!String.IsNullOrEmpty(cert.Hostname) && cert.Hostname.StartsWith("*")) { chkWild.Checked = true; hostname = hostname.Remove(0, 2); } // Assign hostname SetCertHostnameSelection(hostname); // Assign state SetCertCountrySelection(cert.Country); // Assign country SetCertStateSelection(cert.State); // Assign certificate strength MakeSafeListSelection(lstBits, cert.CSRLength.ToString()); // txtCompany.Text = cert.Organisation; txtOU.Text = lblInstalledOU.Text; txtCity.Text = cert.City; // Render button controls appropriately btnCSR.Visible = false; btnRenCSR.Visible = true; }
public static void SetupSSLPorts(hMailServer.Application application) { SSLCertificate sslCeritifcate = SetupSSLCertificate(application); var ports = application.Settings.TCPIPPorts; AddPort(ports, 25000, eConnectionSecurity.eCSNone, sslCeritifcate.ID, eSessionType.eSTSMTP); AddPort(ports, 11000, eConnectionSecurity.eCSNone, sslCeritifcate.ID, eSessionType.eSTPOP3); AddPort(ports, 14300, eConnectionSecurity.eCSNone, sslCeritifcate.ID, eSessionType.eSTIMAP); AddPort(ports, 25001, eConnectionSecurity.eCSTLS, sslCeritifcate.ID, eSessionType.eSTSMTP); AddPort(ports, 11001, eConnectionSecurity.eCSTLS, sslCeritifcate.ID, eSessionType.eSTPOP3); AddPort(ports, 14301, eConnectionSecurity.eCSTLS, sslCeritifcate.ID, eSessionType.eSTIMAP); AddPort(ports, 25002, eConnectionSecurity.eCSSTARTTLSOptional, sslCeritifcate.ID, eSessionType.eSTSMTP); AddPort(ports, 11002, eConnectionSecurity.eCSSTARTTLSOptional, sslCeritifcate.ID, eSessionType.eSTPOP3); AddPort(ports, 14302, eConnectionSecurity.eCSSTARTTLSOptional, sslCeritifcate.ID, eSessionType.eSTIMAP); AddPort(ports, 25003, eConnectionSecurity.eCSSTARTTLSRequired, sslCeritifcate.ID, eSessionType.eSTSMTP); AddPort(ports, 11003, eConnectionSecurity.eCSSTARTTLSRequired, sslCeritifcate.ID, eSessionType.eSTPOP3); AddPort(ports, 14303, eConnectionSecurity.eCSSTARTTLSRequired, sslCeritifcate.ID, eSessionType.eSTIMAP); application.Stop(); application.Start(); }
protected void InstallCertificate(int webSiteId, string certText) { SSLCertificate certificate = ES.Services.WebServers.GetSSLCertificateByID((int)ViewState["CSRID"]); certificate.Certificate = certText; ResultObject result = ES.Services.WebServers.InstallCertificate(certificate, webSiteId); // Check the operation status if (!result.IsSuccess) { messageBox.ShowErrorMessage("WEB_INSTALL_CSR"); return; } // messageBox.ShowSuccessMessage("WEB_INSTALL_CSR"); tabInstalled.Visible = true; tabInstalled.Enabled = true; tabInstalled.HeaderText = "Installed Certificate"; tabCSR.HeaderText = "New Certificate"; pnlInstallCertificate.Visible = false; SSLNotInstalled.Visible = true; // TabContainer1.ActiveTab = tabInstalled; RefreshControlLayout(); }
protected void RenewCertificate(SSLCertificate cert) { TabContainer1.ActiveTab = TabContainer1.Tabs[1]; SSLNotInstalled.Visible = false; pnlCSR.Visible = true; tabCSR.HeaderText = GetLocalizedString("SSLGenereateRenewal.HeaderText"); string hostname = cert.Hostname; // Assign hostname SetCertHostnameSelection(hostname); // Assign state SetCertCountrySelection(cert.Country); // Assign country SetCertStateSelection(cert.State); // Assign certificate strength MakeSafeListSelection(lstBits, cert.CSRLength.ToString()); // txtCompany.Text = cert.Organisation; txtOU.Text = lblInstalledOU.Text; txtCity.Text = cert.City; // Render button controls appropriately btnCSR.Visible = false; btnRenCSR.Visible = true; }
public void SetupSSLCertificateWithPassword() { string sslPath = Path.Combine(SslSetup.GetSslCertPath(), "WithPassword"); SSLCertificate sslCertificate = _application.Settings.SSLCertificates.Add(); sslCertificate.Name = "Example"; sslCertificate.CertificateFile = sslPath + "\\server.crt"; sslCertificate.PrivateKeyFile = sslPath + "\\server.key"; sslCertificate.Save(); TCPIPPort port = _application.Settings.TCPIPPorts.Add(); port.Address = "0.0.0.0"; port.PortNumber = 251; port.UseSSL = true; port.SSLCertificateID = sslCertificate.ID; port.Protocol = eSessionType.eSTSMTP; port.Save(); _application.Stop(); _application.Start(); CustomAsserts.AssertReportedError("The private key file has a password. hMailServer does not support this.", "Failed to load private key file."); SingletonProvider <TestSetup> .Instance.PerformBasicSetup(); }
public void AddBinding(SSLCertificate certificate, WebSite website) { using (ServerManager srvman = GetServerManager()) { // Not sure why do we need to work with X.509 store here, so commented it out and lets see what happens X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); // List <ServerBinding> bindings = new List <ServerBinding>(); // Retrieve existing site bindings to figure out what do we have here WebObjectsModuleService webObjSvc = new WebObjectsModuleService(); bindings.AddRange(webObjSvc.GetSiteBindings(srvman, website.SiteId)); // Look for dedicated ip bool dedicatedIp = bindings.Exists(binding => String.IsNullOrEmpty(binding.Host) && binding.IP != "*"); // string bindingInformation; // bindingInformation = dedicatedIp ? string.Format("{0}:443:", website.SiteIPAddress) : string.Format("{0}:443:{1}", website.SiteIPAddress, certificate.Hostname); // srvman.Sites[website.SiteId].Bindings.Add(bindingInformation, certificate.Hash, store.Name); // store.Close(); // srvman.CommitChanges(); } }
public ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website) { ResultObject result = new ResultObject(); try { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySerialNumber, certificate.SerialNumber, false)[0]; store.Remove(cert); store.Close(); RemoveBinding(certificate, website); result.IsSuccess = true; } catch (Exception ex) { result.IsSuccess = false; result.AddError("", ex); } return(result); }
public static void SetupSSLPorts(hMailServer.Application application, SslVersions sslVersions = null) { SSLCertificate sslCeritifcate = SetupSSLCertificate(application); var settings = application.Settings; var ports = settings.TCPIPPorts; ports.SetDefault(); AddPort(ports, 25000, eConnectionSecurity.eCSNone, sslCeritifcate.ID, eSessionType.eSTSMTP); AddPort(ports, 11000, eConnectionSecurity.eCSNone, sslCeritifcate.ID, eSessionType.eSTPOP3); AddPort(ports, 14300, eConnectionSecurity.eCSNone, sslCeritifcate.ID, eSessionType.eSTIMAP); AddPort(ports, 25001, eConnectionSecurity.eCSTLS, sslCeritifcate.ID, eSessionType.eSTSMTP); AddPort(ports, 11001, eConnectionSecurity.eCSTLS, sslCeritifcate.ID, eSessionType.eSTPOP3); AddPort(ports, 14301, eConnectionSecurity.eCSTLS, sslCeritifcate.ID, eSessionType.eSTIMAP); AddPort(ports, 25002, eConnectionSecurity.eCSSTARTTLSOptional, sslCeritifcate.ID, eSessionType.eSTSMTP); AddPort(ports, 11002, eConnectionSecurity.eCSSTARTTLSOptional, sslCeritifcate.ID, eSessionType.eSTPOP3); AddPort(ports, 14302, eConnectionSecurity.eCSSTARTTLSOptional, sslCeritifcate.ID, eSessionType.eSTIMAP); AddPort(ports, 25003, eConnectionSecurity.eCSSTARTTLSRequired, sslCeritifcate.ID, eSessionType.eSTSMTP); AddPort(ports, 11003, eConnectionSecurity.eCSSTARTTLSRequired, sslCeritifcate.ID, eSessionType.eSTPOP3); AddPort(ports, 14303, eConnectionSecurity.eCSSTARTTLSRequired, sslCeritifcate.ID, eSessionType.eSTIMAP); settings.TlsVersion10Enabled = sslVersions == null || sslVersions.Tls10; settings.TlsVersion11Enabled = sslVersions == null || sslVersions.Tls11; settings.TlsVersion12Enabled = sslVersions == null || sslVersions.Tls12; settings.TlsVersion13Enabled = sslVersions == null || sslVersions.Tls13; application.Stop(); application.Start(); }
private static SSLCertificate SetupSSLCertificate(hMailServer.Application application) { var sslPath = GetSslCertPath(); var exampleCert = Path.Combine(sslPath, "example.crt"); var exampleKey = Path.Combine(sslPath, "example.key"); if (!File.Exists(exampleCert)) { Assert.Fail("Certificate " + exampleCert + " was not found"); } if (!File.Exists(exampleKey)) { Assert.Fail("Private key " + exampleKey + " was not found"); } SSLCertificate sslCertificate = application.Settings.SSLCertificates.Add(); sslCertificate.Name = "Example"; sslCertificate.CertificateFile = exampleCert; sslCertificate.PrivateKeyFile = exampleKey; sslCertificate.Save(); return(sslCertificate); }
protected void btnRenCSR_Click(object sender, EventArgs e) { // string domain = lstDomains.SelectedValue; // if (chkWild.Checked) { domain = "*." + domain; } // string distinguishedName = string.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", domain, txtCompany.Text, txtOU.Text, txtCity.Text, State, lstCountries.SelectedValue); SSLCertificate certificate = new SSLCertificate(); certificate.Hostname = domain; certificate.DistinguishedName = distinguishedName; certificate.CSRLength = Convert.ToInt32(lstBits.SelectedValue); certificate.Organisation = txtCompany.Text; certificate.OrganisationUnit = txtOU.Text; certificate.SiteID = PanelRequest.ItemID; certificate.State = State; certificate.City = txtCity.Text; certificate.Country = lstCountries.SelectedValue; certificate.PreviousId = InstalledCert.id; certificate.IsRenewal = true; certificate = ES.Services.WebServers.CertificateRequest(certificate, certificate.SiteID); // Something is wrong if (certificate.CSR == "") { messageBox.ShowErrorMessage(WEB_GEN_CSR); return; } // pnlShowUpload.Visible = false; pnlCSR.Visible = false; ViewState["CSRID"] = certificate.id; txtCSR.Attributes.Add("onfocus", "this.select();"); RefreshControlLayout(PanelRequest.ItemID); TabContainer1.ActiveTab = TabContainer1.Tabs[0]; messageBox.ShowSuccessMessage(WEB_GEN_CSR); }
private void ConfirmSSLCertificates() { SSLCertificate cert = _application.Settings.SSLCertificates[0]; Assert.AreEqual("file1.txt", cert.CertificateFile); Assert.AreEqual("name1", cert.Name); Assert.AreEqual("pk1", cert.PrivateKeyFile); cert = _application.Settings.SSLCertificates[1]; Assert.AreEqual("file2.txt", cert.CertificateFile); Assert.AreEqual("name2", cert.Name); Assert.AreEqual("pk2", cert.PrivateKeyFile); }
protected void btnCSR_Click(object sender, EventArgs e) { string domain = lstDomains.SelectedValue; // Ensure wildcard certificate request is correct if (chkWild.Checked) { domain = "*." + domain; } // string distinguishedName = string.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", domain, txtCompany.Text, txtOU.Text, txtCity.Text, State, lstCountries.SelectedValue); SSLCertificate certificate = new SSLCertificate(); certificate.Hostname = domain; certificate.DistinguishedName = distinguishedName; certificate.CSRLength = Convert.ToInt32(lstBits.SelectedValue); certificate.Organisation = txtCompany.Text; certificate.OrganisationUnit = txtOU.Text; certificate.SiteID = PanelRequest.ItemID; certificate.State = State; certificate.City = txtCity.Text; certificate.Country = lstCountries.SelectedValue; certificate.IsRenewal = false; certificate = ES.Services.WebServers.CertificateRequest(certificate, certificate.SiteID); // Something is wrong if (certificate.CSR == "") { messageBox.ShowErrorMessage(ERROR_CSR); return; } // We are done SSLNotInstalled.Visible = false; pnlCSR.Visible = false; tabCSR.HeaderText = GetLocalizedString("tabPendingCertificate.HeaderText"); ViewState["CSRID"] = certificate.id; pnlInstallCertificate.Visible = true; txtCSR.Text = certificate.CSR; txtCSR.Attributes.Add("onfocus", "this.select();"); }
public SSLCertificate ImportCertificate(WebSite website) { SSLCertificate certificate = new SSLCertificate { Success = false }; try { using (ServerManager sm = GetServerManager()) { Site site = sm.Sites[website.SiteId]; Binding sslbind = (from b in site.Bindings where b.Protocol == "https" select b).Single(); certificate.Hash = sslbind.CertificateHash; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); X509Certificate2 x509Cert = (from X509Certificate2 c in store.Certificates where Convert.ToBase64String(c.GetCertHash()) == Convert.ToBase64String(certificate.Hash) select c).Single(); store.Close(); certificate.Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false); certificate.FriendlyName = x509Cert.FriendlyName; certificate.CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString()); certificate.Installed = true; certificate.DistinguishedName = x509Cert.Subject; certificate.Hash = x509Cert.GetCertHash(); certificate.SerialNumber = x509Cert.SerialNumber; certificate.ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString()); certificate.ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString()); certificate.Success = true; } } catch (Exception ex) { certificate.Success = false; certificate.Certificate = ex.ToString(); } return(certificate); }
public SSLCertificate installCertificate(SSLCertificate certificate, WebSite website) { try { Log.WriteStart("'{0}' installCertificate", ProviderSettings.ProviderName); SSLCertificate result = WebProvider.installCertificate(certificate, website); Log.WriteEnd("'{0}' installCertificate", ProviderSettings.ProviderName); return(result); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' generateCSR", ProviderSettings.ProviderName), ex); throw; } }
public SSLCertificate generateRenewalCSR(SSLCertificate certificate) { try { Log.WriteStart("'{0}' generateCSR", ProviderSettings.ProviderName); certificate = WebProvider.generateCSR(certificate); Log.WriteEnd("'{0}' generateCSR", ProviderSettings.ProviderName); return(certificate); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' generateCSR", ProviderSettings.ProviderName), ex); throw; } }
public void RemoveBinding(SSLCertificate certificate, WebSite website) { using (ServerManager sm = GetServerManager()) { Site site = sm.Sites[website.SiteId]; Binding sslbind = (from b in site.Bindings where b.Protocol == "https" select b).Single(); site.Bindings.Remove(sslbind); sm.CommitChanges(); } }
private void SetupSSLCertificates() { SSLCertificate cert = _application.Settings.SSLCertificates.Add(); cert.CertificateFile = "file1.txt"; cert.Name = "name1"; cert.PrivateKeyFile = "pk1"; cert.Save(); cert = _application.Settings.SSLCertificates.Add(); cert.CertificateFile = "file2.txt"; cert.Name = "name2"; cert.PrivateKeyFile = "pk2"; cert.Save(); }
public void TestSSLCertificate() { Settings oSettings = SingletonProvider <TestSetup> .Instance.GetApp().Settings; SSLCertificate sslcert = oSettings.SSLCertificates.Add(); sslcert.CertificateFile = "somefile.dat"; sslcert.PrivateKeyFile = "someprivatefile.dat"; sslcert.Save(); if (sslcert.ID == 0) { throw new Exception("SSL certificate not saved properly"); } oSettings.SSLCertificates.DeleteByDBID(sslcert.ID); }
private static SSLCertificate GetSSLCertificateFromX509Certificate2(X509Certificate2 cert) { var certificate = new SSLCertificate { Hostname = cert.GetNameInfo(X509NameType.SimpleName, false), FriendlyName = cert.FriendlyName, CSRLength = Convert.ToInt32(cert.PublicKey.Key.KeySize.ToString(CultureInfo.InvariantCulture)), Installed = true, DistinguishedName = cert.Subject, Hash = cert.GetCertHash(), SerialNumber = cert.SerialNumber, ExpiryDate = DateTime.Parse(cert.GetExpirationDateString()), ValidFrom = DateTime.Parse(cert.GetEffectiveDateString()), Success = true }; return(certificate); }
protected void DeleteCertificate(int webSiteId, SSLCertificate siteCert) { ResultObject result = ES.Services.WebServers.DeleteCertificate(webSiteId, siteCert); if (!result.IsSuccess) { // Show error message messageBox.ShowErrorMessage(WEB_SSL_DELETE); return; } // Show success message messageBox.ShowSuccessMessage(WEB_SSL_DELETE); // tabInstalled.Visible = false; tabInstalled.Enabled = false; tabInstalled.HeaderText = ""; InstalledCert = null; }
public ucSSLCertificate(int certificateID) { InitializeComponent(); if (certificateID > 0) { hMailServer.Settings settings = APICreator.Settings; hMailServer.SSLCertificates sslCertificates = settings.SSLCertificates; _representedObject = sslCertificates.get_ItemByDBID(certificateID); Marshal.ReleaseComObject(settings); Marshal.ReleaseComObject(sslCertificates); } DirtyChecker.SubscribeToChange(this, OnContentChanged); new TabOrderManager(this).SetTabOrder(TabOrderManager.TabScheme.AcrossFirst); }
public ucSSLCertificate(int certificateID) { InitializeComponent(); if (certificateID > 0) { hMailServer.Settings settings = APICreator.Settings; hMailServer.SSLCertificates sslCertificates = settings.SSLCertificates; _representedObject = sslCertificates.get_ItemByDBID(certificateID); Marshal.ReleaseComObject(settings); Marshal.ReleaseComObject(sslCertificates); } DirtyChecker.SubscribeToChange(this, OnContentChanged); new TabOrderManager(this).SetTabOrder(TabOrderManager.TabScheme.AcrossFirst); }
public bool SaveData() { bool newObject = false; if (_representedObject == null) { hMailServer.Settings settings = APICreator.Application.Settings; hMailServer.SSLCertificates sslCertificates = settings.SSLCertificates; _representedObject = sslCertificates.Add(); Marshal.ReleaseComObject(settings); Marshal.ReleaseComObject(sslCertificates); newObject = true; } _representedObject.Name = textName.Text; _representedObject.CertificateFile = textCertificateFile.Text; _representedObject.PrivateKeyFile = textPrivateKeyFile.Text; _representedObject.Save(); // Refresh the node in the tree if the name has changed. IMainForm mainForm = Instances.MainForm; mainForm.RefreshCurrentNode(textName.Text); // Set the object to clean. DirtyChecker.SetClean(this); if (newObject) { SearchNodeText crit = new SearchNodeText(_representedObject.Name); mainForm.SelectNode(crit); } return(true); }
public new ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website) { // This method removes all https bindings and all certificates associated with them. // Old implementation (IIS70) removed a single binding (there could not be more than one) and the first certificate that matched via serial number var result = new ResultObject { IsSuccess = true }; if (certificate == null) { return(result); } try { //var certificatesAndStoreNames = new List<Tuple<string, byte[]>>(); // User servermanager to get aLL SSL-bindings on this website and try to remove the certificates used using (var srvman = GetServerManager()) { var site = srvman.Sites[website.Name]; var bindings = site.Bindings.Where(b => b.Protocol == "https"); foreach (Binding binding in bindings.ToList()) { // Remove binding from site site.Bindings.Remove(binding); } srvman.CommitChanges(); } } catch (Exception ex) { Log.WriteError(String.Format("Unable to delete certificate for website {0}", website.Name), ex); result.IsSuccess = false; result.AddError("", ex); } return(result); }
public static void PrintValue(string amount, string label) { TerminalIPAddress PedIP = new TerminalIPAddress(); SSLCertificate PedSSL = new SSLCertificate(); Status PedState = new Status(); PedIP.IPAddressIn = "192.168.1.58"; PedIP.SetIPAddress(); PedSSL.PathIn = "E:\\TerminalRoot.pem"; PedSSL.SetPath(); PedState.GetTerminalState(); Transaction PedTRN = new Transaction(); PedTRN.MessageNumberIn = "11"; PedTRN.Amount1In = amount; PedTRN.Amount1LabelIn = label; PedTRN.TransactionTypeIn = "00"; PedTRN.DoTransaction(); }
public new SSLCertificate ImportCertificate(WebSite website) { SSLCertificate certificate; try { certificate = GetCurrentSiteCertificate(website); } catch (Exception ex) { certificate = new SSLCertificate { Success = false, Certificate = ex.ToString() }; } return(certificate ?? (new SSLCertificate { Success = false, Certificate = "No certificate in binding on server, please remove or edit binding" })); }
public SSLCertificate LEInstallCertificate(WebSite website, string email) { Runspace runSpace = null; SSLCertificate cert = null; try { runSpace = OpenRunspace(); Command cmd = new Command("letsencrypt.exe"); cmd.Parameters.Add("-plugin", "iissite"); cmd.Parameters.Add("-siteid", website); cmd.Parameters.Add("-emailaddress", email); cmd.Parameters.Add("-accepttos", "--usedefaulttaskuser"); ExecuteShellCommand(runSpace, cmd); cert.Success = true; } catch (Exception ex) { Log.WriteError("Error adding Lets Encrypt certificate", ex); cert.Success = false; } return(cert); }
public SSLCertificate installPFX(byte[] certificate, string password, WebSite website) { try { Log.WriteStart("'{0}' installPFX", ProviderSettings.ProviderName); SSLCertificate response = WebProvider.installPFX(certificate, password, website); if (response.Hash == null) { Log.WriteError(String.Format("'{0}' installPFX", ProviderSettings.ProviderName), null); } else { Log.WriteEnd("'{0}' installPFX", ProviderSettings.ProviderName); } return(response); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' generateCSR", ProviderSettings.ProviderName), ex); throw; } }
public SSLCertificate InstallCertificate(SSLCertificate cert, WebSite website) { CX509Enrollment response = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment; try { response.Initialize(X509CertificateEnrollmentContext.ContextMachine); response.InstallResponse( InstallResponseRestrictionFlags.AllowUntrustedRoot, cert.Certificate, EncodingType.XCN_CRYPT_STRING_BASE64HEADER, null ); SSLCertificate servercert = (from c in GetServerCertificates() where c.FriendlyName == cert.FriendlyName select c).Single(); cert.SerialNumber = servercert.SerialNumber; cert.ValidFrom = servercert.ValidFrom; cert.ExpiryDate = servercert.ExpiryDate; cert.Hash = servercert.Hash; cert.DistinguishedName = servercert.DistinguishedName; if (cert.IsRenewal && CheckCertificate(website)) { DeleteCertificate(GetCurrentSiteCertificate(website), website); } AddBinding(cert, website); } catch (Exception ex) { Log.WriteError("Error adding SSL certificate", ex); cert.Success = false; } return(cert); }
public void GenerateCsr(SSLCertificate cert) { // Create all the objects that will be required CX509CertificateRequestPkcs10 pkcs10 = new CX509CertificateRequestPkcs10Class(); CX509PrivateKey privateKey = new CX509PrivateKeyClass(); CCspInformation csp = new CCspInformationClass(); CCspInformations csPs = new CCspInformationsClass(); CX500DistinguishedName dn = new CX500DistinguishedNameClass(); CX509Enrollment enroll = new CX509EnrollmentClass(); CObjectIds objectIds = new CObjectIdsClass(); CObjectId clientObjectId = new CObjectIdClass(); CObjectId serverObjectId = new CObjectIdClass(); CX509ExtensionKeyUsage extensionKeyUsage = new CX509ExtensionKeyUsageClass(); CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsageClass(); try { // Initialize the csp object using the desired Cryptograhic Service Provider (CSP) csp.InitializeFromName("Microsoft RSA SChannel Cryptographic Provider"); // Add this CSP object to the CSP collection object csPs.Add(csp); // Provide key container name, key length and key spec to the private key object //objPrivateKey.ContainerName = "AlejaCMa"; privateKey.Length = cert.CSRLength; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.MachineContext = true; // Provide the CSP collection object (in this case containing only 1 CSP object) // to the private key object privateKey.CspInformations = csPs; // Create the actual key pair privateKey.Create(); // Initialize the PKCS#10 certificate request object based on the private key. // Using the context, indicate that this is a user certificate request and don't // provide a template name pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.PrivateKey = privateKey.ToString(); // Key Usage Extension extensionKeyUsage.InitializeEncode( CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE ); pkcs10.X509Extensions.Add((CX509Extension)extensionKeyUsage); // Enhanced Key Usage Extension clientObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.2"); objectIds.Add(clientObjectId); serverObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.1"); objectIds.Add(serverObjectId); x509ExtensionEnhancedKeyUsage.InitializeEncode(objectIds); pkcs10.X509Extensions.Add((CX509Extension)x509ExtensionEnhancedKeyUsage); // Encode the name in using the Distinguished Name object string request = String.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", cert.Hostname, cert.Organisation, cert.OrganisationUnit, cert.City, cert.State, cert.Country); dn.Encode(request, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Assing the subject name by using the Distinguished Name object initialized above pkcs10.Subject = dn; // Create enrollment request enroll.InitializeFromRequest(pkcs10); enroll.CertificateFriendlyName = cert.FriendlyName; cert.CSR = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER); } catch (Exception ex) { Log.WriteError("Error creating CSR", ex); } }
public new SSLCertificate ImportCertificate(WebSite website) { SSLCertificate certificate; try { certificate = GetCurrentSiteCertificate(website); } catch (Exception ex) { certificate = new SSLCertificate { Success = false, Certificate = ex.ToString() }; } return certificate ?? (new SSLCertificate {Success = false, Certificate = "No certificate in binding on server, please remove or edit binding"}); }
public bool SaveData() { bool newObject = false; if (_representedObject == null) { hMailServer.Settings settings = APICreator.Application.Settings; hMailServer.SSLCertificates sslCertificates = settings.SSLCertificates; _representedObject = sslCertificates.Add(); Marshal.ReleaseComObject(settings); Marshal.ReleaseComObject(sslCertificates); newObject = true; } _representedObject.Name = textName.Text; _representedObject.CertificateFile = textCertificateFile.Text; _representedObject.PrivateKeyFile = textPrivateKeyFile.Text; _representedObject.Save(); // Refresh the node in the tree if the name has changed. IMainForm mainForm = Instances.MainForm; mainForm.RefreshCurrentNode(textName.Text); // Set the object to clean. DirtyChecker.SetClean(this); if (newObject) { SearchNodeText crit = new SearchNodeText(_representedObject.Name); mainForm.SelectNode(crit); } return true; }
public new SSLCertificate InstallCertificate(SSLCertificate cert, WebSite website) { try { var response = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment; if (response == null) { throw new Exception("Cannot create instance of X509Enrollment.CX509Enrollment"); } response.Initialize(X509CertificateEnrollmentContext.ContextMachine); response.InstallResponse( InstallResponseRestrictionFlags.AllowUntrustedRoot, cert.Certificate, EncodingType.XCN_CRYPT_STRING_BASE64HEADER, null ); // At this point, certificate has been installed into "Personal" store // We need to move it into "WebHosting" store // Get certificate var servercert = GetServerCertificates(StoreName.My.ToString()).Single(c => c.FriendlyName == cert.FriendlyName); // Get certificate data - the one we just added to "Personal" store var storeMy = new X509Store(StoreName.My, StoreLocation.LocalMachine); storeMy.Open(OpenFlags.MaxAllowed); X509CertificateCollection existCerts2 = storeMy.Certificates.Find(X509FindType.FindBySerialNumber, servercert.SerialNumber, false); var certData = existCerts2[0].Export(X509ContentType.Pfx); storeMy.Close(); var x509Cert = new X509Certificate2(certData, string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); if (UseCCS) { // Revert to InstallPfx to install new certificate - this also adds binding InstallPfx(certData, string.Empty, website); } else { // Add new certificate to "WebHosting" store var store = new X509Store(CertificateStoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(x509Cert); store.Close(); } // Remove certificate from "Personal" store storeMy.Open(OpenFlags.MaxAllowed); X509CertificateCollection existCerts = storeMy.Certificates.Find(X509FindType.FindBySerialNumber, servercert.SerialNumber, false); storeMy.Remove((X509Certificate2)existCerts[0]); storeMy.Close(); // Fill object with certificate data cert.SerialNumber = servercert.SerialNumber; cert.ValidFrom = servercert.ValidFrom; cert.ExpiryDate = servercert.ExpiryDate; cert.Hash = servercert.Hash; cert.DistinguishedName = servercert.DistinguishedName; if (!UseCCS) { if (CheckCertificate(website)) { DeleteCertificate(GetCurrentSiteCertificate(website), website); } AddBinding(x509Cert, website); } } catch (Exception ex) { Log.WriteError("Error adding SSL certificate", ex); cert.Success = false; } return cert; }
private static SSLCertificate GetSSLCertificateFromX509Certificate2(X509Certificate2 cert) { var certificate = new SSLCertificate { Hostname = cert.GetNameInfo(X509NameType.SimpleName, false), FriendlyName = cert.FriendlyName, CSRLength = Convert.ToInt32(cert.PublicKey.Key.KeySize.ToString(CultureInfo.InvariantCulture)), Installed = true, DistinguishedName = cert.Subject, Hash = cert.GetCertHash(), SerialNumber = cert.SerialNumber, ExpiryDate = DateTime.Parse(cert.GetExpirationDateString()), ValidFrom = DateTime.Parse(cert.GetEffectiveDateString()), Success = true }; return certificate; }
public SSLCertificate InstallCertificate(SSLCertificate cert, WebSite website) { CX509Enrollment response = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment; try { response.Initialize(X509CertificateEnrollmentContext.ContextMachine); response.InstallResponse( InstallResponseRestrictionFlags.AllowUntrustedRoot, cert.Certificate, EncodingType.XCN_CRYPT_STRING_BASE64HEADER, null ); SSLCertificate servercert = (from c in GetServerCertificates() where c.FriendlyName == cert.FriendlyName select c).Single(); cert.SerialNumber = servercert.SerialNumber; cert.ValidFrom = servercert.ValidFrom; cert.ExpiryDate = servercert.ExpiryDate; cert.Hash = servercert.Hash; cert.DistinguishedName = servercert.DistinguishedName; if (cert.IsRenewal && CheckCertificate(website)) { DeleteCertificate(GetCurrentSiteCertificate(website), website); } AddBinding(cert, website); } catch (Exception ex) { Log.WriteError("Error adding SSL certificate", ex); cert.Success = false; } return cert; }
public SSLCertificate InstallPfx(byte[] certificate, string password, WebSite website) { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); // SSLCertificate newcert = null, oldcert = null; // Ensure we perform operations safely and preserve the original state during all manipulations if (CheckCertificate(website)) oldcert = GetCurrentSiteCertificate(website); // X509Certificate2 x509Cert = new X509Certificate2(certificate, password); #region Step 1: Register X.509 certificate in the store // Trying to keep X.509 store open as less as possible try { store.Open(OpenFlags.ReadWrite); // store.Add(x509Cert); } catch (Exception ex) { Log.WriteError(String.Format("SSLModuleService could not import PFX into X509Store('{0}', '{1}')", store.Name, store.Location), ex); // Re-throw error throw; } finally { store.Close(); } #endregion #region Step 2: Instantiate a copy of new X.509 certificate try { // store.Open(OpenFlags.ReadWrite); // newcert = new SSLCertificate { Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false), FriendlyName = x509Cert.FriendlyName, CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString()), Installed = true, DistinguishedName = x509Cert.Subject, Hash = x509Cert.GetCertHash(), SerialNumber = x509Cert.SerialNumber, ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString()), ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString()), }; } catch (Exception ex) { // Rollback X.509 store changes store.Remove(x509Cert); // Log error Log.WriteError("SSLModuleService could not instantiate a copy of new X.509 certificate. All previous changes have been rolled back.", ex); // Re-throw throw; } finally { store.Close(); } #endregion #region Step 3: Remove old certificate from the web site if any try { store.Open(OpenFlags.ReadWrite); // Check if certificate already exists, remove it. if (oldcert != null) DeleteCertificate(oldcert, website); } catch (Exception ex) { // Rollback X.509 store changes store.Remove(x509Cert); // Log the error Log.WriteError( String.Format("SSLModuleService could not remove existing certificate from '{0}' web site. All changes have been rolled back.", website.Name), ex); // Re-throw throw; } finally { store.Close(); } #endregion #region Step 4: Register new certificate with HTTPS binding on the web site try { store.Open(OpenFlags.ReadWrite); // AddBinding(newcert, website); } catch (Exception ex) { // Install old certificate back if any if (oldcert != null) InstallCertificate(oldcert, website); // Rollback X.509 store changes store.Remove(x509Cert); // Log the error Log.WriteError( String.Format("SSLModuleService could not add new X.509 certificate to '{0}' web site. All changes have been rolled back.", website.Name), ex); // Re-throw throw; } finally { store.Close(); } #endregion // return newcert; }
public void GenerateCsr(SSLCertificate cert) { // Create all the objects that will be required CX509CertificateRequestPkcs10 pkcs10 = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509CertificateRequestPkcs10", true)) as CX509CertificateRequestPkcs10; CX509PrivateKey privateKey = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey", true)) as CX509PrivateKey; CCspInformation csp = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CCspInformation", true)) as CCspInformation; CCspInformations csPs = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CCspInformations", true)) as CCspInformations; CX500DistinguishedName dn = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX500DistinguishedName", true)) as CX500DistinguishedName; CX509Enrollment enroll = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment; CObjectIds objectIds = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CObjectIds", true)) as CObjectIds; CObjectId objectId = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CObjectId", true)) as CObjectId; CX509ExtensionKeyUsage extensionKeyUsage = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionKeyUsage", true)) as CX509ExtensionKeyUsage; CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionEnhancedKeyUsage", true)) as CX509ExtensionEnhancedKeyUsage; try { // Initialize the csp object using the desired Cryptograhic Service Provider (CSP) csp.InitializeFromName("Microsoft RSA SChannel Cryptographic Provider"); // Add this CSP object to the CSP collection object csPs.Add(csp); // Provide key container name, key length and key spec to the private key object privateKey.Length = cert.CSRLength; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_ARCHIVING_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_ARCHIVING_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.MachineContext = true; // Provide the CSP collection object (in this case containing only 1 CSP object) // to the private key object privateKey.CspInformations = csPs; // Create the actual key pair privateKey.Create(); // Initialize the PKCS#10 certificate request object based on the private key. // Using the context, indicate that this is a user certificate request and don't // provide a template name pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.PrivateKey = privateKey.ToString(); // Key Usage Extension extensionKeyUsage.InitializeEncode( CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE ); pkcs10.X509Extensions.Add((CX509Extension)extensionKeyUsage); // Enhanced Key Usage Extension objectId.InitializeFromName(CertEnrollInterop.CERTENROLL_OBJECTID.XCN_OID_PKIX_KP_SERVER_AUTH); objectIds.Add(objectId); x509ExtensionEnhancedKeyUsage.InitializeEncode(objectIds); pkcs10.X509Extensions.Add((CX509Extension)x509ExtensionEnhancedKeyUsage); // Encode the name in using the Distinguished Name object string request = String.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", cert.Hostname, cert.Organisation, cert.OrganisationUnit, cert.City, cert.State, cert.Country); dn.Encode(request, X500NameFlags.XCN_CERT_NAME_STR_NONE); // enable SMIME capabilities pkcs10.SmimeCapabilities = true; // Assing the subject name by using the Distinguished Name object initialized above pkcs10.Subject = dn; // Create enrollment request enroll.InitializeFromRequest(pkcs10); enroll.CertificateFriendlyName = cert.FriendlyName; cert.CSR = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER); } catch (Exception ex) { Log.WriteError("Error creating CSR", ex); } }
public ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website) { ResultObject result = new ResultObject(); try { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySerialNumber, certificate.SerialNumber, false)[0]; store.Remove(cert); store.Close(); RemoveBinding(certificate, website); result.IsSuccess = true; } catch (Exception ex) { result.IsSuccess = false; result.AddError("", ex); } return result; }
public SSLCertificate ImportCertificate(WebSite website) { SSLCertificate certificate = new SSLCertificate { Success = false }; try { using (ServerManager sm = GetServerManager()) { Site site = sm.Sites[website.SiteId]; Binding sslbind = (from b in site.Bindings where b.Protocol == "https" select b).Single(); certificate.Hash = sslbind.CertificateHash; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); X509Certificate2 x509Cert = (from X509Certificate2 c in store.Certificates where Convert.ToBase64String(c.GetCertHash()) == Convert.ToBase64String(certificate.Hash) select c).Single(); store.Close(); certificate.Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false); certificate.FriendlyName = x509Cert.FriendlyName; certificate.CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString()); certificate.Installed = true; certificate.DistinguishedName = x509Cert.Subject; certificate.Hash = x509Cert.GetCertHash(); certificate.SerialNumber = x509Cert.SerialNumber; certificate.ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString()); certificate.ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString()); certificate.Success = true; } } catch (Exception ex) { certificate.Success = false; certificate.Certificate = ex.ToString(); } return certificate; }
private void HandleExceptionAndRollbackCertificate(X509Store store, X509Certificate2 x509Cert, SSLCertificate oldCert, WebSite webSite, string errorMessage, Exception ex) { if (!UseCCS) { try { // Rollback X.509 store changes store.Open(OpenFlags.ReadWrite); store.Remove(x509Cert); store.Close(); } catch (Exception) { Log.WriteError("SSLModuleService could not rollback and remove certificate from store", ex); } // Install old certificate back if any if (oldCert != null) InstallCertificate(oldCert, webSite); } // Log the error Log.WriteError(errorMessage + " All changes have been rolled back.", ex); // Re-throw throw ex; }
public void RemoveBinding(SSLCertificate certificate, WebSite website) { using (ServerManager sm = GetServerManager()) { Site site = sm.Sites[website.SiteId]; Binding sslbind = (from b in site.Bindings where b.Protocol == "https" select b).Single(); site.Bindings.Remove(sslbind); sm.CommitChanges(); } }
public SSLCertificate GetCurrentSiteCertificate(WebSite website) { using (ServerManager sm = GetServerManager()) { Site site = sm.Sites[website.SiteId]; Binding sslbind = (from b in site.Bindings where b.Protocol == "https" select b).Single(); byte[] currentHash = sslbind.CertificateHash; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2 oldcertificate = (from X509Certificate2 c in store.Certificates where Convert.ToBase64String(c.GetCertHash()) == Convert.ToBase64String(currentHash) select c).Single(); store.Close(); SSLCertificate certificate = new SSLCertificate(); certificate.Hash = oldcertificate.GetCertHash(); certificate.SerialNumber = oldcertificate.SerialNumber; return certificate; } }
public new ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website) { // This method removes all https bindings and all certificates associated with them. // Old implementation (IIS70) removed a single binding (there could not be more than one) and the first certificate that matched via serial number var result = new ResultObject { IsSuccess = true }; if (certificate == null) { return result; } try { var certificatesAndStoreNames = new List<Tuple<string, byte[]>>(); // User servermanager to get aLL SSL-bindings on this website and try to remove the certificates used using (var srvman = GetServerManager()) { var site = srvman.Sites[website.Name]; var bindings = site.Bindings.Where(b => b.Protocol == "https"); foreach (Binding binding in bindings.ToList()) { if (binding.SslFlags.HasFlag(SslFlags.CentralCertStore)) { if (!string.IsNullOrWhiteSpace(CCSUncPath) && Directory.Exists(CCSUncPath)) { // This is where it will be if CCS is used var path = GetCCSPath(certificate.Hostname); if (File.Exists(path)) { File.Delete(path); } // If binding with hostname, also try to delete with the hostname in the binding // This is because if SNI is used, several bindings are created for every valid name in the cerificate, but only one name exists in the SSLCertificate if (!string.IsNullOrEmpty(binding.Host)) { path = GetCCSPath(binding.Host); if (File.Exists(path)) { File.Delete(path); } } } } else { var certificateAndStoreName = new Tuple<string, byte[]>(binding.CertificateStoreName, binding.CertificateHash); if (!string.IsNullOrEmpty(binding.CertificateStoreName) && !certificatesAndStoreNames.Contains(certificateAndStoreName)) { certificatesAndStoreNames.Add(certificateAndStoreName); } } // Remove binding from site site.Bindings.Remove(binding); } srvman.CommitChanges(); foreach (var certificateAndStoreName in certificatesAndStoreNames) { // Delete all certs with the same serialnumber in Store var store = new X509Store(certificateAndStoreName.Item1, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); var certs = store.Certificates.Find(X509FindType.FindByThumbprint, BitConverter.ToString(certificateAndStoreName.Item2).Replace("-", ""), false); foreach (var cert in certs) { store.Remove(cert); } store.Close(); } } } catch (Exception ex) { Log.WriteError(String.Format("Unable to delete certificate for website {0}", website.Name), ex); result.IsSuccess = false; result.AddError("", ex); } return result; }
public void AddBinding(SSLCertificate certificate, WebSite website) { using (ServerManager srvman = GetServerManager()) { // Not sure why do we need to work with X.509 store here, so commented it out and lets see what happens X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); // List<ServerBinding> bindings = new List<ServerBinding>(); // Retrieve existing site bindings to figure out what do we have here WebObjectsModuleService webObjSvc = new WebObjectsModuleService(); bindings.AddRange(webObjSvc.GetSiteBindings(srvman, website.SiteId)); // Look for dedicated ip bool dedicatedIp = bindings.Exists(binding => String.IsNullOrEmpty(binding.Host) && binding.IP != "*"); // string bindingInformation; // bindingInformation = dedicatedIp ? string.Format("{0}:443:", website.SiteIPAddress) : string.Format("{0}:443:{1}", website.SiteIPAddress, certificate.Hostname); // srvman.Sites[website.SiteId].Bindings.Add(bindingInformation, certificate.Hash, store.Name); // store.Close(); // srvman.CommitChanges(); } }