public async Task When_a_wrong_merchant_id_is_sent_then_the_transaction_should_fail()
        {
            var idinUrl = new Uri("https://idintest.rabobank.nl/bvn-idx-bankid-rs/bankidGateway");
            var client  = new IdinClient(
                idinUrl,
                () => certificateStore.GetCertificate(
                    "BC2262A6F2E6DB3A63138A167A0E2AA114E2E3AD",
                    false),
                () => new List <X509Certificate2> {
                certificateStore.GetCertificate(
                    "ad96a0ce00209e56f536f0e017415e68460b2b22",
                    false),
            },
                () => new List <X509Certificate2> {
                certificateStore.GetCertificate(
                    "4CC9A1382521DA468F657191EA9B6B996EFFFCF8",
                    false),
            },
                "Test");

            var idinResult = await client.GetIssuersAsync(
                new GetIssuersSettings {
                SubId = 0,
            });

            idinResult.HasError.Should().BeTrue();
            idinResult.ErrorDetails.ErrorMessage.Should().Contain("Value too short");
        }
Пример #2
0
        private async Task <X509Certificate2> GetOrCreateCertificate(CertificateFactory factory, CancellationToken cancellationToken)
        {
            var domainName = _options.Value.DomainNames[0];
            var cert       = _certificateStore.GetCertificate(domainName);

            if (cert != null)
            {
                _logger.LogDebug("Certificate for {hostname} already found.", domainName);
                return(cert);
            }

            if (!_hasRegistered)
            {
                _hasRegistered = true;
                await factory.RegisterUserAsync(cancellationToken);
            }

            try
            {
                _logger.LogInformation("Creating certificate for {hostname} using ACME server {acmeServer}", domainName, _options.Value.GetAcmeServer(_hostEnvironment));
                cert = await factory.CreateCertificateAsync(cancellationToken);

                _logger.LogInformation("Created certificate {subjectName} ({thumbprint})", cert.Subject, cert.Thumbprint);
                _certificateStore.Save(domainName, cert);
                return(cert);
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "Failed to automatically create a certificate for {hostname}", domainName);
                throw;
            }
        }
Пример #3
0
        /// <summary>
        /// Creates a IRestClient with a ClientCertificate.
        /// </summary>
        /// <returns></returns>
        private IRestClient CreateRestClient()
        {
            var certificate = _certificateStore.GetCertificate();
            var client      = new RestClient(_config.BaseUrl)
            {
                // We need to add the clientCertificate in order to authenticate.
                ClientCertificates = new X509CertificateCollection {
                    certificate
                }
            };

            return(client);
        }
Пример #4
0
        public async Task <object> Get(string id)
        {
            CertificateId     certId = new CertificateId(id);
            ICertificate      cert   = null;
            ICertificateStore store  = _storeProvider.Stores.FirstOrDefault(s => s.Name.Equals(certId.StoreName, StringComparison.OrdinalIgnoreCase));

            if (store != null)
            {
                cert = await store.GetCertificate(certId.Id);
            }

            if (cert == null)
            {
                return(NotFound());
            }

            return(CertificateHelper.ToJsonModel(cert, Context.Request.GetFields()));
        }
        public async Task Run(IAcmeDnsRequest acmeDnsRequest, int renewXNumberOfDaysBeforeExpiration)
        {
            try
            {
                CertificateInstallModel model = null;

                string hostsPlusSeparated = AcmeClient.GetHostsPlusSeparated(acmeDnsRequest.Hosts);
                var    certname           = $"{hostsPlusSeparated}-{acmeDnsRequest.AcmeEnvironment.Name}";
                var    cert = await certificateStore.GetCertificate(certname, acmeDnsRequest.PFXPassword);

                if (cert == null || cert.Certificate.NotAfter < DateTime.UtcNow.AddDays(renewXNumberOfDaysBeforeExpiration)) //Cert doesnt exist or expires in less than renewXNumberOfDaysBeforeExpiration days, lets renew.
                {
                    logger.LogInformation("Certificate store didn't contain certificate or certificate was expired starting renewing");
                    model = await acmeClient.RequestDnsChallengeCertificate(acmeDnsRequest);

                    model.CertificateInfo.Name = certname;
                    await certificateStore.SaveCertificate(model.CertificateInfo);
                }
                else
                {
                    logger.LogInformation("Certificate expires in more than {renewXNumberOfDaysBeforeExpiration} days, reusing certificate from certificate store", renewXNumberOfDaysBeforeExpiration);
                    model = new CertificateInstallModel()
                    {
                        CertificateInfo = cert,
                        Hosts           = acmeDnsRequest.Hosts
                    };
                }
                await certificateConsumer.Install(model);

                logger.LogInformation("Removing expired certificates");
                var expired = await certificateConsumer.CleanUp();

                logger.LogInformation("The following certificates was removed {Thumbprints}", string.Join(", ", expired.ToArray()));
            }
            catch (Exception e)
            {
                logger.LogError(e, "Failed");
                throw;
            }
        }
Пример #6
0
        public async Task Run(AcmeDnsRequest acmeDnsRequest, int renewXNumberOfDaysBeforeExpiration)
        {
            try
            {
                CertificateInstallModel model = null;

                var             certname = acmeDnsRequest.Host + "-" + acmeDnsRequest.AcmeEnvironment.Name + ".pfx";
                CertificateInfo cert     = await certificateStore.GetCertificate(certname, acmeDnsRequest.PFXPassword);

                if (cert == null || cert.Certificate.NotAfter < DateTime.UtcNow.AddDays(renewXNumberOfDaysBeforeExpiration)) //Cert doesnt exist or expires in less than 21 days, lets renew.
                {
                    logger.LogInformation("Certificate store didn't contain certificate or certificate was expired starting renewing");
                    model = await acmeClient.RequestDnsChallengeCertificate(acmeDnsRequest);

                    model.CertificateInfo.Name = certname;
                    await certificateStore.SaveCertificate(model.CertificateInfo);
                }
                else
                {
                    logger.LogInformation("Certificate expires in more than {renewXNumberOfDaysBeforeExpiration} days, reusing certificate from certificate store", renewXNumberOfDaysBeforeExpiration);
                    model = new CertificateInstallModel()
                    {
                        CertificateInfo = cert,
                        Host            = acmeDnsRequest.Host
                    };
                }
                await azureWebAppService.Install(model);

                logger.LogInformation("Removing expired certificates");
                System.Collections.Generic.List <string> expired = azureWebAppService.RemoveExpired();
                logger.LogInformation("The following certificates was removed {Thumbprints}", string.Join(", ", expired.ToArray()));
            }
            catch (Exception e)
            {
                logger.LogError(e, "Failed");
                throw;
            }
        }
Пример #7
0
        private static object ToJsonModel(Binding binding)
        {
            dynamic obj = new ExpandoObject();

            obj.protocol            = binding.Protocol;
            obj.binding_information = binding.BindingInformation;

            bool isHttp = binding.Protocol.Equals("http") || binding.Protocol.Equals("https");

            if (isHttp)
            {
                string ipAddress = null;
                int?   port      = null;

                if (binding.EndPoint != null && binding.EndPoint.Address != null)
                {
                    port = binding.EndPoint.Port;
                    if (binding.EndPoint.Address != null)
                    {
                        ipAddress = binding.EndPoint.Address.Equals(IPAddress.Any) ? "*" : binding.EndPoint.Address.ToString();
                    }
                }

                obj.ip_address = ipAddress;
                obj.port       = port;
                obj.hostname   = binding.Host;

                //
                // HTTPS
                if (binding.Protocol.Equals("https"))
                {
                    ICertificateStore store = null;

                    // Windows store
                    if (binding.CertificateStoreName != null)
                    {
                        string thumbprint = binding.CertificateHash == null ? null : BitConverter.ToString(binding.CertificateHash)?.Replace("-", string.Empty);
                        store = CertificateStoreProviderAccessor.Instance?.Stores
                                .FirstOrDefault(s => s.Name.Equals(binding.CertificateStoreName, StringComparison.OrdinalIgnoreCase));

                        // Certificate
                        if (store != null)
                        {
                            obj.certificate = CertificateHelper.ToJsonModelRef(GetCertificate(() => store.GetCertificate(thumbprint).Result));
                        }
                    }

                    // IIS Central Certificate Store
                    else if (binding.Schema.HasAttribute(sslFlagsAttribute) && binding.SslFlags.HasFlag(SslFlags.CentralCertStore) && !string.IsNullOrEmpty(binding.Host))
                    {
                        ICentralCertificateStore centralStore = null;

                        if (PathUtil.IsValidFileName(binding.Host))
                        {
                            centralStore = CertificateStoreProviderAccessor.Instance?.Stores.FirstOrDefault(s => s is ICentralCertificateStore) as ICentralCertificateStore;
                        }

                        // Certificate
                        if (centralStore != null)
                        {
                            obj.certificate = CertificateHelper.ToJsonModelRef(GetCertificate(() => centralStore.GetCertificateByHostName(binding.Host.Replace('*', '_')).Result));
                        }
                    }

                    //
                    // Ssl Flags
                    if (binding.Schema.HasAttribute(sslFlagsAttribute))
                    {
                        obj.require_sni = binding.SslFlags.HasFlag(SslFlags.Sni);
                    }
                }
            }

            return(obj);
        }
Пример #8
0
        private static void SetBinding(Binding binding, dynamic obj)
        {
            string protocol           = DynamicHelper.Value(obj.protocol);
            string bindingInformation = DynamicHelper.Value(obj.binding_information);
            bool?  requireSni         = DynamicHelper.To <bool>(obj.require_sni);

            if (protocol == null)
            {
                throw new ApiArgumentException("binding.protocol");
            }

            binding.Protocol = protocol;

            bool isHttp = protocol.Equals("http") || protocol.Equals("https");

            if (isHttp)
            {
                //
                // HTTP Binding information provides port, ip address, and hostname
                UInt16    port;
                string    hostname;
                IPAddress ipAddress = null;

                if (bindingInformation == null)
                {
                    var ip = DynamicHelper.Value(obj.ip_address);
                    if (ip == "*")
                    {
                        ipAddress = IPAddress.Any;
                    }
                    else if (!IPAddress.TryParse(ip, out ipAddress))
                    {
                        throw new ApiArgumentException("binding.ip_address");
                    }

                    UInt16?p = (UInt16?)DynamicHelper.To(obj.port, 1, UInt16.MaxValue);
                    if (p == null)
                    {
                        throw new ApiArgumentException("binding.port");
                    }
                    port = p.Value;

                    hostname = DynamicHelper.Value(obj.hostname) ?? string.Empty;
                }
                else
                {
                    var parts = bindingInformation.Split(':');
                    if (parts.Length != 3)
                    {
                        throw new ApiArgumentException("binding.binding_information");
                    }

                    if (parts[0] == "*")
                    {
                        ipAddress = IPAddress.Any;
                    }
                    else if (!IPAddress.TryParse(parts[0], out ipAddress))
                    {
                        throw new ApiArgumentException("binding.binding_information");
                    }

                    if (!UInt16.TryParse(parts[1], out port))
                    {
                        throw new ApiArgumentException("binding.binding_information");
                    }

                    hostname = parts[2];
                }

                binding.Protocol = protocol;

                // HTTPS
                if (protocol.Equals("https"))
                {
                    if (string.IsNullOrEmpty(hostname) && requireSni.HasValue && requireSni.Value)
                    {
                        throw new ApiArgumentException("binding.require_sni");
                    }

                    if (obj.certificate == null || !(obj.certificate is JObject))
                    {
                        throw new ApiArgumentException("binding.certificate");
                    }

                    dynamic certificate = obj.certificate;
                    string  uuid        = DynamicHelper.Value(certificate.id);

                    if (string.IsNullOrEmpty(uuid))
                    {
                        throw new ApiArgumentException("binding.certificate.id");
                    }

                    CertificateId     id    = new CertificateId(uuid);
                    ICertificateStore store = CertificateStoreProviderAccessor.Instance?.Stores
                                              .FirstOrDefault(s => s.Name.Equals(id.StoreName, StringComparison.OrdinalIgnoreCase));
                    ICertificate cert = null;

                    if (store != null)
                    {
                        cert = store.GetCertificate(id.Id).Result;
                    }

                    if (cert == null)
                    {
                        throw new NotFoundException("binding.certificate");
                    }

                    if (!cert.Purposes.Contains("Server Authentication", StringComparer.OrdinalIgnoreCase))
                    {
                        throw new ApiArgumentException("binding.certificate", "Certificate does not support server authentication");
                    }

                    //
                    // Windows builtin store
                    if (store is IWindowsCertificateStore)
                    {
                        // The specified certificate must be in the store with a private key or else there will be an exception when we commit
                        if (cert == null)
                        {
                            throw new NotFoundException("binding.certificate");
                        }
                        if (!cert.HasPrivateKey)
                        {
                            throw new ApiArgumentException("binding.certificate", "Certificate must have a private key");
                        }

                        List <byte> bytes = new List <byte>();
                        // Decode the hex string of the certificate hash into bytes
                        for (int i = 0; i < id.Id.Length; i += 2)
                        {
                            bytes.Add(Convert.ToByte(id.Id.Substring(i, 2), 16));
                        }

                        binding.CertificateStoreName = id.StoreName;
                        binding.CertificateHash      = bytes.ToArray();
                    }

                    //
                    // IIS Central Certificate store
                    else if (store is ICentralCertificateStore)
                    {
                        string name = Path.GetFileNameWithoutExtension(cert.Alias);

                        if (string.IsNullOrEmpty(hostname) || !hostname.Replace('*', '_').Equals(name))
                        {
                            throw new ApiArgumentException("binding.hostname", "Hostname must match certificate file name for central certificate store");
                        }

                        binding.SslFlags |= SslFlags.CentralCertStore;
                    }

                    if (requireSni.HasValue)
                    {
                        if (!binding.Schema.HasAttribute(sslFlagsAttribute))
                        {
                            // throw on IIS 7.5 which does not have SNI support
                            throw new ApiArgumentException("binding.require_sni", "SNI not supported on this machine");
                        }

                        if (requireSni.Value)
                        {
                            binding.SslFlags |= SslFlags.Sni;
                        }
                        else
                        {
                            binding.SslFlags &= ~SslFlags.Sni;
                        }
                    }
                }

                var ipModel = ipAddress.Equals(IPAddress.Any) ? "*" : ipAddress.ToString();
                binding.BindingInformation = $"{ipModel}:{port}:{hostname}";
            }
            else
            {
                //
                // Custom protocol
                if (string.IsNullOrEmpty(bindingInformation))
                {
                    throw new ApiArgumentException("binding.binding_information");
                }

                binding.BindingInformation = bindingInformation;
            }
        }