Ejemplo n.º 1
0
        public Task <X509Certificate2?> LoadAsync(string name, string certificatePassword, CancellationToken cancellationToken)
        {
            var certs = _store.Certificates.Find(
                X509FindType.FindBySubjectDistinguishedName,
                "CN=" + name,
                validOnly: !_options.AllowInvalidCerts);

            if (certs == null || certs.Count == 0)
            {
                return(Task.FromResult <X509Certificate2>(null));
            }

            if (_logger.IsEnabled(LogLevel.Trace))
            {
                foreach (var cert in certs)
                {
                    _logger.LogTrace("Found certificate {subject}", cert.SubjectName.Name);
                }
            }

            X509Certificate2?certWithMostTtl = null;

            foreach (var cert in certs)
            {
                if (certWithMostTtl == null || cert.NotAfter > certWithMostTtl.NotAfter)
                {
                    certWithMostTtl = cert;
                }
            }

            return(Task.FromResult(certWithMostTtl));
        }
Ejemplo n.º 2
0
        public X509Certificate2?GetCertificate(string domainName)
        {
            var certs = _store.Certificates.Find(
                X509FindType.FindBySubjectDistinguishedName,
                "CN=" + domainName,
                validOnly: !AllowInvalidCerts);

            if (certs == null || certs.Count == 0)
            {
                return(null);
            }

            if (_logger.IsEnabled(LogLevel.Trace))
            {
                foreach (var cert in certs)
                {
                    _logger.LogTrace("Found certificate {subject}", cert.SubjectName.Name);
                }
            }

            X509Certificate2?certWithMostTtl = null;

            foreach (var cert in certs)
            {
                if (certWithMostTtl == null || cert.NotAfter > certWithMostTtl.NotAfter)
                {
                    certWithMostTtl = cert;
                }
            }

            return(certWithMostTtl);
        }
Ejemplo n.º 3
0
        private X509Certificate2?GetSignerCertificate(X509Certificate2Collection?extraCandidates)
        {
            Debug.Assert(_signerInfo != null, "_signerInfo != null");
            X509Certificate2?signerCert = _signerInfo.Certificate;

            if (signerCert != null)
            {
                if (CheckCertificate(signerCert, _signerInfo, in _essCertId, in _essCertIdV2, TokenInfo))
                {
                    return(signerCert);
                }

                // SignedCms will not try another certificate in this state, so just fail.
                return(null);
            }

            if (extraCandidates == null || extraCandidates.Count == 0)
            {
                return(null);
            }

            foreach (X509Certificate2 candidate in extraCandidates)
            {
                if (CheckCertificate(candidate, _signerInfo, in _essCertId, in _essCertIdV2, TokenInfo))
                {
                    return(candidate);
                }
            }

            return(null);
        }
Ejemplo n.º 4
0
            internal byte[]? DecryptCek(X509Certificate2?cert, RSA?privateKey, out Exception?exception)
            {
                ReadOnlyMemory <byte>?parameters = _asn.KeyEncryptionAlgorithm.Parameters;
                string?keyEncryptionAlgorithm    = _asn.KeyEncryptionAlgorithm.Algorithm;

                switch (keyEncryptionAlgorithm)
                {
                case Oids.Rsa:
                    if (parameters != null &&
                        !parameters.Value.Span.SequenceEqual(s_rsaPkcsParameters))
                    {
                        exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                        return(null);
                    }
                    break;

                case Oids.RsaOaep:
                    break;

                default:
                    exception = new CryptographicException(
                        SR.Cryptography_Cms_UnknownAlgorithm,
                        _asn.KeyEncryptionAlgorithm.Algorithm);

                    return(null);
                }

                return(DecryptCekCore(cert, privateKey, _asn.EncryptedKey.Span, keyEncryptionAlgorithm, parameters, out exception));
            }
Ejemplo n.º 5
0
        public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2?certificate, AsymmetricAlgorithm?privateKey)
        {
            switch (signerIdentifierType)
            {
            case SubjectIdentifierType.Unknown:
                _signerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
                IncludeOption         = X509IncludeOption.ExcludeRoot;
                break;

            case SubjectIdentifierType.IssuerAndSerialNumber:
                _signerIdentifierType = signerIdentifierType;
                IncludeOption         = X509IncludeOption.ExcludeRoot;
                break;

            case SubjectIdentifierType.SubjectKeyIdentifier:
                _signerIdentifierType = signerIdentifierType;
                IncludeOption         = X509IncludeOption.ExcludeRoot;
                break;

            case SubjectIdentifierType.NoSignature:
                _signerIdentifierType = signerIdentifierType;
                IncludeOption         = X509IncludeOption.None;
                break;

            default:
                _signerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
                IncludeOption         = X509IncludeOption.ExcludeRoot;
                break;
            }

            Certificate     = certificate;
            DigestAlgorithm = s_defaultAlgorithm.CopyOid();
            PrivateKey      = privateKey;
        }
Ejemplo n.º 6
0
        private bool StartAuthenticate(AsyncCallback callback, object state)
        {
            Debug.Assert(_sslStream != null);
            try
            {
                _writeCallback = callback;
                if (!_incoming)
                {
                    //
                    // Client authentication.
                    //
                    _writeResult = _sslStream.BeginAuthenticateAsClient(_host,
                                                                        _engine.Certs,
                                                                        _engine.SslProtocols,
                                                                        _engine.CheckCRL > 0,
                                                                        WriteCompleted,
                                                                        state);
                }
                else
                {
                    //
                    // Server authentication.
                    //
                    // Get the certificate collection and select the first one.
                    //
                    X509Certificate2Collection?certs = _engine.Certs;
                    X509Certificate2?          cert  = null;
                    if (certs != null && certs.Count > 0)
                    {
                        cert = certs[0];
                    }

                    _writeResult = _sslStream.BeginAuthenticateAsServer(cert,
                                                                        _verifyPeer > 0,
                                                                        _engine.SslProtocols,
                                                                        _engine.CheckCRL > 0,
                                                                        WriteCompleted,
                                                                        state);
                }
            }
            catch (IOException ex)
            {
                if (Network.ConnectionLost(ex))
                {
                    //
                    // This situation occurs when connectToSelf is called; the "remote" end
                    // closes the socket immediately.
                    //
                    throw new ConnectionLostException();
                }
                throw new TransportException(ex);
            }
            catch (AuthenticationException ex)
            {
                throw new TransportException(ex);
            }

            Debug.Assert(_writeResult != null);
            return(_writeResult.CompletedSynchronously);
        }
Ejemplo n.º 7
0
        public async Task Start()
        {
            if (!_config.Model.SocketSettings.EnableHubSocket || _isRunning)
            {
                return;
            }

            try
            {
                _socketServer = new SocketServer(_logger);
                X509Certificate2?cert = null;
                if (!string.IsNullOrWhiteSpace(_config.Model.SocketSettings.SslCertLocation) && File.Exists(_config.Model.SocketSettings.SslCertLocation))
                {
                    if (!string.IsNullOrWhiteSpace(_config.Model.SocketSettings.SslCertPassword))
                    {
                        cert = new X509Certificate2(_config.Model.SocketSettings.SslCertLocation, _config.Model.SocketSettings.SslCertPassword);
                    }
                    else
                    {
                        cert = new X509Certificate2(_config.Model.SocketSettings.SslCertLocation);
                    }
                }
                //Console.WriteLine($"Loaded X509Certificate2 {cert}");
                await _socketServer.Start(_config.Model.SocketSettings.ListenIp.ToString(), _config.Model.SocketSettings.ListenPort, _config.Model.SocketSettings.AspnetConsoleLog, cert, _config.Model.SocketSettings.SslProtocol);

                _socketServer.OnClientMessage += HandleClientCommand;
                _isRunning = true;
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"ex {ex}");
                _ = Task.Run(() => { _logger?.WriteLog(ex.ToString()); });
            }
        }
Ejemplo n.º 8
0
 public Connector(X509Certificate2Collection clientCertificates, X509Certificate2?trustedCertificateAuthority, bool verifyCertificateAuthority, bool verifyCertificateName)
 {
     _clientCertificates          = clientCertificates;
     _trustedCertificateAuthority = trustedCertificateAuthority;
     _verifyCertificateAuthority  = verifyCertificateAuthority;
     _verifyCertificateName       = verifyCertificateName;
 }
        private IApiClient GetApiClient(ITestConfigurationProvider testConfig)
        {
            if (TestConfig.GetBooleanValue("mockHttp").GetValueOrDefault(false))
            {
                MockHttpMessageHandler?mockHttp = new MockHttpMessageHandler();

                OpenIdConfiguration?openIdConfigData = TestConfig.GetOpenBankingOpenIdConfiguration();
                string?openIdConfig = JsonConvert.SerializeObject(openIdConfigData);


                mockHttp.When(method: HttpMethod.Get, url: "https://issuer.com/.well-known/openid-configuration")
                .Respond(mediaType: "application/json", content: openIdConfig);

                mockHttp.When(method: HttpMethod.Get, url: "").Respond(mediaType: "application/json", content: "{}");
                mockHttp.When(method: HttpMethod.Post, url: "").Respond(mediaType: "application/json", content: "{}");

                HttpClient?client = mockHttp.ToHttpClient();

                return(new ApiClient(instrumentation: Substitute.For <IInstrumentationClient>(), httpClient: client));
            }

            X509Certificate2?certificate = CertificateFactories.GetCertificate2FromPem(
                privateKey: TestConfig.GetValue("transportcertificatekey"),
                pem: TestConfig.GetValue("transportCertificate"));

            HttpMessageHandler?handler = new HttpRequestBuilder()
                                         .SetClientCertificate(certificate)
                                         .CreateMessageHandler();

            return(ApiClientFactory.CreateApiClient(handler));
        }
Ejemplo n.º 10
0
    public static void AddCertificateForwarding(WebApplicationBuilder builder)
    {
        // <snippet_AddCertificateForwarding>
        builder.Services.AddCertificateForwarding(options =>
        {
            options.CertificateHeader = "X-SSL-CERT";

            options.HeaderConverter = headerValue =>
            {
                X509Certificate2?clientCertificate = null;

                if (!string.IsNullOrWhiteSpace(headerValue))
                {
                    clientCertificate = new X509Certificate2(StringToByteArray(headerValue));
                }

                return(clientCertificate !);

                static byte[] StringToByteArray(string hex)
                {
                    var numberChars = hex.Length;
                    var bytes       = new byte[numberChars / 2];

                    for (int i = 0; i < numberChars; i += 2)
                    {
                        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
                    }

                    return(bytes);
                }
            };
        });
Ejemplo n.º 11
0
        private X509Certificate2 makeCertificate(string sSubjectCN,
                                                 bool switchToMTAIfNeeded, X509Certificate2?signingCertificate = null,
                                                 CancellationToken cancellationToken = default)
        {
            if (switchToMTAIfNeeded && Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA)
            {
                return(Task.Run(() => makeCertificate(sSubjectCN, false, signingCertificate),
                                cancellationToken).Result);
            }

            // Subject
            string fullSubject = $"CN={sSubjectCN}";

            // Sig Algo
            const string hashAlgo = "SHA256";

            // Grace Days
            const int graceDays = -366;

            // ValiDays
            const int validDays = 1825;

            // KeyLength
            const int keyLength = 2048;

            var now         = DateTime.UtcNow;
            var graceTime   = now.AddDays(graceDays);
            var certificate = makeCertificate(sSubjectCN, fullSubject, keyLength, hashAlgo, graceTime,
                                              now.AddDays(validDays), signingCertificate);

            return(certificate);
        }
Ejemplo n.º 12
0
        public HttpsConnectionMiddleware(ConnectionDelegate next, HttpsConnectionAdapterOptions options, ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.ServerCertificate == null && options.ServerCertificateSelector == null)
            {
                throw new ArgumentException(CoreStrings.ServerCertificateRequired, nameof(options));
            }

            _next             = next;
            _handshakeTimeout = options.HandshakeTimeout;
            _logger           = loggerFactory.CreateLogger <HttpsConnectionMiddleware>();

            // Something similar to the following could allow us to remove more duplicate logic, but we need https://github.com/dotnet/runtime/issues/40402 to be fixed first.
            //var sniOptionsSelector = new SniOptionsSelector("", new Dictionary<string, SniConfig> { { "*", new SniConfig() } }, new NoopCertificateConfigLoader(), options, options.HttpProtocols, _logger);
            //_httpsOptionsCallback = SniOptionsSelector.OptionsCallback;
            //_httpsOptionsCallbackState = sniOptionsSelector;
            //_sslStreamFactory = s => new SslStream(s);

            _options = options;
            _options.HttpProtocols = ValidateAndNormalizeHttpProtocols(_options.HttpProtocols, _logger);

            // capture the certificate now so it can't be switched after validation
            _serverCertificate         = options.ServerCertificate;
            _serverCertificateSelector = options.ServerCertificateSelector;

            // If a selector is provided then ignore the cert, it may be a default cert.
            if (_serverCertificateSelector != null)
            {
                // SslStream doesn't allow both.
                _serverCertificate = null;
            }
            else
            {
                Debug.Assert(_serverCertificate != null);

                EnsureCertificateIsAllowedForServerAuth(_serverCertificate);

                var certificate = _serverCertificate;
                if (!certificate.HasPrivateKey)
                {
                    // SslStream historically has logic to deal with certificate missing private keys.
                    // By resolving the SslStreamCertificateContext eagerly, we circumvent this logic so
                    // try to resolve the certificate from the store if there's no private key in the cert.
                    certificate = LocateCertificateWithPrivateKey(certificate);
                }

                // This might be do blocking IO but it'll resolve the certificate chain up front before any connections are
                // made to the server
                _serverCertificateContext = SslStreamCertificateContext.Create(certificate, additionalCertificates: null);
            }

            var remoteCertificateValidationCallback = _options.ClientCertificateMode == ClientCertificateMode.NoCertificate ?
                                                      (RemoteCertificateValidationCallback?)null : RemoteCertificateValidationCallback;

            _sslStreamFactory = s => new SslStream(s, leaveInnerStreamOpen: false, userCertificateValidationCallback: remoteCertificateValidationCallback);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Attempt to decrypt the CMS using the specified "cert". If successful, return the ContentInfo that contains the decrypted content. If unsuccessful, return null and set "exception"
 /// to a valid Exception object. Do not throw the exception as EnvelopedCms will want to continue decryption attempts against other recipients. Only if all the recipients fail to
 /// decrypt will then EnvelopedCms throw the exception from the last failed attempt.
 /// </summary>
 public abstract ContentInfo?TryDecrypt(
     RecipientInfo recipientInfo,
     X509Certificate2?cert,
     AsymmetricAlgorithm?privateKey,
     X509Certificate2Collection originatorCerts,
     X509Certificate2Collection extraStore,
     out Exception?exception);
Ejemplo n.º 14
0
        internal SocketClient(ClientConfigurationData conf, DnsEndPoint server, string hostName, ILoggingAdapter logger)
        {
            _server = server;
            if (conf.ClientCertificates != null)
            {
                _clientCertificates = conf.ClientCertificates;
            }

            if (conf.Authentication is AuthenticationTls tls)
            {
                _clientCertificates = tls.AuthData.TlsCertificates;
            }

            if (conf.TrustedCertificateAuthority != null)
            {
                _trustedCertificateAuthority = conf.TrustedCertificateAuthority;
            }

            _encrypt = conf.UseTls;

            _serviceUrl = conf.ServiceUrl;

            _clientConfiguration = conf;

            _logger = logger;

            _targetServerName = hostName;
            //_heartbeat.Start();

            //_connectonId = $"{_networkstream.}";
        }
Ejemplo n.º 15
0
        public async Task <Option <GrantedToken> > GetTokenByRefreshTokenGrantType(
            RefreshTokenGrantTypeParameter refreshTokenGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            // Read this RFC for more information
            if (string.IsNullOrWhiteSpace(refreshTokenGrantTypeParameter.RefreshToken))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(
                        Strings.MissingParameter,
                        StandardTokenRequestParameterNames.RefreshToken)
                });
            }

            return(await _getTokenByRefreshTokenGrantTypeAction.Execute(
                       refreshTokenGrantTypeParameter,
                       authenticationHeaderValue,
                       certificate,
                       issuerName,
                       cancellationToken).ConfigureAwait(false));
        }
    Task <X509Certificate2?> ITlsConnectionFeature.GetClientCertificateAsync(CancellationToken cancellationToken)
    {
        if (_clientCertTask != null)
        {
            return(_clientCertTask);
        }

        var tlsFeature = (ITlsConnectionFeature)this;
        var clientCert = tlsFeature.ClientCertificate; // Lazy initialized

        if (clientCert != null ||
            Server.Options.ClientCertificateMethod != ClientCertificateMethod.AllowRenegotation
            // Delayed client cert negotiation is not allowed on HTTP/2.
            || Request.ProtocolVersion >= HttpVersion.Version20)
        {
            return(_clientCertTask = Task.FromResult(clientCert));
        }

        return(_clientCertTask = GetCertificateAsync(cancellationToken));

        async Task <X509Certificate2?> GetCertificateAsync(CancellationToken cancellation)
        {
            return(_clientCert = await Request.GetClientCertificateAsync(cancellation));
        }
    }
Ejemplo n.º 17
0
        public async Task <Option <GrantedToken> > GetTokenByClientCredentialsGrantType(
            ClientCredentialsGrantTypeParameter clientCredentialsGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(clientCredentialsGrantTypeParameter.Scope))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(Strings.MissingParameter, StandardTokenRequestParameterNames.ScopeName)
                });
            }

            // 1. Authenticate the client
            var instruction = authenticationHeaderValue.GetAuthenticateInstruction(
                clientCredentialsGrantTypeParameter,
                certificate);
            var authResult = await _authenticateClient.Authenticate(instruction, issuerName, cancellationToken)
                             .ConfigureAwait(false);

            var client = authResult.Client;

            if (client == null)
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidClient,
                    Detail = authResult.ErrorMessage !
                });
Ejemplo n.º 18
0
        public X509Certificate2?GetCertificateByThumbprint(string thumbprint, bool refreshCache, StoreName storeName)
        {
            Validation.ThrowIfNullOrWhiteSpace(thumbprint, nameof(thumbprint));

            X509Certificate2?matchingCertificate = null;

            foreach (CertificateInformation info in LoadCertificates(storeName, refreshCache))
            {
                if (string.Equals(info.Certificate.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase))
                {
                    matchingCertificate = info.Certificate;
                    break;
                }
            }

            if (matchingCertificate == null)
            {
                m_logger.LogError(Tag.Create(), "Could not find certificate with {0} thumbprint.", thumbprint);
            }
            else
            {
                m_logger.LogDebug(Tag.Create(), "Found certificate with {0} thumbprint.", thumbprint);
            }

            return(matchingCertificate);
        }
Ejemplo n.º 19
0
        internal static SslPolicyErrors VerifyCertificateProperties(
            SafeDeleteContext securityContext,
            X509Chain chain,
            X509Certificate2?remoteCertificate,
            bool checkCertName,
            bool isServer,
            string?hostName)
        {
            if (remoteCertificate == null)
            {
                return(SslPolicyErrors.RemoteCertificateNotAvailable);
            }

            SslPolicyErrors errors = chain.Build(remoteCertificate)
                ? SslPolicyErrors.None
                : SslPolicyErrors.RemoteCertificateChainErrors;

            if (checkCertName)
            {
                System.Diagnostics.Debug.Assert(hostName != null);
                SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext;
                if (!Interop.AndroidCrypto.SSLStreamVerifyHostname(sslContext.SslContext, hostName !))
                {
                    errors |= SslPolicyErrors.RemoteCertificateNameMismatch;
                }
            }

            return(errors);
        }
Ejemplo n.º 20
0
        public SafeFreeSslCredentials(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy)
            : base(IntPtr.Zero, true)
        {
            Debug.Assert(
                certificate == null || certificate is X509Certificate2,
                "Only X509Certificate2 certificates are supported at this time");

            X509Certificate2?cert = (X509Certificate2?)certificate;

            if (cert != null)
            {
                Debug.Assert(cert.HasPrivateKey, "cert.HasPrivateKey");

                // Make a defensive copy of the certificate. In some async cases the
                // certificate can have been disposed before being provided to the handshake.
                //
                // This meshes with the Unix (OpenSSL) PAL, because it extracts the private key
                // and cert handle (which get up-reffed) to match the API expectations.
                cert = new X509Certificate2(cert);

                Debug.Assert(cert.HasPrivateKey, "cert clone.HasPrivateKey");
            }

            Certificate = cert;
            Protocols   = protocols;
            Policy      = policy;
        }
Ejemplo n.º 21
0
        public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Certificate cert)
        {
            _socket = sock;
            _epl    = epl;
            _secure = secure;
            _cert   = cert;
            if (secure == false)
            {
                _stream = new NetworkStream(sock, false);
            }
            else
            {
#pragma warning disable CA5359
                _sslStream = HttpListener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) =>
                {
                    if (c == null)
                    {
                        return(true);
                    }

                    _clientCert       = c as X509Certificate2 ?? new X509Certificate2(c.GetRawCertData());
                    _clientCertErrors = new int[] { (int)e };
                    return(true);
                });
#pragma warning restore CA5359

                _stream = _sslStream;
            }

            _timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
            _sslStream?.AuthenticateAsServer(_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
            Init();
        }
Ejemplo n.º 22
0
        public void GetCertificateByThumbprint_ReturnsCerts()
        {
            StoreName        storeName = StoreName.CertificateAuthority;
            X509Certificate2 expected  = CreateCert("someName");

            (ICertificateReader reader, Action <Times, string> verify) = CreateReader(
                storeName,
                CreateCert("dummyCert"),
                expected,
                CreateCert("anotherDummyCert")
                );

            X509Certificate2?actual = reader.GetCertificateByThumbprint(expected.Thumbprint, storeName: storeName);

            X509Certificate2?actualFirstCall = reader.GetCertificateByThumbprint(expected.Thumbprint, storeName: storeName);

            Assert.AreEqual(expected, actualFirstCall, "Fist call to GetCertificateByThumbprint returned wrong data");
            verify(Times.Once(), "Certificate store should be called once to get certificates");

            X509Certificate2?actualSecondCall = reader.GetCertificateByThumbprint(expected.Thumbprint, storeName: storeName);

            Assert.AreEqual(expected, actualFirstCall, "Second call to GetCertificateByThumbprint returned wrong data");
            verify(Times.Never(), "Certificate store should not be called when certificates taken from cache");

            X509Certificate2?actualNoCacheCall = reader.GetCertificateByThumbprint(expected.Thumbprint, refreshCache: true, storeName: storeName);

            Assert.AreEqual(expected, actualFirstCall, "Call of GetCertificateByThumbprint (without cache) returned wrong data");
            verify(Times.Once(), "Certificate store should when cache not used");

            X509Certificate2?missingCert = reader.GetCertificateByThumbprint(expected.Thumbprint + "9", storeName: storeName);

            Assert.IsNull(missingCert, "GetCertificateByThumbprint should return null when certificate not found");
        }
Ejemplo n.º 23
0
 /// <summary>
 ///     Makes the certificate internal.
 /// </summary>
 /// <param name="subject">The s subject cn.</param>
 /// <param name="switchToMtaIfNeeded">if set to <c>true</c> [switch to MTA if needed].</param>
 /// <param name="signingCert">The signing cert.</param>
 /// <returns>X509Certificate2.</returns>
 private X509Certificate2 makeCertificateInternal(string subject,
                                                  bool switchToMtaIfNeeded, X509Certificate2?signingCert = null)
 {
     return(makeCertificateInternal(subject, $"CN={subject}",
                                    DateTime.UtcNow.AddDays(-certificateGraceDays), DateTime.UtcNow.AddDays(certificateValidDays),
                                    signingCert));
 }
Ejemplo n.º 24
0
        public async Task <Option <GrantedToken> > GetTokenByTicketId(
            GetTokenViaTicketIdParameter parameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(parameter.Ticket))
            {
                _logger.LogError("Ticket is null or empty");
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(Strings.MissingParameter, UmaConstants.RptClaims.Ticket)
                });
            }

            var instruction = authenticationHeaderValue.GetAuthenticateInstruction(parameter, certificate);
            var authResult  = await _authenticateClient.Authenticate(instruction, issuerName, cancellationToken)
                              .ConfigureAwait(false);

            var client = authResult.Client;

            if (client == null)
            {
                _logger.LogError("Client not found.");
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidClient,
                    Detail = authResult.ErrorMessage !
                });
        protected override async Task <StreamPair> CreateWrappedConnectedStreamsAsync(StreamPair wrapped, bool leaveOpen = false)
        {
            X509Certificate2?cert = Test.Common.Configuration.Certificates.GetServerCertificate();
            var ssl1 = new SslStream(wrapped.Stream1, leaveOpen, delegate { return(true); });
            var ssl2 = new SslStream(wrapped.Stream2, leaveOpen, delegate { return(true); });

            await new[]
            {
                ssl1.AuthenticateAsClientAsync(cert.GetNameInfo(X509NameType.SimpleName, false), null, GetSslProtocols(), false),
                ssl2.AuthenticateAsServerAsync(cert, false, GetSslProtocols(), false)
            }.WhenAllOrAnyFailed().ConfigureAwait(false);

            if (GetSslProtocols() == SslProtocols.Tls13)
            {
                // TLS 1.3 can generate some extra messages and we may get reset if test sends unidirectional traffic
                // and extra packet stays in socket buffer.

                // This ping-ping should flush leftovers from the handshake.
                // We use sync method to preserve socket in default blocking state
                // (as we don't go back once Async is used at least once)
                ssl1.Write(new byte[1]);
                ssl2.Write(new byte[1]);
                Assert.Equal(1, ssl2.Read(new byte[1]));
                Assert.Equal(1, ssl1.Read(new byte[1]));
            }

            return(new StreamPair(ssl1, ssl2));
        }
Ejemplo n.º 26
0
 private PixivProxyServer(X509Certificate2 certificate, TcpListener tcpListener)
 {
     _certificate = certificate;
     _tcpListener = tcpListener;
     _tcpListener.Start();
     _tcpListener.BeginAcceptTcpClient(AcceptTcpClientCallback, _tcpListener);
 }
Ejemplo n.º 27
0
        public bool VerifySignatureForHash(
            ReadOnlySpan <byte> hash,
            Oid hashAlgorithmId,
            [NotNullWhen(true)] out X509Certificate2?signerCertificate,
            X509Certificate2Collection?extraCandidates = null)
        {
            if (hashAlgorithmId == null)
            {
                throw new ArgumentNullException(nameof(hashAlgorithmId));
            }

            signerCertificate = null;

            X509Certificate2?cert = GetSignerCertificate(extraCandidates);

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

            if (VerifyHash(hash, hashAlgorithmId.Value))
            {
                // REVIEW: Should this return the cert, or new X509Certificate2(cert.RawData)?
                // SignedCms.SignerInfos builds new objects each call, which makes
                // ReferenceEquals(cms.SignerInfos[0].Certificate, cms.SignerInfos[0].Certificate) be false.
                // So maybe it's weird to give back a cert we've copied from that?
                signerCertificate = cert;
                return(true);
            }

            return(false);
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Creates SecureMailAddress object instance
 /// </summary>
 /// <param name="address">Email address</param>
 /// <param name="displayName">Email owner display name</param>
 /// <param name="encryptionCertificate">Certificate used for email encryption</param>
 /// <param name="signingCertificate">Certificate used for email signing</param>
 public SecureMailAddress(string address, string displayName,
                          X509Certificate2?encryptionCertificate = null, X509Certificate2?signingCertificate = null)
     : base(address, displayName)
 {
     EncryptionCertificate = encryptionCertificate;
     SigningCertificate    = signingCertificate;
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Load certificate from disk
        /// </summary>
        /// <param name="fi"></param>
        /// <returns></returns>
        private X509Certificate2?LoadCertificate(FileInfo fi)
        {
            X509Certificate2?cert = null;

            if (!fi.Exists)
            {
                return(cert);
            }
            try
            {
                cert = new X509Certificate2(fi.FullName, _password);
            }
            catch (CryptographicException)
            {
                try
                {
                    cert = new X509Certificate2(fi.FullName, "");
                }
                catch
                {
                    _log.Warning("Unable to scan certificate {name}", fi.FullName);
                }
            }
            return(cert);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Gets the result of the <see cref="HttpRequestMessage"/>.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type"/> of data downloaded.</typeparam>
        /// <param name="request">The download request.</param>
        /// <param name="token">The authorization token for the request.</param>
        /// <param name="certificate">The <see cref="X509Certificate2"/> to include in request.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the async operation.</param>
        /// <returns></returns>
        protected async Task <Option <T> > GetResult <T>(
            HttpRequestMessage request,
            AuthenticationHeaderValue?token,
            X509Certificate2?certificate        = null,
            CancellationToken cancellationToken = default)
            where T : class
        {
            request = PrepareRequest(request, token, certificate);
            var result = await _client().SendAsync(request, cancellationToken).ConfigureAwait(false);

#if NET5_0
            var content = await result.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
#else
            var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
#endif
            if (result.IsSuccessStatusCode && result.StatusCode != HttpStatusCode.NoContent)
            {
                return(Serializer.Default.Deserialize <T>(content) !);
            }

            var genericResult = string.IsNullOrWhiteSpace(content)
                ? new ErrorDetails {
                Status = result.StatusCode
            }
                : Serializer.Default.Deserialize <ErrorDetails>(content);

            return(genericResult !);
        }