public static async Task <X509Certificate2Collection> GetOrderCertificateAsync(this AcmeProtocolClient acmeProtocolClient, OrderDetails order, string preferredChain, CancellationToken cancel = default) { IEnumerable <string> linkHeaders; X509Certificate2Collection defaultX509Certificates; using (var resp = await acmeProtocolClient.GetAsync(order.Payload.Certificate, cancel)) { defaultX509Certificates = await resp.Content.ReadAsCertificatesAsync(); // 証明書チェーンが未指定の場合は即返す if (string.IsNullOrEmpty(preferredChain)) { return(defaultX509Certificates); } linkHeaders = resp.Headers.GetValues("Link"); } foreach (var linkHeader in linkHeaders) { // Link ヘッダーから alternate で指定されている URL を拾ってくる var rel = Regex.Match(linkHeader, "(?<=rel=\").+?(?=\")", RegexOptions.IgnoreCase); if (!string.Equals(rel.Value, "alternate", StringComparison.OrdinalIgnoreCase)) { continue; } var url = Regex.Match(linkHeader, "(?<=<).+?(?=>)", RegexOptions.IgnoreCase); // 代替の証明書をダウンロードする using (var resp = await acmeProtocolClient.GetAsync(url.Value, cancel)) { var x509Certificates = await resp.Content.ReadAsCertificatesAsync(); // ルート CA の名前が指定された証明書チェーンに一致する場合は返す if (x509Certificates[^ 1].GetNameInfo(X509NameType.DnsName, true) == preferredChain)
public async Task FinalizeOrder() { using (var http = _server.CreateClient()) { var dir = await GetDir(); var signer = new Crypto.JOSE.Impl.RSJwsTool(); signer.Init(); using (var acme = new AcmeProtocolClient(http, dir, signer: signer)) { await acme.GetNonceAsync(); var acct = await acme.CreateAccountAsync(new[] { "mailto:[email protected]" }); acme.Account = acct; var dnsIds = new[] { "foo.mock.acme2.zyborg.io", "foo-alt-1.mock.acme2.zyborg.io", "foo-alt-2.mock.acme2.zyborg.io", "foo-alt-3.mock.acme2.zyborg.io", }; var order = await acme.CreateOrderAsync(dnsIds); Assert.IsNotNull(order?.OrderUrl); Assert.AreEqual(dnsIds.Length, order.Payload.Authorizations?.Length); Assert.AreEqual(dnsIds.Length, order.Payload.Identifiers?.Length); var authzUrl = order.Payload.Authorizations[0]; var authz = await acme.GetAuthorizationDetailsAsync(authzUrl); Assert.IsNotNull(authz); Assert.IsFalse(authz.Wildcard ?? false); Assert.AreEqual(dnsIds[0], authz.Identifier.Value); foreach (var chlng in authz.Challenges) { var chlng2 = await acme.AnswerChallengeAsync(chlng.Url); Assert.IsNotNull(chlng2); Assert.AreEqual("valid", chlng2.Status); } var kpr = PkiKeyPair.GenerateRsaKeyPair(2048); var csr = new PkiCertificateSigningRequest($"cn={dnsIds[0]}", kpr, PkiHashAlgorithm.Sha256); csr.CertificateExtensions.Add( PkiCertificateExtension.CreateDnsSubjectAlternativeNames(dnsIds.Skip(1))); var csrDer = csr.ExportSigningRequest(PkiEncodingFormat.Der); var finalizedOrder = await acme.FinalizeOrderAsync(order.Payload.Finalize, csrDer); Assert.AreEqual("valid", finalizedOrder.Payload.Status); Assert.IsNotNull(finalizedOrder.Payload.Certificate); var getResp = await acme.GetAsync(finalizedOrder.Payload.Certificate); getResp.EnsureSuccessStatusCode(); using (var fs = new FileStream( @"C:\local\prj\bek\ACMESharp\ACMESharpCore\test\ACMESharp.MockServer.UnitTests\finalize-cert.pem", FileMode.Create)) { await getResp.Content.CopyToAsync(fs); } } } }
public async Task <IActionResult> Post([FromBody] DomainRequest request) { if (!IsValidDomain(request.Domain)) { return(BadRequest(new DomainResponse { Error = "Invalid domain" })); } var domain = string.Join(".", request.Domain.Split(".").TakeLast(2)); var subDomain = string.Join(".", request.Domain.Split(".").SkipLast(2)); var credentials = new AzureCredentialsFactory() .FromServicePrincipal( _configuration["Azure:ClientId"], _configuration["Azure:ClientSecret"], _configuration["Azure:TenantId"], AzureEnvironment.AzureGlobalCloud ); var azure = Azure .Configure() .WithRetryPolicy(new RetryPolicy(new TransientErrorIgnoreStrategy(), 0)) .Authenticate(credentials) .WithSubscription(_configuration["Azure:SubscriptionId"]); var webApp = await azure.AppServices.WebApps.GetByIdAsync( _configuration["Azure:AppId"]); try { webApp.Update() .DefineHostnameBinding() .WithThirdPartyDomain(domain) .WithSubDomain(subDomain) .WithDnsRecordType(CustomHostNameDnsRecordType.CName) .Attach() .Apply(); } catch (Exception e) { return(BadRequest(new DomainResponse { Error = "Unable to validate domain ownership" })); } _ = Task.Run(async() => { using var airtableBase = new AirtableBase(_configuration["Airtable:Key"], _configuration["Airtable:Base"]); try { HttpClient httpClient = new HttpClient { BaseAddress = new Uri(_configuration["Acme:Endpoint"]) }; AcmeProtocolClient acme = new AcmeProtocolClient(httpClient, usePostAsGet: true); var acmeDir = await acme.GetDirectoryAsync(); acme.Directory = acmeDir; await acme.GetNonceAsync(); var account = await acme.CreateAccountAsync(new[] { "mailto:" + _configuration["Acme:Email"] }, true); acme.Account = account; var order = await acme.CreateOrderAsync(new[] { request.Domain }); if (order.Payload.Status == "invalid") { return; } var authorizationUrl = order.Payload.Authorizations.FirstOrDefault(); if (string.IsNullOrEmpty(authorizationUrl)) { return; } var authorization = await acme.GetAuthorizationDetailsAsync(authorizationUrl); foreach (var challenge in authorization.Challenges.Where(x => x.Type == "http-01").ToList()) { var challengeValidationDetails = (Http01ChallengeValidationDetails) AuthorizationDecoder.DecodeChallengeValidation(authorization, challenge.Type, acme.Signer); var path = challengeValidationDetails.HttpResourcePath; var token = path.Split("/", StringSplitOptions.RemoveEmptyEntries).Last(); var value = challengeValidationDetails.HttpResourceValue; var contentType = challengeValidationDetails.HttpResourceContentType; await airtableBase.CreateRecord("Acme", new Fields { FieldsCollection = new Dictionary <string, object> { ["Token"] = token, ["Value"] = value, ["ContentType"] = contentType } }); await Task.Delay(10 * 1000); var challengeUpdated = await acme.AnswerChallengeAsync(challenge.Url); } //Wait for challenge to be resolved var waitUntil = DateTime.Now.AddSeconds(300); Authorization authorizationUpdated; do { await Task.Delay(10 * 1000); authorizationUpdated = await acme.GetAuthorizationDetailsAsync(authorizationUrl); } while (authorizationUpdated.Status != "valid" && DateTime.Now < waitUntil); if (authorizationUpdated.Status != "valid") { return; } //Generate certificate private key and CSR (Certificate signing request) var keyPair = PkiKeyPair.GenerateEcdsaKeyPair(256); var csr = new PkiCertificateSigningRequest($"CN={request.Domain}", keyPair, PkiHashAlgorithm.Sha256); var certCsr = csr.ExportSigningRequest(PkiEncodingFormat.Der); order = await acme.FinalizeOrderAsync(order.Payload.Finalize, certCsr); if (order.Payload.Status != "valid") { return; } if (string.IsNullOrEmpty(order.Payload.Certificate)) { //Wait for certificate var waitUntil2 = DateTime.Now.AddSeconds(300); while (DateTime.Now < waitUntil2) { await Task.Delay(10 * 1000); order = await acme.GetOrderDetailsAsync(order.OrderUrl, existing: order); if (!string.IsNullOrEmpty(order.Payload.Certificate)) { break; } } } if (string.IsNullOrEmpty(order.Payload.Certificate)) { return; } var certResp = await acme.GetAsync(order.Payload.Certificate); if (!certResp.IsSuccessStatusCode) { return; } var certByteArray = await certResp.Content.ReadAsByteArrayAsync(); //Export PFX file var pfxPassword = _configuration["Acme:PfxPassword"]; var privateKey = keyPair.PrivateKey; using var cert = new X509Certificate2(certByteArray); X509Chain chain = new X509Chain(); chain.Build(cert); List <PkiCertificate> chainList = new List <PkiCertificate>(); foreach (var e in chain.ChainElements) { chainList.Add(PkiCertificate.From(e.Certificate)); } var pfx = chainList[0].Export(PkiArchiveFormat.Pkcs12, chain: chainList.Skip(1), privateKey: privateKey, password: pfxPassword?.ToCharArray()); webApp.Update() .DefineSslBinding() .ForHostname(request.Domain) .WithPfxByteArrayToUpload(pfx, pfxPassword) .WithSniBasedSsl() .Attach() .Apply(); } catch (Exception e) { await airtableBase.CreateRecord("Logs", new Fields { FieldsCollection = new Dictionary <string, object> { ["Hostname"] = request.Domain, ["Event"] = "exception-thrown", ["Data"] = JsonConvert.SerializeObject(e) } }); } }); return(Ok(new DomainResponse { IsSuccessful = true })); }