Exemple #1
0
        private async Task <X509Certificate2> CompleteCertificateRequestAsync(IOrderContext order,
                                                                              CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (_client == null)
            {
                throw new InvalidOperationException();
            }

            var commonName = _options.Value.DomainNames[0];

            _logger.LogDebug("Creating cert for {commonName}", commonName);

            var csrInfo = new CsrInfo
            {
                CommonName = commonName,
            };
            var privateKey = KeyFactory.NewKey((Certes.KeyAlgorithm)_options.Value.KeyAlgorithm);
            var acmeCert   = await _client.GetCertificateAsync(csrInfo, privateKey, order);

            _logger.LogAcmeAction("NewCertificate");

            var pfxBuilder = acmeCert.ToPfx(privateKey);
            var pfx        = pfxBuilder.Build("HTTPS Cert - " + _options.Value.DomainNames, string.Empty);

            return(new X509Certificate2(pfx, string.Empty, X509KeyStorageFlags.Exportable));
        }
 public OrderController(ApplicationDbContext db, IOrderContext orderContext, IWebHostEnvironment webHostEnvironment, UserManager <IdentityUser> userManager)
 {
     this._db                 = db;
     this._orderContext       = orderContext;
     this._webHostEnvironment = webHostEnvironment;
     this._userManager        = userManager;
 }
Exemple #3
0
        /// <summary>
        /// Register a new order on the ACME service, for the specified domains. Challenges will be automatically verified.
        /// This method manages automatically the creation of necessary directory and files.
        /// </summary>
        /// <remarks>
        /// When using HTTP Validation, the ACME directory will access to http://__domain__/.well-known/acme-challenge/token, that should be served
        /// by a local web server when not using built-in, and translated into local path {challengeVerifyPath}\.well-known\acme-challenge\token.
        /// Important Note: currently WinCertes supports only http-01 validation mode, and dns-01 validation mode with limitations.
        /// </remarks>
        /// <param name="domains">The list of domains to be registered and validated</param>
        /// <param name="httpChallengeValidator">The object used for challenge validation</param>
        /// <returns>True if successful</returns>
        public async Task <bool> RegisterNewOrderAndVerify(IList <string> domains, IHTTPChallengeValidator httpChallengeValidator, IDNSChallengeValidator dnsChallengeValidator)
        {
            try {
                // Re-init to be sure to get a fresh Nonce
                InitCertes();

                // Creating the order
                _orderCtx = await _acme.NewOrder(domains);

                if (_orderCtx == null)
                {
                    throw new Exception("Could not create certificate order.");
                }

                // And fetching authorizations
                var orderAuthz = await _orderCtx.Authorizations();

                // Looping through authorizations
                foreach (IAuthorizationContext authz in orderAuthz)
                {
                    InitCertes();
                    await ValidateAuthz(authz, httpChallengeValidator, dnsChallengeValidator);
                }
                _options.CertificateChallenged = true;
                // If we are here, it means order was properly created, and authorizations & challenges were properly verified.
                logger.Info($"Generated orders and validated challenges for domains: {String.Join(",", domains)}");
                return(true);
            } catch (Exception exp) {
                logger.Debug(exp, "Error while trying to register and validate order");
                logger.Error($"Failed to register and validate order with CA: {ProcessCertesException(exp)}");
                _options.CertificateChallenged = false;
                return(false);
            }
        }
        protected async Task ProcessOrderAuthorizations(IOrderContext orderCtx, IAcmeContext acmeCtx, CertificateInfo certInfo)
        {
            // Пройти по всем авторизациям и создать необходимые DNS записи (DNS challenge)
            // или текстовые файлы (HTTP challenge)
            var authorizations = (await orderCtx.Authorizations()).ToList();

            foreach (IAuthorizationContext authCtx in authorizations)
            {
                Challenge challenge = null;

                foreach (var handler in challengeHandlers.OrderBy(x => x.Priority))
                {
                    challenge = await handler.DoChallengeAsync(authCtx, acmeCtx, orderCtx, certInfo);

                    if (challenge != null)
                    {
                        break;
                    }
                }

                //Если не нашлось ни одного handler'а для обработки авторизации, то выкинуть исключение это означает,
                //что мы не можем завершить подтвержденрие владения доменом
                if (challenge == null)
                {
                    throw  new InvalidOperationException($"Can't complete authorizations for certificate {certInfo.Name}");
                }
            }
        }
        /// <summary>
        /// 导出证书文件
        /// </summary>
        /// <param name="orderCtx">订单上下文</param>
        /// <param name="acmeConfig">ACME配置文件实体</param>
        /// <returns></returns>
        public static async Task ExportCertificateAsync(IOrderContext orderCtx, AcmeV2Config acmeConfig)
        {
            var privateKey = KeyFactory.NewKey(KeyAlgorithm.ES256);
            var cert       = await orderCtx.Generate(new CsrInfo
            {
                CommonName       = acmeConfig.CommonName,
                CountryName      = acmeConfig.CountryName,
                State            = acmeConfig.State,
                Locality         = acmeConfig.Locality,
                Organization     = acmeConfig.Organization,
                OrganizationUnit = acmeConfig.OrganizationUnit
            }, privateKey);

            //导出整个证书链
            var certPem = cert.ToPem();

            File.WriteAllText(Path.Combine(acmeConfig.CertSavePath, acmeConfig.CertFullChainPemName), certPem);
            //导出PFX格式的证书
            var pfxBuilder = cert.ToPfx(privateKey);
            var pfx        = pfxBuilder.Build(acmeConfig.ServerCertDisplayName, acmeConfig.ServerCertPwd);

            using (FileStream fs = new FileStream(Path.Combine(acmeConfig.CertSavePath, acmeConfig.CertPfxName), FileMode.Create))
            {
                fs.Write(pfx, 0, pfx.Length);
            }
        }
Exemple #6
0
        public async Task <byte[]> GetCertificateAsync(Action <string> setDnsTxt)
        {
            IOrderContext order = await AcmeContext.NewOrder(new[] { Configuration.CertificateIdentifier });

            var authz        = (await order.Authorizations()).First();
            var dnsChallenge = await authz.Dns();

            var dnsTxt     = AcmeContext.AccountKey.DnsTxt(dnsChallenge.Token);
            var privateKey = KeyFactory.NewKey(KeyAlgorithm.ES256);

            setDnsTxt(dnsTxt);
            Challenge challenge = null;

            for (int i = 0; challenge?.Status != ChallengeStatus.Valid && i < 10; i++)
            {
                challenge = await dnsChallenge.Validate();

                if (challenge.Status == ChallengeStatus.Valid)
                {
                    break;
                }
                Thread.Sleep(1000);
            }
            var cert = await order.Generate(Configuration.CsrInfo, privateKey);

            var pfxBuilder = cert.ToPfx(privateKey);

            return(pfxBuilder.Build(Configuration.CertificateName, Configuration.CertificatePassword));
        }
        public static async Task <X509Certificate2> GetFinalCertificate(this IOrderContext orderContext, Options.CsrInfo csrInfo, string commonName, string friendlyName)
        {
            commonName.ArgNotNull(nameof(commonName));
            friendlyName.ArgNotNull(nameof(friendlyName));

            // Download final certificate
            var privateKey  = KeyFactory.NewKey(KeyAlgorithm.ES256);
            var certificate = await orderContext.Generate(new CsrInfo {
                CountryName      = csrInfo?.CountryName,
                State            = csrInfo?.State,
                Locality         = csrInfo?.Locality,
                Organization     = csrInfo?.Organization,
                OrganizationUnit = csrInfo?.OrganizationUnit,
                CommonName       = commonName
            }, privateKey);

            // Generate pfx and then load it into a X509Certificate2 class.
            // Havent found a conversion to X509Certificate2 without the need for a password...
            string tempPassword = Guid.NewGuid().ToString();

            byte[] pfx = certificate
                         .ToPfx(privateKey)
                         .Build(friendlyName, tempPassword);

            return(new X509Certificate2(pfx, tempPassword, X509KeyStorageFlags.Exportable));
        }
Exemple #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="challengeUrl"></param>
        /// <param name="challengeContent"></param>
        /// <param name="challengeFilePath"></param>
        public void GenerateHttpChallenge(out string challengeUrl, out string challengeContent, out string challengeFilePath)
        {
            this.OrderContext = this.AcmeContext.NewOrder(new List <string>()
            {
                this.HostName
            }).Result;

            if (this.OrderContext == null)
            {
                throw new Exception("Could not create certificate order.");
            }

            // And fetching authorizations
            var orderAuthz = this.OrderContext.Authorizations().Result;

            // Looping through authorizations
            foreach (IAuthorizationContext authz in orderAuthz)
            {
                // Although this is a loop, we only allow one authorization per request in our implementation,
                this.HttpChallenge = this.GenerateChallengeRequests(authz).Result;

                if (this.HttpChallenge == null)
                {
                    break;
                }

                // TODO: Revisar estos valores
                challengeContent  = this.HttpChallenge.KeyAuthz;
                challengeUrl      = $"http://{this.HostName}/.well-known/acme-challenge/" + this.HttpChallenge.Token;
                challengeFilePath = ".well-known/acme-challenge/" + this.HttpChallenge.Token;
                return;
            }

            throw new Exception("No authorization order was created.");
        }
Exemple #9
0
        /// <summary>
        /// Finalizes and download the certifcate for the order.
        /// </summary>
        /// <param name="context">The order context.</param>
        /// <param name="csr">The CSR.</param>
        /// <param name="key">The private key for the certificate.</param>
        /// <param name="retryCount">Number of retries when the Order is in 'processing' state. (default = 1)</param>
        /// <param name="preferredChain">The preferred Root Certificate.</param>
        /// <returns>
        /// The certificate generated.
        /// </returns>
        public static async Task <CertificateChain> Generate(this IOrderContext context, CsrInfo csr, IKey key, string preferredChain = null, int retryCount = 1)
        {
            var order = await context.Resource();

            if (order.Status != OrderStatus.Ready && // draft-11
                order.Status != OrderStatus.Pending) // pre draft-11
            {
                throw new AcmeException(string.Format(Strings.ErrorInvalidOrderStatusForFinalize, order.Status));
            }

            order = await context.Finalize(csr, key);

            while (order.Status == OrderStatus.Processing && retryCount-- > 0)
            {
                await Task.Delay(TimeSpan.FromSeconds(Math.Max(context.RetryAfter, 1)));

                order = await context.Resource();
            }

            if (order.Status != OrderStatus.Valid)
            {
                throw new AcmeException(Strings.ErrorFinalizeFailed);
            }

            return(await context.Download(preferredChain));
        }
Exemple #10
0
        public Tuple <int, int> TestPerfLoadOrderBook(IOrderContext context)
        {
            BuyBook.TestPerfLoadOrders(context);
            SellBook.TestPerfLoadOrders(context);

            return(Count);
        }
Exemple #11
0
        async Task <bool> LoadOrderAsync(string orderUri)
        {
            if (string.IsNullOrWhiteSpace(orderUri))
            {
                throw new ArgumentNullException(nameof(orderUri));
            }

            Console.WriteLine("Loading order");
            _OrderContext = _Acme.Order(new Uri(orderUri));

            if (_OrderContext != null)
            {
                _Order = await _OrderContext.Resource();
            }

            //if the order has or is about to expire, create a new one
            if (_Order.Expires <= DateTime.UtcNow)
            {
                Console.WriteLine("Previous order has expired");
                _Order        = null;
                _OrderContext = null;

                return(false);
            }

            return(true);
        }
        private static async Task ValidateOrder(IOrderContext order)
        {
            Log($" 4. Validating domain {_configuration.DomainName}...");
            var authz         = (await order.Authorizations()).First();
            var httpChallenge = await authz.Http();

            var keyAuthz = httpChallenge.KeyAuthz;

            Log(" 5. Writing challenge file");
            var tokens = keyAuthz.Split('.');
            await File.WriteAllTextAsync(Path.Combine(_configuration.ChallengePath, tokens[0]), keyAuthz);

            var chall = await httpChallenge.Validate();

            while (chall.Status == ChallengeStatus.Pending)
            {
                await Task.Delay(10000);

                chall = await httpChallenge.Validate();
            }

            if (chall.Status == ChallengeStatus.Valid)
            {
                Log($" 6. Domain {_configuration.DomainName} is valid!");
            }

            if (chall.Status == ChallengeStatus.Invalid)
            {
                Log($" 6. Domain {_configuration.DomainName} is NOT valid! {chall.Error.Detail}");
            }
        }
Exemple #13
0
        private async Task <byte[]> AcquireCertificateBytesFromOrderAsync(
            IOrderContext order,
            CsrInfo certificateSigningRequest,
            string certificateFriendlyName,
            string certificatePassword,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            _logger.LogInformation("Acquiring certificate through signing request.");

            var privateKey = KeyFactory.NewKey(KeyAlgorithm.ES256);

            var certificateChain = await order.Generate(certificateSigningRequest, privateKey);

            var pfxBuilder = certificateChain.ToPfx(privateKey);

            pfxBuilder.FullChain = true;

            var pfxBytes = pfxBuilder.Build(certificateFriendlyName, certificatePassword);

            _logger.LogInformation("Certificate acquired.");

            return(pfxBytes);
        }
        public void Order_Fetch_returns_old_Order_with_expected_data()
        {
            var mocks = new MockRepository();

            using (mocks.Record())
            {
                //mock DTO's
                var lineItemDto1 = mocks.StrictMock <ILineItemDto>();
                Expect.Call(lineItemDto1.Id).Return(200).Repeat.Any();
                Expect.Call(lineItemDto1.ProductName).Return("Widget A").Repeat.Any();
                Expect.Call(lineItemDto1.Price).Return(10M).Repeat.Any();
                Expect.Call(lineItemDto1.Quantity).Return(2).Repeat.Any();
                Expect.Call(lineItemDto1.Timestamp).Return(new byte[8]).Repeat.Any();
                var lineItemDto2 = mocks.StrictMock <ILineItemDto>();
                Expect.Call(lineItemDto2.Id).Return(201).Repeat.Any();
                Expect.Call(lineItemDto2.ProductName).Return("Widget B").Repeat.Any();
                Expect.Call(lineItemDto2.Price).Return(20.5M).Repeat.Any();
                Expect.Call(lineItemDto2.Quantity).Return(3).Repeat.Any();
                Expect.Call(lineItemDto2.Timestamp).Return(new byte[8]).Repeat.Any();
                var orderDto1 = mocks.StrictMock <IOrderDto>();
                Expect.Call(orderDto1.Id).Return(100).Repeat.Any();
                Expect.Call(orderDto1.Customer).Return("Bob").Repeat.Any();
                Expect.Call(orderDto1.Date).Return(DateTime.Parse("1/1/2008")).Repeat.Any();
                Expect.Call(orderDto1.ShippingCost).Return(5.5M).Repeat.Any();
                Expect.Call(orderDto1.Timestamp).Return(new byte[8]).Repeat.Any();
                Expect.Call(orderDto1.LineItems).Return(new[] { lineItemDto1, lineItemDto2 }).Repeat.Any();
                //mock read context
                IOrderContext readContext = mocks.StrictMock <IOrderContext>();
                Expect.Call(readContext.FetchSingleWithLineItems(100)).Return(orderDto1);
                readContext.Dispose();
                //mock repository
                var repository = base.MockRepository <IOrderContext>(mocks);
                Expect.Call(repository.CreateContext(false)).Return(readContext);
            }
            using (mocks.Playback())
            {
                //fetch existing order
                IOrderFactory factory = new OrderFactory();
                var           entity  = factory.Fetch(100);
                //test state of entity
                Assert.That(entity.IsNew, Is.False);
                Assert.That(entity.Id, Is.EqualTo(100));
                Assert.That(entity.Customer, Is.EqualTo("Bob"));
                Assert.That(entity.Date, Is.EqualTo(DateTime.Parse("1/1/2008")));
                Assert.That(entity.ShippingCost, Is.EqualTo(5.5M));
                //test state of items in child collection
                var collection = entity.LineItems;
                Assert.That(collection, Is.Not.Null);
                Assert.That(collection.Count, Is.EqualTo(2));
                ILineItem item;
                item = collection[0];
                Assert.That(item.ProductName, Is.EqualTo("Widget A"));
                Assert.That(item.Price, Is.EqualTo(10M));
                Assert.That(item.Quantity, Is.EqualTo(2));
                item = collection[1];
                Assert.That(item.ProductName, Is.EqualTo("Widget B"));
                Assert.That(item.Price, Is.EqualTo(20.5M));
                Assert.That(item.Quantity, Is.EqualTo(3));
            }
        }
Exemple #15
0
        private async Task ValidateOrderAsync(IOrderContext order, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var allAuthorizations = await order.Authorizations();

            var challengeContexts = await Task.WhenAll(allAuthorizations.Select(x => x.Http()));

            _logger.LogInformation("Validating all pending order authorizations.");

            var acmeChallengeResponses = challengeContexts.Select(x => new AcmeChallengeResponse(x.Token, x.KeyAuthz)).ToArray();

            foreach (var acmeChallengeResponse in acmeChallengeResponses)
            {
                await _challengeStore.SaveChallengesAsync(acmeChallengeResponse, cancellationToken);
            }

            var challenges = await ValidateChallengesAsync(challengeContexts, cancellationToken);

            var challengeExceptions = challenges
                                      .Where(x => x.Status == ChallengeStatus.Invalid)
                                      .Select(x => new Exception(x.Error.Type + ": " + x.Error.Detail))
                                      .ToArray();

            if (challengeExceptions.Length > 0)
            {
                throw new AcmeRequestException(
                          "One or more LetsEncrypt orders were invalid. Make sure that LetsEncrypt can contact the domain you are trying to request an SSL certificate for, in order to verify it.",
                          new AggregateException(challengeExceptions));
            }
        }
Exemple #16
0
 /// <summary>
 /// Dispose elements of AcmeSharpProviderV2
 /// </summary>
 public void Dispose()
 {
     this.OrderContext = null;
     this.HttpClient.Dispose();
     this.CertesSettings = null;
     this.AcmeContext    = null;
     this.AcmeHttpClient = null;
 }
Exemple #17
0
        public DeleteRefreshTokenCommandValidator(IOrderContext context)
        {
            CascadeMode = CascadeMode.Stop;

            RuleFor(cmd => cmd.UserId)
            .MustAsync((userId, ct) => context.UserRefreshToken.AnyAsync(t => t.UserId == userId, ct))
            .WithMessage((cmd, userId) => $"L'utilisateur d'ID {userId} n'existe pas");
        }
Exemple #18
0
        public OrderService(IOrderContext orderContext, OrderContext seedContext, IMapper mapper)
        {
            _orderContext = orderContext;
            _mapper       = mapper;

            // Only for seeding.
            OrderDbInitializer.Initialize(seedContext);
        }
 public OrderController(ILogger <OrderController> logger, IOrderContext orderContext, IHttpClientFactory httpClientFactory,
                        IConfiguration configuration)
 {
     _logger            = logger;
     _orderContext      = orderContext;
     _httpClientFactory = httpClientFactory;
     _configuration     = configuration;
 }
Exemple #20
0
        public SaveUserAddressCommandValidator(IOrderContext context)
        {
            RuleFor(cmd => cmd.Address.Address1)
            .NotEmpty();

            RuleFor(cmd => cmd.Address.IdCity)
            .MustAsync((zc, ct) => context.City.AnyAsync(c => c.Id == zc))
            .WithMessage((cmd, zc) => $"Le code postal '{zc}' n'éxiste pas");
        }
Exemple #21
0
 public OrderBook(IOrderContext context, String ticker, OrderAction type)
 {
     Ticker   = ticker;
     Type     = type;
     comparer = OrderAction.OrderBuy.Equals(type) ?
                Orders.STRIKE_PRICE_DESCENDING_COMPARER :
                Orders.STRIKE_PRICE_ASCENDING_COMPARER;
     LoadOrders(context);
 }
Exemple #22
0
 /// <summary>
 /// All new
 /// </summary>
 /// <param name="acmeContext"></param>
 /// <param name="accountContext"></param>
 /// <param name="orderContext"></param>
 /// <param name="workDir"></param>
 /// <param name="loggerFactory"></param>
 public FreeCertContext(IAcmeContext acmeContext, IAccountContext accountContext, IOrderContext orderContext, string workDir, ILoggerFactory loggerFactory)
 {
     _workDir       = workDir;
     _loggerFactory = loggerFactory;
     AcmeContext    = acmeContext;
     AccountContext = accountContext;
     OrderContext   = orderContext;
     _dnsResolver   = new DnsResolver(_loggerFactory.CreateLogger <DnsResolver>());
 }
 public ReviewFormController(ICatalogContext catalogContext, IRepository <Product> productRepository, IRepository <ProductReviewStatus> productReviewStatusRepository,
                             IOrderContext orderContext, IPipeline <ProductReview> productReviewPipeline)
 {
     _catalogContext                = catalogContext;
     _productRepository             = productRepository;
     _productReviewStatusRepository = productReviewStatusRepository;
     _orderContext          = orderContext;
     _productReviewPipeline = productReviewPipeline;
 }
Exemple #24
0
 public PlacedOrder(
     ChallengeDto[] challenges,
     IOrderContext order,
     IChallengeContext[] challengeContexts)
 {
     Challenges        = challenges;
     Order             = order;
     ChallengeContexts = challengeContexts;
 }
        public void Order_Save_Update_with_changed_order_and_no_line_items_calls_expected_repository_methods()
        {
            var mocks = new MockRepository();

            using (mocks.Record())
            {
                var oldTimestamp = new byte[8];
                var newTimestamp = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1 };
                //mock DTO's
                var orderDto1 = mocks.StrictMock <IOrderDto>();
                Expect.Call(orderDto1.Id).Return(100).Repeat.Any();
                Expect.Call(orderDto1.Customer).Return("Bob").Repeat.Any();
                Expect.Call(orderDto1.Date).Return(DateTime.Parse("1/1/2008")).Repeat.Any();
                Expect.Call(orderDto1.ShippingCost).Return(5.5M).Repeat.Any();
                Expect.Call(orderDto1.Timestamp).Return(oldTimestamp).Repeat.Any();
                Expect.Call(orderDto1.LineItems).Return(new ILineItemDto[] { }).Repeat.Any();
                var updatedOrderDto1 = mocks.StrictMock <IOrderDto>();
                updatedOrderDto1.Id           = 100;
                updatedOrderDto1.Customer     = "Jim";
                updatedOrderDto1.Date         = DateTime.Parse("1/1/2008");
                updatedOrderDto1.ShippingCost = 5.5M;
                updatedOrderDto1.Timestamp    = oldTimestamp;
                Expect.Call(updatedOrderDto1.Timestamp).Return(newTimestamp);
                //mock read context
                IOrderContext readContext = mocks.StrictMock <IOrderContext>();
                Expect.Call(readContext.FetchSingleWithLineItems(100)).Return(orderDto1);
                readContext.Dispose();
                //mock transactional context
                IOrderContext trxContext = mocks.StrictMock <IOrderContext>();
                trxContext.UpdateOrder(updatedOrderDto1);
                trxContext.CompleteTransaction();
                trxContext.Dispose();
                //mock repository
                var repository = base.MockRepository <IOrderContext>(mocks);
                Expect.Call(repository.CreateContext(false)).Return(readContext);
                Expect.Call(repository.CreateContext(true)).Return(trxContext);
                Expect.Call(repository.CreateOrderDto()).Return(updatedOrderDto1);
            }
            using (mocks.Playback())
            {
                //fetch existing order
                IOrderFactory factory = new OrderFactory();
                var           entity  = factory.Fetch(100);
                //change order
                entity.Customer = "Jim";
                //test that entity is old and dirty
                Assert.That(entity.IsNew, Is.False);
                Assert.That(entity.IsDirty, Is.True);
                //perform update
                entity = entity.Save();
                //test that entity is old and clean
                Assert.That(entity.IsNew, Is.False);
                Assert.That(entity.IsDirty, Is.False);
            }
        }
Exemple #26
0
        private async Task ValidateOrderAsync(string[] domains, IOrderContext order)
        {
            var allAuthorizations = await order.Authorizations();

            var challengeContextTasks = new List <Task <IChallengeContext> >();

            challengeContextTasks.AddRange(allAuthorizations.Select(x => x.Http()));

            var challengeContexts = await Task.WhenAll(challengeContextTasks);

            var nonNullChallengeContexts = challengeContexts.Where(x => x != null);

            _logger.LogInformation("Validating all pending order authorizations.");

            var challengeDtos = nonNullChallengeContexts.Select(x => new ChallengeDto()
            {
                Token = x.Type == ChallengeTypes.Dns01 ?
                        acme.AccountKey.DnsTxt(x.Token) :
                        x.Token,
                Response = x.KeyAuthz,
                Domains  = domains
            }).ToArray();

            await _persistenceService.PersistChallengesAsync(challengeDtos);

            try
            {
                var challengeValidationResponses = await ValidateChallengesAsync(nonNullChallengeContexts);

                var nonNullChallengeValidationResponses = challengeValidationResponses.Where(x => x != null).ToArray();

                if (challengeValidationResponses.Length > nonNullChallengeValidationResponses.Length)
                {
                    _logger.LogWarning("Some challenge responses were null.");
                }

                await _persistenceService.DeleteChallengesAsync(challengeDtos);

                var challengeExceptions = nonNullChallengeValidationResponses
                                          .Where(x => x.Status == ChallengeStatus.Invalid)
                                          .Select(x => new Exception($"{x.Error?.Type ?? "errortype null"}: {x.Error?.Detail ?? "null errordetails"} (challenge type {x.Type ?? "null"})"))
                                          .ToArray();

                if (challengeExceptions.Length > 0)
                {
                    throw new OrderInvalidException(
                              "One or more LetsEncrypt orders were invalid. Make sure that LetsEncrypt can contact the domain you are trying to request an SSL certificate for, in order to verify it.",
                              new AggregateException(challengeExceptions));
                }
            }
            finally
            {
                await _persistenceService.DeleteChallengesAsync(challengeDtos);
            }
        }
Exemple #27
0
        private void LoadOrders(IOrderContext context)
        {
            context.GetAllOpenOrdersByTickerAndAction(Ticker, Type).ToList()
            .ForEach(entity => {
                OrderBL order = new OrderBL(entity);
                orderIds.Add(order.OrderId, order);
                orders.Add(order);
            });

            orders.Sort(comparer);
        }
        /// <summary>
        /// Creates CSR from the order.
        /// </summary>
        /// <param name="context">The order context.</param>
        /// <param name="key">The private key.</param>
        /// <returns>The CSR.</returns>
        public static async Task <CertificationRequestBuilder> CreateCsr(this IOrderContext context, IKey key)
        {
            var builder = new CertificationRequestBuilder(key);
            var order   = await context.Resource();

            foreach (var identifier in order.Identifiers)
            {
                builder.SubjectAlternativeNames.Add(identifier.Value);
            }

            return(builder);
        }
 private Task <CertificateChain> TryOrderGenerate(IOrderContext order, string dnsName, IKey privateKey)
 {
     return(order.Generate(new CsrInfo
     {
         CountryName = "RU",
         State = "Svr",
         Locality = "Yekaterinburg",
         Organization = "AutomaticCA",
         OrganizationUnit = "Dev",
         CommonName = dnsName,
     }, privateKey));
 }
Exemple #30
0
        /// <summary>
        /// Register a new order on the ACME service, for the specified domains. Challenges will be automatically verified.
        /// This method manages automatically the creation of necessary directory and files.
        /// </summary>
        /// <remarks>
        /// The ACME directory will access to http://__domain__/.well-known/acme-challenge/token, that should be served by a local web server
        /// when not using built-in, and translated into local path {challengeVerifyPath}\.well-known\acme-challenge\token.
        /// Important Note: currently WinCertes supports only http-01 validation mode.
        /// </remarks>
        /// <param name="domains">The list of domains to be registered and validated</param>
        /// <param name="challengeValidator">The object used for challenge validation</param>
        /// <returns></returns>
        public async Task <bool> RegisterNewOrderAndVerify(IList <string> domains, IHTTPChallengeValidator challengeValidator)
        {
            try {
                // Re-init to be sure to get a fresh Nonce
                InitCertes();

                // Creating the order
                _orderCtx = await _acme.NewOrder(domains);

                if (_orderCtx == null)
                {
                    throw new Exception("Could not create certificate order.");
                }

                // And fetching authorizations
                var orderAuthz = await _orderCtx.Authorizations();

                // Looping through authorizations
                foreach (IAuthorizationContext authz in orderAuthz)
                {
                    InitCertes();
                    // For each authorization, get the challenges
                    var allChallenges = await authz.Challenges();

                    // Not sure if it's useful...
                    var res = await authz.Resource();

                    // Get the HTTP challenge
                    var httpChallenge = await authz.Http();

                    if (httpChallenge != null)
                    {
                        var resValidation = await ValidateChallenge(httpChallenge, challengeValidator);

                        if (!resValidation)
                        {
                            throw new Exception($"Could not validate challenge {httpChallenge.Location.ToString()}");
                        }
                    }
                    else
                    {
                        throw new Exception("Only HTTP challenges are supported for now");
                    }
                }
                // If we are here, it means order was properly created, and authorizations & challenges were properly verified.
                logger.Info($"Generated orders and validated challenges for domains: {String.Join(",", domains)}");
                return(true);
            } catch (Exception exp) {
                logger.Error($"Failed to register and validate order with CA: {ProcessCertesException(exp)}");
                return(false);
            }
        }
Exemple #31
0
        public void Setup()
        {
            _fakeSearchResult = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("a", 99),
                new KeyValuePair<string, int>("b", 98),
                new KeyValuePair<string, int>("c", 97),
                new KeyValuePair<string, int>("d", 96),
                new KeyValuePair<string, int>("e", 95)
            };

            _context = new OrderContext<KeyValuePair<string, int>>(_fakeSearchResult, "Key", false);
        }
 public OrdersController()
 {
     db = new OrderEDMX();
 }
 public OrdersController(IOrderContext context)
 {
     db = context;
 }