public override int Start() { Certificate c = null; try { c = CertificateStore.CreateFromPfxFile(@"certs\server.pfx", "test").FindCertificateByUsage(new string[] { "1.3.6.1.5.5.7.3.1" }); } catch { AddError("CC-S-0"); return(1); } int tests = 0; // test constructor try { CertificateChain cc = new CertificateChain(null); AddError("CC-S-1"); } catch (ArgumentNullException) { } catch { AddError("CC-S-2"); } tests += 2; // do other tests tests = TestBuildChain(); tests += TestVerifyCert(); return(tests); }
private void verifyLevel1Authentication(SecureSocket socket, Certificate cert, CertificateChain chain, VerifyEventArgs e ) { if (cert == null) { if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0) { log.Warn("Client Certificate is missing and fails SIF Level 1 Authentication"); } e.Valid = false; } else if (!cert.IsCurrent) { if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0) { log.Warn("Client Certificate is invalid and fails SIF Level 1 Authentication"); } e.Valid = false; } else { e.Valid = true; } }
private void verifyLevel2Authentication(SecureSocket socket, Certificate cert, CertificateChain chain, VerifyEventArgs e ) { // Verify level 1 first verifyLevel1Authentication(socket, cert, chain, e); if (!e.Valid) { return; } CertificateStatus certStatus = chain.VerifyChain(null, AuthType.Client, VerificationFlags.IgnoreInvalidName); if (certStatus != CertificateStatus.ValidCertificate) { if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0) { log.Warn ("Client Certificate is not trusted and fails SIF Level 2 Authentication: " + certStatus.ToString()); } e.Valid = false; } else { e.Valid = true; } }
/// <summary> /// Encodes the full certificate chain in PEM. /// </summary> /// <param name="certificateChain">The certificate chain.</param> /// <param name="certKey">The certificate key.</param> /// <returns>The encoded certificate chain.</returns> public static string ToPem(this CertificateChain certificateChain, IKey certKey = null) { var certStore = new CertificateStore(); foreach (var issuer in certificateChain.Issuers) { certStore.Add(issuer.ToDer()); } var issuers = certStore.GetIssuers(certificateChain.Certificate.ToDer()); using (var writer = new StringWriter()) { if (certKey != null) { writer.WriteLine(certKey.ToPem().TrimEnd()); } writer.WriteLine(certificateChain.Certificate.ToPem().TrimEnd()); var certParser = new X509CertificateParser(); var pemWriter = new PemWriter(writer); foreach (var issuer in issuers) { var cert = certParser.ReadCertificate(issuer); pemWriter.WriteObject(cert); } return(writer.ToString()); } }
public async Task CanProcessCommand() { var domain = "www.certes.com"; var orderLoc = new Uri("http://acme.com/o/1"); var resourceGroup = "resGroup"; var appName = "my-app"; var appSlot = "staging"; var keyPath = "./cert-key.pem"; var certChainContent = string.Join( Environment.NewLine, File.ReadAllText("./Data/leaf-cert.pem"), File.ReadAllText("./Data/test-ca2.pem"), File.ReadAllText("./Data/test-root.pem")); var certChain = new CertificateChain(certChainContent); var order = new Order { Certificate = new Uri("http://acme.com/o/1/cert") }; var settingsMock = new Mock <IUserSettings>(MockBehavior.Strict); settingsMock.Setup(m => m.GetDefaultServer()).ReturnsAsync(LetsEncryptV2); settingsMock.Setup(m => m.GetAccountKey(LetsEncryptV2)).ReturnsAsync(GetKeyV2()); settingsMock.Setup(m => m.GetAzureSettings()).ReturnsAsync(new AzureSettings { ClientId = "clientId", ClientSecret = "secret", SubscriptionId = Guid.NewGuid().ToString("N"), TenantId = Guid.NewGuid().ToString("N"), }); var orderMock = new Mock <IOrderContext>(MockBehavior.Strict); orderMock.Setup(m => m.Location).Returns(orderLoc); orderMock.Setup(m => m.Resource()).ReturnsAsync(order); orderMock.Setup(m => m.Download()).ReturnsAsync(certChain); var ctxMock = new Mock <IAcmeContext>(MockBehavior.Strict); ctxMock.Setup(m => m.GetDirectory()).ReturnsAsync(MockDirectoryV2); ctxMock.Setup(m => m.Order(orderLoc)).Returns(orderMock.Object); ctxMock.SetupGet(m => m.AccountKey).Returns(GetKeyV2()); var fileMock = new Mock <IFileUtil>(MockBehavior.Strict); fileMock.Setup(m => m.ReadAllText(keyPath)) .ReturnsAsync(KeyFactory.NewKey(KeyAlgorithm.ES256).ToPem()); var appSvcMock = new Mock <IWebSiteManagementClient>(MockBehavior.Strict); var certOpMock = new Mock <ICertificatesOperations>(MockBehavior.Strict); var webAppOpMock = new Mock <IWebAppsOperations>(MockBehavior.Strict); appSvcMock.SetupSet(m => m.SubscriptionId); appSvcMock.SetupGet(m => m.WebApps).Returns(webAppOpMock.Object); appSvcMock.SetupGet(m => m.Certificates).Returns(certOpMock.Object); appSvcMock.Setup(m => m.Dispose()); certOpMock.Setup(m => m.ListByResourceGroupWithHttpMessagesAsync(resourceGroup, default, default))
public async Task <ICertificate> CreateCertificate() { try { _logger.Write("Generating certificate for {0}", domain.ZoneName); IKey privateKey = KeyFactory.NewKey(KeyAlgorithm.ES256); domain.Csr.CommonName = domain.DomainName; CertificateChain cert = await _orderContext.Generate(domain.Csr, privateKey); PfxBuilder pfxBuilder = cert.ToPfx(privateKey); byte[] pfx = pfxBuilder.Build(domain.ZoneName, "cert_password"); FileWorker.WriteFile(pfx, string.Format(@"{0}{1}.pfx", _certDir, domain.ZoneName)); FileWorker.WriteFile(cert.ToPem(certKey: privateKey), string.Format(@"{0}{1}.pem", _certDir, domain.ZoneName)); FileWorker.WriteFile(cert.Certificate.ToDer( ), string.Format(@"{0}{1}.der", _certDir, domain.ZoneName)); return(new Certificate { status = true, Cert = this.GetX509Certificate2(pfx), isExpired = false }); } catch (Exception e) { _logger.Write("Error occured while generating certificate for {0} :: error==>{1}", domain.ZoneName, e.Message); _logger.Write(e.StackTrace); return(new Certificate { status = false, errorDescription = e.Message }); } }
private string ExportFullCertPEM(IKey csrKey, CertificateChain certificateChain, string certId, string primaryDomainPath) { var storePath = Path.GetFullPath(Path.Combine(new string[] { _settingsFolder, "..\\assets", primaryDomainPath })); if (!System.IO.Directory.Exists(storePath)) { System.IO.Directory.CreateDirectory(storePath); } if (!System.IO.Directory.Exists(storePath)) { System.IO.Directory.CreateDirectory(storePath); } var pemPath = Path.Combine(storePath, certId + ".pem"); // write pem in order of Private .key, primary server .crt, intermediate .crt, issuer.crt // note: // nginx needs combined primary + intermediate.crt as pem (ssl_certificate), plus .key (ssl_certificate_key) // apache needs combined primary.crt (SSLCertificateFile), intermediate.crt (SSLCertificateChainFile), plus private .key (SSLCertificateKeyFile) var pem = certificateChain.ToPem(csrKey); System.IO.File.WriteAllText(pemPath, pem); return(pemPath); }
private int TestBuildChain() { Certificate c = null; CertificateChain cc = null; try { c = CertificateStore.CreateFromPfxFile(@"certs\server.pfx", "test").FindCertificateByUsage(new string[] { "1.3.6.1.5.5.7.3.1" }); } catch { AddWarning("CC-W-TBC1"); return(0); } try { cc = c.GetCertificateChain(); Certificate[] cs = null; try { cs = cc.GetCertificates(); } catch { AddError("CC-TBC2"); } if (cs.Length != 2) { AddError("CC-TBC3"); } if (!cs[0].Equals(c)) { AddError("CC-TBC4"); } } catch { AddError("CC-TBC1"); } return(4); }
public async Task NewCertificateShouldUpdateTargetResource() { var config = TestHelper.LoadConfig("config"); var auth = new Mock <IAuthenticationService>(); var certBuilder = new Mock <ICertificateBuilder>(); var ctx = new Mock <IAcmeContext>(); var orderContext = new Mock <IOrderContext>(); var authContext = new AuthenticationContext(ctx.Object, config.Acme); var parser = new Mock <IRenewalOptionParser>(); var log = new Mock <ILogger <RenewalService> >(); IRenewalService service = new RenewalService(auth.Object, parser.Object, certBuilder.Object, log.Object); var certStore = new Mock <ICertificateStore>(); var challengeResponder = new Mock <IChallengeResponder>(); var challengeContext = new Mock <IChallengeContext>(); var challenge = new Challenge { Status = ChallengeStatus.Valid }; var fakeChain = new CertificateChain("fakeChain"); var pfxBytes = new byte[] { 0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF }; const string fakePassword = "******"; var targetResource = new Mock <ITargetResource>(); var cert = new Mock <ICertificate>(); // check if outdated (yes, not found) parser.Setup(x => x.ParseCertificateStore(config.Certificates[0])) .Returns(certStore.Object); // let's encrypt challenge auth.Setup(x => x.AuthenticateAsync(config.Acme, CancellationToken.None)) .Returns(Task.FromResult(authContext)); ctx.Setup(x => x.NewOrder(config.Certificates[0].HostNames, null, null)) .Returns(Task.FromResult(orderContext.Object)); parser.Setup(x => x.ParseChallengeResponderAsync(config.Certificates[0], CancellationToken.None)) .Returns(Task.FromResult(challengeResponder.Object)); challengeResponder.Setup(x => x.InitiateChallengesAsync(orderContext.Object, CancellationToken.None)) .Returns(Task.FromResult(new[] { challengeContext.Object })); challengeContext.Setup(x => x.Resource()) .Returns(Task.FromResult(challenge)); // save cert certBuilder.Setup(x => x.BuildCertificateAsync(orderContext.Object, config.Certificates[0], CancellationToken.None)) .Returns(Task.FromResult((pfxBytes, fakePassword))); certStore.Setup(x => x.UploadAsync(pfxBytes, fakePassword, config.Certificates[0].HostNames, CancellationToken.None)) .Returns(Task.FromResult(cert.Object)); // update azure resource parser.Setup(x => x.ParseTargetResource(config.Certificates[0])) .Returns(targetResource.Object); // actual run - must run through all steps as no existing cert is found var r = await service.RenewCertificateAsync(config.Acme, config.Certificates[0], CancellationToken.None); r.Should().Be(RenewalResult.Success); certStore.Verify(x => x.UploadAsync(pfxBytes, fakePassword, config.Certificates[0].HostNames, CancellationToken.None)); targetResource.Verify(x => x.UpdateAsync(cert.Object, CancellationToken.None), Times.Once); }
/// <summary> /// Verifies a certificate received from the remote host. /// </summary> /// <param name="socket">The SecureSocket that received the certificate.</param> /// <param name="remote">The received certificate.</param> /// <param name="e">The event parameters.</param> protected void OnVerify(SecureSocket socket, Certificate remote, CertificateChain chain, VerifyEventArgs e) { CertificateChain cc = new CertificateChain(remote); Console.WriteLine("\r\nServer Certificate:\r\n-------------------"); Console.WriteLine(remote.ToString(true)); Console.Write("\r\nServer Certificate Verification:\r\n--------------------------------\r\n -> "); Console.WriteLine(cc.VerifyChain(socket.CommonName, AuthType.Server).ToString() + "\r\n"); }
/// <summary> /// Retrieves the certificate from the ACME service. This method also generates the key and the CSR. /// </summary> /// <param name="commonName">the CN of the certificate to be requested</param> /// <param name="pathForPfx">Path where the resulting PFX/PKCS#12 file will be generated</param> /// <param name="pfxFriendlyName">Friendly name for the resulting PFX/PKCS#12</param> /// <returns>The name of the generated PFX/PKCS#12 file, or null in case of error</returns> public async Task <AuthenticatedPFX> RetrieveCertificate(IList <string> domains, string pathForPfx, string pfxFriendlyName) { try { if (_orderCtx == null) { throw new Exception("Do not call RetrieveCertificate before RegisterNewOrderAndVerify"); } if (!System.IO.Directory.Exists(pathForPfx)) { throw new Exception("Directory for PFX writing do not exists"); } InitCertes(); // Let's generate a new key (RSA is good enough IMHO) IKey certKey = KeyFactory.FromPem(Utils.GenerateRSAKeyAsPEM(_keySize)); // Then let's generate the CSR var csr = await _orderCtx.CreateCsr(certKey); csr.AddName("CN", domains[0]); csr.SubjectAlternativeNames = domains; // and finalize the ACME order var finalOrder = await _orderCtx.Finalize(csr.Generate()); // Now we can fetch the certificate CertificateChain cert = await _orderCtx.Download(); // We build the PFX/PKCS#12 and the cert/key as PEM var pfx = cert.ToPfx(certKey); var cer = cert.ToPem(); var key = certKey.ToPem(); pfx.AddIssuers(GetCACertChainFromStore()); var pfxBytes = pfx.Build(pfxFriendlyName, PfxPassword); var fileName = pathForPfx + "\\" + Guid.NewGuid().ToString(); var pfxName = fileName + ".pfx"; var cerPath = fileName + ".cer"; var keyPath = fileName + ".key"; // We write the PFX/PKCS#12 to file System.IO.File.WriteAllBytes(pfxName, pfxBytes); logger.Info($"Retrieved certificate from the CA. The certificate is in {pfxName}"); // We write the PEMs to corresponding files System.IO.File.WriteAllText(cerPath, cer); System.IO.File.WriteAllText(keyPath, key); AuthenticatedPFX authPFX = new AuthenticatedPFX(pfxName, PfxPassword, cerPath, keyPath); return(authPFX); } catch (Exception exp) { logger.Error($"Failed to retrieve certificate from CA: {ProcessCertesException(exp)}"); return(null); } }
public IActionResult Index(string name, string pfxPassword, bool staging = false, string format = "pem", bool chain = true) { if (string.Equals(format, "pfx", StringComparison.OrdinalIgnoreCase) && string.IsNullOrWhiteSpace(pfxPassword)) { return(BadRequest("pfxPassword must be specified")); } var acmeCert = _dataContext.GetAcmeCertificate(name, staging); if (acmeCert == null) { return(NotFound("Certificate with that name does not exist")); } if (acmeCert.LatestValidAcmeOrder == null) { return(NotFound("Certificate does not yet exist")); } // Ensure cert matches the one used during authentication var id = User.FindFirst(x => x.Type == ClaimTypes.NameIdentifier)?.Value; if (!string.Equals(acmeCert.AcmeCertificateId.ToString(), id)) { return(StatusCode(403, "Status Code: 403; Forbidden")); } switch (format?.ToLower() ?? "pem") { case "pfx": var certChain = new CertificateChain(acmeCert.LatestValidAcmeOrder.RawDataPem); var key = KeyFactory.FromPem(acmeCert.Key.RawData); var pfxBuilder = certChain.ToPfx(key); var pfx = pfxBuilder.Build(acmeCert.Subject, pfxPassword); return(new ContentResult { Content = Convert.ToBase64String(pfx), ContentType = "text/plain", StatusCode = 200 }); case "pem": default: var content = chain ? acmeCert.LatestValidAcmeOrder.RawDataPem : new CertificateChain(acmeCert.LatestValidAcmeOrder.RawDataPem).Certificate.ToPem(); return(new ContentResult { Content = content, ContentType = "text/plain", StatusCode = 200 }); } }
private int TestVerifyCert() { Certificate c = null; CertificateChain cc = null; try { c = CertificateStore.CreateFromPfxFile(@"certs\server.pfx", "test").FindCertificateByUsage(new string[] { "1.3.6.1.5.5.7.3.1" }); cc = c.GetCertificateChain(); } catch { AddWarning("CC-W-TBC2"); return(0); } try { if (cc.VerifyChain("Mentalis.org Team", AuthType.Server, VerificationFlags.AllowUnknownCA) != CertificateStatus.ValidCertificate) { AddError("CC-TVC1"); } } catch { AddError("CC-TVC2"); } try { if (cc.VerifyChain("Mentalis.org Team", AuthType.Server) != CertificateStatus.UntrustedRoot) { AddError("CC-TVC3"); } } catch { AddError("CC-TVC4"); } try { if (cc.VerifyChain("Other Name", AuthType.Server, VerificationFlags.AllowUnknownCA) != CertificateStatus.NoCNMatch) { AddError("CC-TVC5"); } } catch { AddError("CC-TVC6"); } try { c = CertificateStore.CreateFromCerFile(@"certs\expired.cer").FindCertificateByUsage(new string[] { "1.3.6.1.5.5.7.3.1" }); cc = c.GetCertificateChain(); } catch { AddWarning("CC-W-TBC3"); return(0); } try { IAsyncResult ret = cc.BeginVerifyChain("Mentalis.org Team", AuthType.Server, VerificationFlags.AllowUnknownCA, null, null); ret.AsyncWaitHandle.WaitOne(); if (cc.EndVerifyChain(ret) != CertificateStatus.Expired) { AddError("CC-TVC7"); } } catch { AddError("CC-TVC8"); } return(8); }
/// <summary> /// This method is called when the SecureSocket received the remote /// certificate and when the certificate validation type is set to Manual. /// </summary> /// <param name="socket">The <see cref="SecureSocket"/> that received the certificate to verify.</param> /// <param name="remote">The <see cref="Certificate"/> of the remote party to verify.</param> /// <param name="chain">The <see cref="CertificateChain"/> associated with the remote certificate.</param> /// <param name="e">A <see cref="VerifyEventArgs"/> instance used to (in)validate the certificate.</param> /// <remarks>If an error is thrown by the code in the delegate, the SecureSocket will close the connection.</remarks> protected void OnVerify(SecureSocket socket, Certificate remote, CertificateChain chain, VerifyEventArgs e) { // get all the certificates from the certificate chain .. Certificate[] certs = chain.GetCertificates(); // .. and print them out in the console for (int i = 0; i < certs.Length; i++) { Console.WriteLine(certs[i].ToString(true)); } // print out the result of the chain verification Console.WriteLine(chain.VerifyChain(socket.CommonName, AuthType.Server)); }
/// <summary> /// verifies the certificate chain against the certificate store /// </summary> /// <param name="allCertsReceived">the chain to verify</param> /// <param name="expectedCNName">the expected CN; may be null</param> /// <param name="authType">the authtype: is the certificate to verify a client or server certificate; /// i.e when verifying a client cert, pass AuthType.Client; when verifying a server cert: pass AuthType.Server</param>ram> /// <returns></returns> protected bool IsValidCertificate(CertificateChain allCertsReceived, string expectedCNName, AuthType authType) { VerificationFlags verificationFlags = VerificationFlags.None; if (expectedCNName == null) { verificationFlags = VerificationFlags.IgnoreInvalidName; } CertificateStatus status = allCertsReceived.VerifyChain(expectedCNName, authType, verificationFlags); return(status == CertificateStatus.ValidCertificate); }
protected SslHandshakeStatus ProcessCertificate(HandshakeMessage message, bool client) { if (client) { if (m_State != HandshakeType.ServerHello) { throw new SslException(AlertDescription.UnexpectedMessage, "Certificate message must be preceded by a ServerHello message."); } } else // server { if (m_State != HandshakeType.ClientHello) { throw new SslException(AlertDescription.UnexpectedMessage, "Certificate message must be preceded by a ClientHello message."); } } UpdateHashes(message, HashUpdate.All); // input message Certificate[] certs = null; try { certs = ParseCertificateList(message.fragment); if (certs.Length == 0) { if (!m_MutualAuthentication) { return(new SslHandshakeStatus(SslStatus.MessageIncomplete, null)); } } } catch (SslException t) { throw t; } catch (Exception f) { throw new SslException(f, AlertDescription.InternalError, "The Certificate message is invalid."); } CertificateChain chain = null; m_RemoteCertificate = null; if (certs.Length != 0) { m_RemoteCertificate = certs[0]; if (m_RemoteCertificate.GetPublicKeyLength() < 512) { throw new SslException(AlertDescription.HandshakeFailure, "The pulic key should be at least 512 bits."); } CertificateStore cs = new CertificateStore(certs); for (int i = 0; i < certs.Length; i++) { certs[i].Store = cs; } chain = new CertificateChain(m_RemoteCertificate, cs); } VerifyChain(chain, client); return(new SslHandshakeStatus(SslStatus.MessageIncomplete, null)); }
protected void LogNewCertificateInfo(CertificateChain certificateChain) { var certParser = new X509CertificateParser(); var x509Cert = certParser.ReadCertificate(Encoding.UTF8.GetBytes(certificateChain.Certificate.ToPem())); logger.LogInformation("Received new certificate: {certData}", new { Subject = x509Cert.SubjectDN, Expires = x509Cert.NotAfter, Issuer = x509Cert.IssuerDN, SubjAltNames = string.Join(",", x509Cert.GetSubjectAlternativeNames().Cast <ArrayList>().Select(x => x[1])) }); }
public static byte[] Generate(RSA rsa, CertificateChain certificateChain, string password, X509ContentType certificateType) { var certificate = new X509Certificate2(certificateChain.CertificateBytes); var issuer = new X509Certificate2(certificateChain.IssuerBytes); certificate = certificate.CopyWithPrivateKey(rsa); var collection = new X509Certificate2Collection(); collection.Add(issuer); collection.Add(certificate); return(collection.Export(certificateType, password)); }
/// <summary> /// Converts the certificate to PFX with the key. /// </summary> /// <param name="certificateChain">The certificate chain.</param> /// <param name="certKey">The certificate private key.</param> /// <returns>The PFX.</returns> public static PfxBuilder ToPfx(this CertificateChain certificateChain, IKey certKey) { var pfx = new PfxBuilder(certificateChain.Certificate.ToDer(), certKey); if (certificateChain.Issuers != null) { foreach (var issuer in certificateChain.Issuers) { pfx.AddIssuer(issuer.ToDer()); } } return(pfx); }
private async Task <byte[]> CreateCertificate(IOrderContext order) { IKey privateKey = KeyFactory.NewKey(KeyAlgorithm.RS256); CertificateChain certificateChain = await order.Generate(new CsrInfo { CommonName = Hostname }, privateKey); PfxBuilder pfxBuilder = certificateChain.ToPfx(privateKey); byte[] pfx = pfxBuilder.Build(Hostname, string.Empty); return(pfx); }
/// <summary> /// 验证、生成证书 /// </summary> /// <returns></returns> public async Task <(bool, string)> GenerateCert() { if (GeneratedCert) { return(true, string.Empty); } var checkResult = await dnsHelper.CheckDns(this.ChallengeDomain, this.ChallengRecordValue); if (!checkResult.Result) { string msg = "未找到 DNS TXT 解析信息"; if (checkResult.RecordValues.Count > 0) { msg = "未找到正确的解析,当前的解析值有:<br/>"; foreach (var item in checkResult.RecordValues) { msg += item + "<br/>"; } } return(false, msg); } try { Challenge challenge = await this.dnsChallenge.Validate(); this.privateKey = KeyFactory.NewKey(KeyAlgorithm.ES256); this.cert = await this.order.Generate(new CsrInfo { CountryName = "CN", //State = "beijing", //Locality = "beijing", //Organization = "ZTImage", //OrganizationUnit = "Dev", CommonName = this.Domain }, this.privateKey); this.GeneratedCert = true; return(true, "success"); } catch { return(false, "生成证书时出现问题,请联系我们"); } }
public IActionResult Index(string name, string pfxPassword, bool staging = false, string format = "pem") { if (string.Equals(format, "pfx", StringComparison.OrdinalIgnoreCase) && string.IsNullOrWhiteSpace(pfxPassword)) { return(BadRequest("pfxPassword must be specified")); } var acmeCert = _dataContext.GetAcmeCertificate(name, staging); if (acmeCert == null) { return(NotFound("Certificate with that name does not exist")); } if (acmeCert.LatestValidAcmeOrder == null) { return(NotFound("Certificate does not yet exist")); } switch (format?.ToLower() ?? "pem") { case "pfx": var certChain = new CertificateChain(acmeCert.LatestValidAcmeOrder.RawDataPem); var key = KeyFactory.FromPem(acmeCert.Key.RawData); var pfxBuilder = certChain.ToPfx(key); var pfx = pfxBuilder.Build(acmeCert.Subject, pfxPassword); return(new ContentResult { Content = Convert.ToBase64String(pfx), ContentType = "text/plain", StatusCode = 200 }); case "pem": default: return(new ContentResult { Content = acmeCert.LatestValidAcmeOrder.RawDataPem, ContentType = "text/plain", StatusCode = 200 }); } }
protected void VerifyChain(CertificateChain chain, bool client) { VerifyEventArgs e = new VerifyEventArgs(); switch (m_Options.VerificationType) { case CredentialVerification.Manual: try { m_Options.Verifier(Parent, m_RemoteCertificate, chain, e); } catch (Exception de) { throw new SslException(de, AlertDescription.InternalError, "The code inside the CertVerifyEventHandler delegate threw an exception."); } break; case CredentialVerification.Auto: if (chain != null) { e.Valid = (chain.VerifyChain(m_Options.CommonName, client ? AuthType.Client : AuthType.Server) == CertificateStatus.ValidCertificate); } else { e.Valid = false; } break; case CredentialVerification.AutoWithoutCName: if (chain != null) { e.Valid = (chain.VerifyChain(m_Options.CommonName, client ? AuthType.Client : AuthType.Server, VerificationFlags.IgnoreInvalidName) == CertificateStatus.ValidCertificate); } else { e.Valid = false; } break; case CredentialVerification.None: default: e.Valid = true; break; } if (!e.Valid) { throw new SslException(AlertDescription.CertificateUnknown, "The certificate could not be verified."); } }
private static async Task SetupValidationResponder(Authorization authz, string alpnCert, IKey certKey) { // setup validation certificate var certC = new CertificateChain(alpnCert); var json = JsonConvert.SerializeObject(new { Cert = certC.Certificate.ToDer(), Key = certKey.ToDer(), }, JsonUtil.CreateSettings()); using (var resp = await http.Value.PostAsync( $"https://{authz.Identifier.Value}/tls-alpn-01/", new StringContent(json, Encoding.UTF8, "application/json"))) { Assert.Equal(authz.Identifier.Value, await resp.Content.ReadAsStringAsync()); } }
private string ExportFullCertPFX(string certFriendlyName, IKey csrKey, CertificateChain certificateChain, string pfxFile) { var pxfFolderPath = _settingsFolder + "\\assets\\pfx"; if (!System.IO.Directory.Exists(pxfFolderPath)) { System.IO.Directory.CreateDirectory(pxfFolderPath); } var pfxPath = pxfFolderPath + "\\" + pfxFile; var pfx = certificateChain.ToPfx(csrKey); var pfxBytes = pfx.Build(certFriendlyName, ""); System.IO.File.WriteAllBytes(pfxPath, pfxBytes); return(pfxPath); }
// ------------------------ OnVerify ------------------------------------- protected void OnVerify( SecureSocket socket, Certificate remote, CertificateChain InChain, VerifyEventArgs e) { Certificate[] certs = InChain.GetCertificates( ); for (int Ix = 0; Ix < certs.Length; Ix++) { AddMessage(NetworkRole.Client, certs[Ix].ToString(true)); } // print out the result of the chain verification AddMessage( NetworkRole.Client, "Verify certificate: " + InChain.VerifyChain(socket.CommonName, AuthType.Server).ToString( )); }
private string ExportFullCertPFX(string certFriendlyName, IKey csrKey, CertificateChain certificateChain, string certId, string primaryDomainPath) { var storePath = Path.GetFullPath(Path.Combine(new string[] { _settingsFolder, "..\\assets", primaryDomainPath })); if (!System.IO.Directory.Exists(storePath)) { System.IO.Directory.CreateDirectory(storePath); } var pfxFile = certId + ".pfx"; var pfxPath = Path.Combine(storePath, pfxFile); var pfx = certificateChain.ToPfx(csrKey); var pfxBytes = pfx.Build(certFriendlyName, ""); System.IO.File.WriteAllBytes(pfxPath, pfxBytes); return(pfxPath); }
/// <summary> /// Retrieves the certificate from the ACME service. This method also generates the key and the CSR. /// </summary> /// <param name="commonName">the CN of the certificate to be requested</param> /// <param name="pathForPfx">Path where the resulting PFX/PKCS#12 file will be generated</param> /// <param name="pfxFriendlyName">Friendly name for the resulting PFX/PKCS#12</param> /// <returns>The name of the generated PFX/PKCS#12 file, or null in case of error</returns> public async Task <string> RetrieveCertificate(IList <string> domains, string pathForPfx, string pfxFriendlyName) { try { if (_orderCtx == null) { throw new Exception("Do not call RetrieveCertificate before RegisterNewOrderAndVerify"); } if (!System.IO.Directory.Exists(pathForPfx)) { throw new Exception("Directory for PFX writing do not exists"); } InitCertes(); // Let's generate a new key (RSA is good enough IMHO) IKey certKey = KeyFactory.NewKey(KeyAlgorithm.RS256); // Then let's generate the CSR var csr = await _orderCtx.CreateCsr(certKey); csr.AddName("CN", domains[0]); csr.SubjectAlternativeNames = domains; // and finalize the ACME order var finalOrder = await _orderCtx.Finalize(csr.Generate()); // Now we can fetch the certificate CertificateChain cert = await _orderCtx.Download(); // We build the PFX/PKCS#12 var pfx = cert.ToPfx(certKey); pfx.AddIssuers(GetCACertChainFromStore()); var pfxBytes = pfx.Build(pfxFriendlyName, PfxPassword); var pfxName = Guid.NewGuid().ToString() + ".pfx"; // We write the PFX/PKCS#12 to file System.IO.File.WriteAllBytes(pathForPfx + "\\" + pfxName, pfxBytes); logger.Info($"Retrieved certificate from the CA. The certificate is in {pfxName}"); return(pfxName); } catch (Exception exp) { logger.Error($"Failed to retrieve certificate from CA: {ProcessCertesException(exp)}"); return(null); } }
static void Main(string[] args) { Console.WriteLine("This example shows how you can validate a certificate."); // load the certificate from a file Certificate cert = Certificate.CreateFromCerFile(@"client.cer"); // build a certificate chain CertificateChain cc = new CertificateChain(cert); // validate the chain CertificateStatus status = cc.VerifyChain(null, AuthType.Client); // interpret the result if (status == CertificateStatus.ValidCertificate) { Console.WriteLine("The certificate is valid."); } else { Console.WriteLine("The certificate is not valid [" + status.ToString() + "]."); } }
private string ExportFullCertPEM(IKey csrKey, CertificateChain certificateChain, string certId) { var pemFolderPath = _settingsFolder + "\\assets\\pem"; if (!System.IO.Directory.Exists(pemFolderPath)) { System.IO.Directory.CreateDirectory(pemFolderPath); } var pemPath = pemFolderPath + "\\" + certId + ".pem"; // write pem in order of Private .key, primary server .crt, intermediate .crt, issuer.crt // note: // nginx needs combined primary + intermediate.crt as pem (ssl_certificate), plus .key (ssl_certificate_key) // apache needs combined primary.crt (SSLCertificateFile), intermediate.crt (SSLCertificateChainFile), plus private .key (SSLCertificateKeyFile) var pem = certificateChain.ToPem(csrKey); System.IO.File.WriteAllText(pemPath, pem); return(pemPath); }