Ejemplo n.º 1
0
        public async Task <ServerHelloRequest> ClientHelloWithCookie(ISession session, ClientHelloWithCookieRequest request)
        {
            _logger.Verbose(
                $"Handling {nameof(ClientHelloWithCookieRequest)} " +
                $"(CertificateResponseId={request.CertificateResponseId}, " +
                $"Random='{BitConverter.ToString(request.Random)}', " +
                $"Cookie='{BitConverter.ToString(request.Cookie)}')."
                );
            if (!request.Cookie.SequenceEqual(session.Cookie))
            {
                _logger.Warning(
                    $"Session sent {nameof(ClientHelloWithCookieRequest)} with a mismatching cookie " +
                    $"(EndPoint='{session.EndPoint}', " +
                    $"Cookie='{BitConverter.ToString(request.Cookie)}', " +
                    $"Expected='{BitConverter.ToString(session.Cookie ?? new byte[0])}')."
                    );
                return(null);
            }
            if (!request.Random.SequenceEqual(session.ClientRandom))
            {
                _logger.Warning(
                    $"Session sent {nameof(ClientHelloWithCookieRequest)} with a mismatching client random " +
                    $"(EndPoint='{session.EndPoint}', " +
                    $"Random='{BitConverter.ToString(request.Random)}', " +
                    $"Expected='{BitConverter.ToString(session.ClientRandom ?? new byte[0])}')."
                    );
                return(null);
            }

            // Generate a server random
            session.ServerRandom = _randomProvider.GetRandom();

            // Generate a key pair
            var keyPair = _diffieHellmanService.GetECKeyPair();

            session.ServerPrivateKeyParameters = keyPair.PrivateKeyParameters;

            // Generate a signature
            var certificate = _certificateProvider.GetCertificate();
            var signature   = MakeSignature(session.ClientRandom, session.ServerRandom, keyPair.PublicKey);

            await _messageDispatcher.Send(session, new ServerCertificateRequest()
            {
                RequestId    = session.GetNextRequestId(),
                ResponseId   = request.CertificateResponseId,
                Certificates = new List <byte[]>()
                {
                    certificate.RawData
                }
            });

            return(new ServerHelloRequest()
            {
                Random = session.ServerRandom,
                PublicKey = keyPair.PublicKey,
                Signature = signature
            });
        }
Ejemplo n.º 2
0
        public override void ConfigureConnectionFactory(ConnectionFactory factory, Exchange exchange)
        {
            // try to get a certificate
            X509Certificate2 cert = _certProvider.GetCertificate();

            if (null != cert)
            {
                _log.Info("A certificate was located with subject: " + cert.Subject);
            }
            else
            {
                throw new RabbitException("Cannot connect to an exchange because no certificate was found");
            }

            base.ConfigureConnectionFactory(factory, exchange);

            // let's set the connection factory's ssl-specific settings
            // NOTE: it's absolutely required that what you set as Ssl.ServerName be
            //       what's on your rabbitmq server's certificate (its CN - common name)
            factory.AuthMechanisms = new AuthMechanismFactory[] { new ExternalMechanismFactory() };
            factory.Ssl.Certs      = new X509CertificateCollection(new X509Certificate[] { cert });
            factory.Ssl.ServerName = exchange.HostName;
            factory.Ssl.Enabled    = true;
            // TLS will enable more secure cipher suites to use in the exchange, encryption, and HMAC algorithms
            // used on a secure connection. Also, if the Windows OS the client runs on has the FIPS Mode security
            // policy enabled (Windows STIG), this will ensure successful connections to the Message Broker.
            factory.Ssl.Version = System.Security.Authentication.SslProtocols.Tls;
        }
        public byte[] GetSignature(byte[] content)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            var certificate = _Provider.GetCertificate();

            if (certificate == null)
            {
                throw new InvalidOperationException("Certificate not found.");
            }

            var chain = GetChainWithoutRoot();

            var contentInfo = new ContentInfo(content);
            var signedCms   = new SignedCms(contentInfo, true);
            var signer      = new System.Security.Cryptography.Pkcs.CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);

            signedCms.Certificates.AddRange(chain);
            signedCms.ComputeSignature(signer);

            return(signedCms.Encode());
        }
Ejemplo n.º 4
0
        public byte[] GetSignature(byte[] content)
        {
            var cer = _Provider.GetCertificate();

            if (cer == null)
            {
                throw new InvalidOperationException("Certificate not found.");
            }

            var cert          = DotNetUtilities.FromX509Certificate(cer);
            var signaturePair = DotNetUtilities.GetKeyPair(cer.PrivateKey);

            IList certList = new ArrayList();
            IList crlList  = new ArrayList();

            certList.Add(cert);

            IX509Store x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certList));
            IX509Store x509Crls  = X509StoreFactory.Create("CRL/Collection", new X509CollectionStoreParameters(crlList));

            var gen = new CmsSignedDataGenerator();

            gen.AddCertificates(x509Certs);

            gen.AddSigner(signaturePair.Private, cert, CmsSignedGenerator.DigestSha256);
            //gen.AddCrls(x509Crls);

            var cmsSignedData = gen.Generate(new CmsProcessableByteArray(content), false);
            var signature     = cmsSignedData.GetEncoded(Asn1Encodable.Der);

            return(signature);
        }
 public void UpdateUsing(ICertificateProvider certificateProvider)
 {
     lock (sync)
     {
         x509      = certificateProvider.GetCertificate();
         expiresAt = timeProvider.Now + lifeSpan;
     }
 }
Ejemplo n.º 6
0
        public async Task <SigningCredentials> GetSigningCredentialsAsync()
        {
            X509Certificate2 certificate = await certificateProvider.GetCertificate();

            return(certificate != null
                ? new SigningCredentials(new X509SecurityKey(certificate), SecurityAlgorithms.RsaSha256)
                : null);
        }
Ejemplo n.º 7
0
        public async Task Load(CancellationToken cancellationToken)
        {
            X509Certificate2 certificate = await certificateProvider.GetCertificate();

            if (certificate != null)
            {
                serverCertificateSelector.Add(certificate);
            }
        }
Ejemplo n.º 8
0
        public X509Certificate2 GetCertificate()
        {
            if (cache == null)
            {
                cache = _certificateProvider.GetCertificate();
            }

            return(cache);
        }
        public byte[] GetSignature(byte[] content)
        {
            using var hasher = SHA256.Create();
            var hash = hasher.ComputeHash(content);

            var cert = _Provider.GetCertificate();

            if (cert == null)
                throw new InvalidOperationException("Certificate not found");

            var signer = cert.GetECDsaPrivateKey();
            return signer.SignHash(hash);
        }
Ejemplo n.º 10
0
        public DigitalSignatureProcessor(ICertificateProvider certProvider)
        {
            _certProvider = certProvider;

            try
            {
                _cert = certProvider.GetCertificate();
            }
            catch (Exception ex)
            {
                _log.Error("Failed to get a certificate from the provider", ex);
            }
        }
        public DigitalSignatureProcessor(ICertificateProvider certProvider)
        {
            _certProvider = certProvider;

            try
            {
                _cert = certProvider.GetCertificate();
            }
            catch (Exception ex)
            {
                _log.Error("Failed to get a certificate from the provider", ex);
            }
        }
        public string GetAuthnRequest(string authnRequestId, string relayState, string assertionConsumerServiceUrl)
        {
            var signingCertificate = _certificateProvider.GetCertificate();

            var saml20AuthnRequest =
                _saml2MessageFactory.CreateAuthnRequest(authnRequestId, assertionConsumerServiceUrl);

            // check protocol binding if supporting more than HTTP-REDIRECT
            return(_httpRedirectBinding.BuildAuthnRequestUrl(saml20AuthnRequest,
                                                             signingCertificate.ServiceProvider.PrivateKey,
                                                             _identityProviderConfiguration.HashingAlgorithm, relayState));
        }
 InMemoryCertificate GetOrUpdateCertificate(InMemoryCertificate cert, ICertificateProvider certificateProvider)
 {
     lock (sync)
     {
         if (cert == null)
         {
             cert = new InMemoryCertificate(certificateProvider.GetCertificate(), inMemLifeSpan, timeProvider);
         }
         if (cert.IsExpired)
         {
             cert.UpdateUsing(certificateProvider);
         }
         return(cert);
     }
 }
Ejemplo n.º 14
0
        public async Task <IEnumerable <SecurityKeyInfo> > GetValidationKeysAsync()
        {
            X509Certificate2 certificate = await certificateProvider.GetCertificate();

            return(certificate != null
                ? new[]
            {
                new SecurityKeyInfo
                {
                    Key = new X509SecurityKey(certificate, SecurityAlgorithms.RsaSha256),
                    SigningAlgorithm = SecurityAlgorithms.RsaSha256
                }
            }
                : Enumerable.Empty <SecurityKeyInfo>());
        }
        private RSA GetRSA(KeyType keyType)
        {
            var cert = _certificateProvider.GetCertificate();

            switch (keyType)
            {
            case KeyType.Private:
                return(cert.GetRSAPrivateKey());

            case KeyType.Public:
                return(cert.GetRSAPublicKey());

            default:
                throw new UserException("Unknown KeyType " + keyType.ToString());
            }
        }
Ejemplo n.º 16
0
        public byte[] GetSignature(byte[] content)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            var certificate = _certificateProvider.GetCertificate();

            if (!certificate.HasPrivateKey)
            {
                throw new InvalidOperationException($"Certificate does not have a private key - Subject:{certificate.Subject} Thumbprint:{certificate.Thumbprint}.");
            }

            var certificateChain = _certificateChainProvider.GetCertificates();

            var contentInfo = new ContentInfo(content);
            var signedCms   = new SignedCms(contentInfo, true);

            signedCms.Certificates.AddRange(certificateChain);

            var signer      = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);
            var signingTime = new Pkcs9SigningTime(_dateTimeProvider.Now());

            signer.SignedAttributes.Add(new CryptographicAttributeObject(signingTime.Oid, new AsnEncodedDataCollection(signingTime)));

            try
            {
                signedCms.ComputeSignature(signer);
            }
            catch (Exception e)
            {
                //NB. Cannot catch the internal exception type (cross-platform design of .NET Core)
                if (e.GetType().Name == "WindowsCryptographicException" && e.Message == "Keyset does not exist" && !WindowsIdentityQueries.CurrentUserIsAdministrator())
                {
                    throw new InvalidOperationException("Failed to sign with certificate when current user does not have UAC elevated permissions.", e);
                }

                throw;
            }

            return(signedCms.Encode());
        }
Ejemplo n.º 17
0
        public WebRequest CreateRequest(string url)
        {
            try
            {
                WebRequest request = WebRequest.Create(url);

                if (request is HttpWebRequest)
                {
                    ((HttpWebRequest)request).ClientCertificates.Add(_certificateProvider.GetCertificate());
                }
                else
                {
                    throw new ApplicationException(string.Format("WebRequest.Create() did not return an HttpWebRequest for the Url: {0}  Only HTTPS urls are supported by the CertificateWebRequestFactory.", url));
                }

                return(request);
            }
            catch (Exception ex)
            {
                _log.Error("Failed to create WebRequest.", ex);
                throw;
            }
        }
        public string GetAuthnRequest(string authnRequestId, string relayState, string assertionConsumerServiceUrl)
        {
            System.Console.WriteLine("");
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => authnRequestId: " + authnRequestId);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => relayState: " + relayState);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => assertionConsumerServiceUrl: " + assertionConsumerServiceUrl);

            var signingCertificate = _certificateProvider.GetCertificate();

            System.Console.WriteLine("[SamlService][GetAuthnRequest] => signingCertificate.IdentityProvider: " + signingCertificate.IdentityProvider);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => signingCertificate.ServiceProvider: " + signingCertificate.ServiceProvider);

            var saml20AuthnRequest =
                _saml2MessageFactory.CreateAuthnRequest(authnRequestId, assertionConsumerServiceUrl);

            System.Console.WriteLine("");
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.ID: " + saml20AuthnRequest.ID);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.Issuer: " + saml20AuthnRequest.Issuer);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.ForceAuthn: " + saml20AuthnRequest.ForceAuthn);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.IsPassive: " + saml20AuthnRequest.IsPassive);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.Destination: " + saml20AuthnRequest.Destination);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.IssuerFormat: " + saml20AuthnRequest.IssuerFormat);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.IssueInstant: " + saml20AuthnRequest.IssueInstant);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.ProtocolBinding: " + saml20AuthnRequest.ProtocolBinding);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.Request.AssertionConsumerServiceUR: " + saml20AuthnRequest.Request.AssertionConsumerServiceURL);
            System.Console.WriteLine("");


            System.Console.WriteLine("[SamlService][GetAuthnRequest] => saml20AuthnRequest.GetXml(): " + saml20AuthnRequest.GetXml());
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => signingCertificate.ServiceProvider.PrivateKey: " + signingCertificate.ServiceProvider.PrivateKey);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => _identityProviderConfiguration.HashingAlgorithm: " + _identityProviderConfiguration.HashingAlgorithm);
            System.Console.WriteLine("[SamlService][GetAuthnRequest] => relayState: " + relayState);


            // check protocol binding if supporting more than HTTP-REDIRECT
            return(_httpRedirectBinding.BuildAuthnRequestUrl(saml20AuthnRequest,
                                                             signingCertificate.ServiceProvider.PrivateKey,
                                                             _identityProviderConfiguration.HashingAlgorithm, relayState));
        }
Ejemplo n.º 19
0
        public byte[] GetSignature(byte[] content)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            //using var hasher = SHA256.Create();
            //var hash = hasher.ComputeHash(content);

            var cert = _provider.GetCertificate();

            if (cert == null)
            {
                throw new InvalidOperationException("Certificate not found");
            }

            //Should be 70 or so but not fixed length
            //Adds X.962 packaging?
            //Adds 8 magical bytes.
            var notTheResult = cert.GetECDsaPrivateKey().SignData(content, HashAlgorithmName.SHA256);

            return(new X962PackagingFix().Format(notTheResult));
        }
Ejemplo n.º 20
0
        public override void ConfigureConnectionFactory(ConnectionFactory factory, Exchange exchange)
        {
            // try to get a certificate
            X509Certificate2 cert = _certProvider.GetCertificate();

            if (null != cert)
            {
                _log.Info("A certificate was located with subject: " + cert.Subject);
            }
            else
            {
                throw new RabbitException("Cannot connect to an exchange because no certificate was found");
            }

            base.ConfigureConnectionFactory(factory, exchange);

            // let's set the connection factory's ssl-specific settings
            // NOTE: it's absolutely required that what you set as Ssl.ServerName be
            //       what's on your rabbitmq server's certificate (its CN - common name)
            factory.AuthMechanisms = new AuthMechanismFactory[] { new ExternalMechanismFactory() };
            factory.Ssl.Certs      = new X509CertificateCollection(new X509Certificate[] { cert });
            factory.Ssl.ServerName = exchange.HostName;
            factory.Ssl.Enabled    = true;
        }
Ejemplo n.º 21
0
 public X509Certificate2 GetCertificate()
 {
     return(_certProvider != null?_certProvider.GetCertificate(Settings.CertificateName, Settings.CertificatePassword) : null);
 }