コード例 #1
0
        protected async Task <bool> ResolveChallenges(AcmeProtocolClient acme)
        {
            if (AcmeState.PendingStatus == _state.Order?.Payload?.Status)
            {
                _logger.LogInformation("Order is pending, resolving Authorizations");
                if (_state.Authorizations == null)
                {
                    _state.Authorizations = new Dictionary <string, Authorization>();
                }
                foreach (var authzUrl in _state.Order.Payload.Authorizations)
                {
                    var authz = await acme.GetAuthorizationDetailsAsync(authzUrl);

                    _state.Authorizations[authzUrl] = authz;

                    if (AcmeState.PendingStatus == authz.Status)
                    {
                        foreach (var chlng in authz.Challenges)
                        {
                            if (string.IsNullOrEmpty(_options.ChallengeType) ||
                                _options.ChallengeType == chlng.Type)
                            {
                                var chlngValidation = AuthorizationDecoder.DecodeChallengeValidation(
                                    authz, chlng.Type, acme.Signer);
                                if (_options.ChallengeHandler(_services, chlngValidation))
                                {
                                    _logger.LogInformation("Challenge Handler has handled challenge:");
                                    _logger.LogInformation(JsonConvert.SerializeObject(chlngValidation, Formatting.Indented));
                                    var chlngUpdated = await acme.AnswerChallengeAsync(chlng.Url);

                                    if (chlngUpdated.Error != null)
                                    {
                                        _logger.LogError("Submitting Challenge Answer reported an error:");
                                        _logger.LogError(JsonConvert.SerializeObject(chlngUpdated.Error));
                                    }
                                }

                                _logger.LogInformation("Refreshing Authorization status");
                                authz = await acme.GetAuthorizationDetailsAsync(authzUrl);

                                if (AcmeState.PendingStatus != authz.Status)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                Save(_state.AuthorizationsFile, _state.Authorizations);

                _logger.LogInformation("Refreshing Order status");
                _state.Order = await acme.GetOrderDetailsAsync(_state.Order.OrderUrl, _state.Order);

                Save(_state.OrderFile, _state.Order);
            }
            return(true);
        }
コード例 #2
0
        private async void submitDnsAnswerButton_Click(object sender, EventArgs e)
        {
            var url = ResolveCaServerEndpoint();

            if (url == null)
            {
                return;
            }

            await InvokeWithWaitCursor(async() =>
            {
                var signer = new PkiJwsTool(256);
                signer.Import(_account.JwsSigner);

                using (var acme = new AcmeProtocolClient(url, signer: signer,
                                                         acct: _account.Details))
                {
                    var dir        = await acme.GetDirectoryAsync();
                    acme.Directory = dir;

                    await acme.GetNonceAsync();

                    var dnsChallenge = SelectedAuthorization.Details.Challenges.First(
                        x => x.Type == Dns01ChallengeValidationDetails.Dns01ChallengeType);

                    var updatedDnsChallenge = await acme.AnswerChallengeAsync(dnsChallenge.Url);
                    var details             = await acme.GetOrderDetailsAsync(
                        _lastOrder.Details.OrderUrl ?? _lastOrder.FirstOrderUrl);
                    _lastOrder.Details = details;
                    Repo.Saveorder(_lastOrder);

                    RebindOrderControls();
                    SetStatus("DNS Challenge Answered; Order refreshed and saved");

                    await RefreshOrderAuthorizations(acme);
                }

                Repo.Saveorder(_lastOrder);
                RebindOrderControls();
                SetStatus("DNS Challenge Answered; Order details and Authorizations refreshed and saved");

                await DecodeOrderAuthorizationChallenges(signer);

                Repo.Saveorder(_lastOrder);
                RebindOrderControls();
                SetStatus("DNS Challenge Answered; Order details and Authorizations refreshed, Challenges decoded and saved");
            });
        }
コード例 #3
0
        public async Task AnswerChallenge()
        {
            using (var http = _server.CreateClient())
            {
                var dir = await GetDir();

                var dnsIds = new[] { "foo.mock.acme2.zyborg.io" };

                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 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);
                    }
                }
            }
        }
コード例 #4
0
ファイル: AcmeClient.cs プロジェクト: ZhHong/win-acme
        internal async Task <Challenge> AnswerChallenge(Challenge challenge)
        {
            // Have to loop to wait for server to stop being pending
            challenge = await Retry(() => _client.AnswerChallengeAsync(challenge.Url));

            var tries = 1;

            while (
                challenge.Status == AuthorizationPending ||
                challenge.Status == AuthorizationProcessing)
            {
                await Task.Delay(_settings.Acme.RetryInterval * 1000);

                _log.Debug("Refreshing authorization ({tries}/{count})", tries, _settings.Acme.RetryCount);
                challenge = await Retry(() => _client.GetChallengeDetailsAsync(challenge.Url));

                tries += 1;
                if (tries > _settings.Acme.RetryCount)
                {
                    break;
                }
            }
            return(challenge);
        }
コード例 #5
0
        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);
                    }
                }
            }
        }
コード例 #6
0
ファイル: AcmeClient.cs プロジェクト: zoka-ml/win-acme
 internal Challenge AnswerChallenge(Challenge challenge)
 {
     return(Retry(() => _client.AnswerChallengeAsync(challenge.Url).Result));
 }
コード例 #7
0
        public async Task <StatusMessage> SubmitChallenge(ILog log, string challengeType, AuthorizationChallengeItem attemptedChallenge)
        {
            if (attemptedChallenge == null)
            {
                return(new StatusMessage
                {
                    IsOK = false,
                    Message = "Challenge could not be submitted. No matching attempted challenge."
                });
            }

            if (!attemptedChallenge.IsValidated)
            {
                //  IChallengeContext challenge = (IChallengeContext)attemptedChallenge.ChallengeData;
                try
                {
                    var result = await _client.AnswerChallengeAsync(attemptedChallenge.ResourceUri);

                    var attempts = 10;

                    while (attempts > 0 && result.Status == "pending" || result.Status == "processing")
                    {
                        result = await _client.GetChallengeDetailsAsync(attemptedChallenge.ResourceUri);
                    }

                    if (result.Status == "valid")
                    {
                        return(new StatusMessage
                        {
                            IsOK = true,
                            Message = "Submitted"
                        });
                    }
                    else
                    {
                        return(new StatusMessage
                        {
                            IsOK = false,
                            Message = result.Error.ToString()
                        });
                    }
                }
                catch (ACMESharp.Protocol.AcmeProtocolException exp)
                {
                    var msg = $"Submit Challenge failed: {exp.ProblemDetail}";

                    log.Error(msg);

                    return(new StatusMessage
                    {
                        IsOK = false,
                        Message = msg
                    });
                }
            }
            else
            {
                return(new StatusMessage
                {
                    IsOK = true,
                    Message = "Validated"
                });
            }
        }
コード例 #8
0
ファイル: DomainController.cs プロジェクト: franklbt/mfork
        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
            }));
        }