Inheritance: System.Collections.CollectionBase
Ejemplo n.º 1
0
		private void ConfigureCertificates()
		{
			_certificate = _appleSettings.Certificate;

			_certificates = new X509CertificateCollection();

			if (_appleSettings.AddLocalAndMachineCertificateStores)
			{
				var store = new X509Store(StoreLocation.LocalMachine);
				_certificates.AddRange(store.Certificates);

				store = new X509Store(StoreLocation.CurrentUser);
				_certificates.AddRange(store.Certificates);
			}

			_certificates.Add(_certificate);

			if (_appleSettings.AdditionalCertificates != null)
			{
				foreach (var additionalCertificate in _appleSettings.AdditionalCertificates)
				{
					_certificates.Add(additionalCertificate);
				}
			}
		}
                public HttpsClientStream (Stream stream, X509CertificateCollection clientCertificates,
					HttpWebRequest request, byte [] buffer)
                        : base (stream, request.RequestUri.Host, false, (Mono.Security.Protocol.Tls.SecurityProtocolType)
				ServicePointManager.SecurityProtocol, clientCertificates)
                {
                        // this constructor permit access to the WebRequest to call
                        // ICertificatePolicy.CheckValidationResult
                        _request = request;
			_status = 0;
			if (buffer != null)
				InputBuffer.Write (buffer, 0, buffer.Length);
#if !NET_1_0
                        // also saved from reflection
                        base.CheckCertRevocationStatus = ServicePointManager.CheckCertificateRevocationList;
#endif
#if NET_2_0
			ClientCertSelection += delegate (X509CertificateCollection clientCerts, X509Certificate serverCertificate,
				string targetHost, X509CertificateCollection serverRequestedCertificates) {
				return ((clientCerts == null) || (clientCerts.Count == 0)) ? null : clientCerts [0];
			};
			PrivateKeySelection += delegate (X509Certificate certificate, string targetHost) {
				X509Certificate2 cert = (certificate as X509Certificate2);
				return (cert == null) ? null : cert.PrivateKey;
			};
#endif
               }
 internal SecureChannel(string hostname, bool serverMode, SchProtocols protocolFlags, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
 {
     if (Logging.On)
     {
         Logging.PrintInfo(Logging.Web, this, ".ctor", string.Concat(new object[] { "hostname=", hostname, ", #clientCertificates=", (clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo), ", encryptionPolicy=", encryptionPolicy }));
     }
     SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, "Microsoft Unified Security Protocol Provider", true);
     if (ComNetOS.IsWin9x && (clientCertificates.Count > 0))
     {
         this.m_Destination = hostname + "+" + clientCertificates.GetHashCode();
     }
     else
     {
         this.m_Destination = hostname;
     }
     this.m_HostName = hostname;
     this.m_ServerMode = serverMode;
     if (serverMode)
     {
         this.m_ProtocolFlags = protocolFlags & SchProtocols.ServerMask;
     }
     else
     {
         this.m_ProtocolFlags = protocolFlags & SchProtocols.ClientMask;
     }
     this.m_ServerCertificate = serverCertificate;
     this.m_ClientCertificates = clientCertificates;
     this.m_RemoteCertRequired = remoteCertRequired;
     this.m_SecurityContext = null;
     this.m_CheckCertRevocation = checkCertRevocationStatus;
     this.m_CheckCertName = checkCertName;
     this.m_CertSelectionDelegate = certSelectionDelegate;
     this.m_RefreshCredentialNeeded = true;
     this.m_EncryptionPolicy = encryptionPolicy;
 }
Ejemplo n.º 4
0
        internal SecureChannel(string hostname, bool serverMode, SslProtocols sslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName,
                                                  bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
        {
            GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::.ctor", "hostname:" + hostname + " #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
            if (Logging.On)
            { 
                Logging.PrintInfo(Logging.Web, this, ".ctor", "hostname=" + hostname + ", #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)) + ", encryptionPolicy=" + encryptionPolicy);
            }
          
            SSPIWrapper.VerifyPackageInfo(GlobalSSPI.SSPISecureChannel);

            _destination = hostname;

            GlobalLog.Assert(hostname != null, "SecureChannel#{0}::.ctor()|hostname == null", Logging.HashString(this));
            _hostName = hostname;
            _serverMode = serverMode;

            _sslProtocols = sslProtocols;

            _serverCertificate = serverCertificate;
            _clientCertificates = clientCertificates;
            _remoteCertRequired = remoteCertRequired;
            _securityContext = null;
            _checkCertRevocation = checkCertRevocationStatus;
            _checkCertName = checkCertName;
            _certSelectionDelegate = certSelectionDelegate;
            _refreshCredentialNeeded = true;
            _encryptionPolicy = encryptionPolicy;
            GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::.ctor");
        }
 public LocalCertificationSelectionInfo(string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssures)
 {
     this.target = targetHost;
     this.localCerts = localCertificates;
     this.remoteCert = remoteCertificate;
     this.accIssures = acceptableIssures;
 }
Ejemplo n.º 6
0
        static bool BuildX509Chain(XX509CertificateCollection certs, X509Chain chain, ref SslPolicyErrors errors, ref int status11)
        {
#if MOBILE
            return(false);
#else
            if (is_macosx)
            {
                return(false);
            }

            var leaf = (X509Certificate2)certs [0];

            bool ok;
            try {
                ok = chain.Build(leaf);
                if (!ok)
                {
                    errors |= GetErrorsFromChain(chain);
                }
            } catch (Exception e) {
                Console.Error.WriteLine("ERROR building certificate chain: {0}", e);
                Console.Error.WriteLine("Please, report this problem to the Mono team");
                errors |= SslPolicyErrors.RemoteCertificateChainErrors;
                ok      = false;
            }

            try {
                status11 = GetStatusFromChain(chain);
            } catch {
                status11 = -2146762485;                 // TRUST_E_FAIL - generic
            }

            return(ok);
#endif
        }
        public AsyncWebSocketClientConfiguration()
        {
            InitialBufferAllocationCount = 4;
            ReceiveBufferSize = 8192;
            SendBufferSize = 8192;
            ReceiveTimeout = TimeSpan.Zero;
            SendTimeout = TimeSpan.Zero;
            NoDelay = true;
            LingerState = new LingerOption(false, 0); // The socket will linger for x seconds after Socket.Close is called.

            SslTargetHost = null;
            SslClientCertificates = new X509CertificateCollection();
            SslEncryptionPolicy = EncryptionPolicy.RequireEncryption;
            SslEnabledProtocols = SslProtocols.Ssl3 | SslProtocols.Tls;
            SslCheckCertificateRevocation = false;
            SslPolicyErrorsBypassed = false;

            ConnectTimeout = TimeSpan.FromSeconds(10);
            CloseTimeout = TimeSpan.FromSeconds(5);
            KeepAliveInterval = TimeSpan.FromSeconds(30);
            KeepAliveTimeout = TimeSpan.FromSeconds(5);
            ReasonableFragmentSize = 4096;

            EnabledExtensions = new Dictionary<string, IWebSocketExtensionNegotiator>()
            {
                { PerMessageCompressionExtension.RegisteredToken, new PerMessageCompressionExtensionNegotiator() },
            };
            EnabledSubProtocols = new Dictionary<string, IWebSocketSubProtocolNegotiator>();

            OfferedExtensions = new List<WebSocketExtensionOfferDescription>()
            {
                new WebSocketExtensionOfferDescription(PerMessageCompressionExtension.RegisteredToken),
            };
            RequestedSubProtocols = new List<WebSocketSubProtocolRequestDescription>();
        }
Ejemplo n.º 8
0
        static bool CheckUsage(XX509CertificateCollection certs, string host, ref SslPolicyErrors errors, ref int status11)
        {
#if !MONOTOUCH
            var leaf = certs[0] as X509Certificate2;
            if (leaf == null)
            {
                leaf = new X509Certificate2(certs[0]);
            }
            // for OSX and iOS we're using the native API to check for the SSL server policy and host names
            if (!is_macosx)
            {
                if (!CheckCertificateUsage(leaf))
                {
                    errors  |= SslPolicyErrors.RemoteCertificateChainErrors;
                    status11 = -2146762490;                     //CERT_E_PURPOSE 0x800B0106
                    return(false);
                }

                if (!string.IsNullOrEmpty(host) && !CheckServerIdentity(leaf, host))
                {
                    errors  |= SslPolicyErrors.RemoteCertificateNameMismatch;
                    status11 = -2146762481;                     // CERT_E_CN_NO_MATCH 0x800B010F
                    return(false);
                }
            }
#endif
            return(true);
        }
Ejemplo n.º 9
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
            : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                    certificates.Add(addlCert);

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
Ejemplo n.º 10
0
        //
        // This version of an Ssl Stream is for internal HttpWebrequest use.
        // This Ssl client owns the underlined socket
        // The TlsStream will own secured read/write and disposal of the passed "networkStream" stream.
        //
        public TlsStream(string destinationHost, NetworkStream networkStream, X509CertificateCollection clientCertificates, ServicePoint servicePoint, object initiatingRequest, ExecutionContext executionContext)
               :base(networkStream, true) {

        // WebRequest manages the execution context manually so we have to ensure we get one for SSL client certificate demand
        _ExecutionContext = executionContext;
        if (_ExecutionContext == null)
        {
            _ExecutionContext = ExecutionContext.Capture();
        }

        // 


         GlobalLog.Enter("TlsStream::TlsStream", "host="+destinationHost+", #certs="+((clientCertificates == null) ? "none" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
         if (Logging.On) Logging.PrintInfo(Logging.Web, this, ".ctor", "host="+destinationHost+", #certs="+((clientCertificates == null) ? "null" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));

         m_ExceptionStatus = WebExceptionStatus.SecureChannelFailure;
         m_Worker = new SslState(networkStream, initiatingRequest is HttpWebRequest, SettingsSectionInternal.Section.EncryptionPolicy);

         m_DestinationHost = destinationHost;
         m_ClientCertificates = clientCertificates;

         RemoteCertValidationCallback certValidationCallback = servicePoint.SetupHandshakeDoneProcedure(this, initiatingRequest);
         m_Worker.SetCertValidationDelegate(certValidationCallback);

         // The Handshake is NOT done at this point
         GlobalLog.Leave("TlsStream::TlsStream (Handshake is not done)");
        }
Ejemplo n.º 11
0
 public ValidationResult ValidateCertificate(string host, bool serverMode, XX509CertificateCollection certs)
 {
     try {
         X509Certificate leaf;
         if (certs != null && certs.Count != 0)
         {
             leaf = certs [0];
         }
         else
         {
             leaf = null;
         }
         var result = ValidateChain(host, serverMode, leaf, null, certs, 0);
         if (tlsStream != null)
         {
             tlsStream.CertificateValidationFailed = result == null || !result.Trusted || result.UserDenied;
         }
         return(result);
     } catch {
         if (tlsStream != null)
         {
             tlsStream.CertificateValidationFailed = true;
         }
         throw;
     }
 }
Ejemplo n.º 12
0
        public GcmXmppConnection (GcmXmppConfiguration configuration)
        {
            authCompletion = new TaskCompletionSource<bool> ();

            notifications = new Dictionary<string,CompletableNotification> ();
            Configuration = configuration;

            certificates = new X509CertificateCollection ();

            // Add local/machine certificate stores to our collection if requested
            //if (Configuration.AddLocalAndMachineCertificateStores) {
                var store = new X509Store (StoreLocation.LocalMachine);
                certificates.AddRange (store.Certificates);

                store = new X509Store (StoreLocation.CurrentUser);
                certificates.AddRange (store.Certificates);
            //}

            // Add optionally specified additional certs into our collection
//            if (Configuration.AdditionalCertificates != null) {
//                foreach (var addlCert in Configuration.AdditionalCertificates)
//                    certificates.Add (addlCert);
//            }

            // Finally, add the main private cert for authenticating to our collection
//            if (certificate != null)
//                certificates.Add (certificate);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initializes the dialog box.
        /// </summary>
        /// <param name="eventArgs">Event arguments.</param>
        protected override void OnLoad(EventArgs eventArgs)
        {
            // Call the base class to inherit any initialization.
            base.OnLoad(eventArgs);

            // Load up the certificates from the personal certificate store.
            this.x509CertificateCollection = Crypt.GetCertificateStore(myCertificateStoreName);

            // Parse the friendly name out of the different tags in the certificate name and place them
            // in the list box.
            foreach (X509Certificate x509Certificate in this.x509CertificateCollection)
            {
                Regex regex = new Regex("CN=(?<friendlyName>[^,]+)");

                MatchCollection matches = regex.Matches(x509Certificate.Subject);
                foreach (Match match in matches)
                {
                    if (match.Groups["friendlyName"].Value != "Users")
                    {
                        this.listBoxCertificates.Items.Add(match.Groups["friendlyName"].Value);
                        break;
                    }
                }
            }
        }
        protected HandshakeSession(SecurityParameters securityParameters, ILogger logger)
        {
            this.logger = logger;

            _pluginManager = new CipherSuitePluginManager(this.logger);
            _state = HandshakeState.Initial;

            _minVersion = securityParameters.MinimumVersion;
            _maxVersion = securityParameters.MaximumVersion;
            _supportedCipherSuites = securityParameters.CipherSuiteIDs.ToArray();
            _supportedCompressions = securityParameters.CompressionIDs.ToArray();

            _availableCertificates = new List<X509CertificateCollection>(securityParameters.AvailableCertificates);
            _availablePrivateKeys = new List<CertificatePrivateKey>(securityParameters.AvailablePrivateKeys);

            _clientCertificates = new X509CertificateCollection();
            _serverCertificates = new X509CertificateCollection();

            // Initialize the default ClientHello version, to
            // be as compatible as possible based on maxVersion
            _version = _minVersion;

            
            _cipherSuite = new CipherSuite(_version);
        }
Ejemplo n.º 15
0
        static byte[] InternalSslSocketHttp(IPEndPoint endpoint, HttpArgs args, HttpMethod method, X509CertificateCollection certificates)
        {
            using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                try
                {
                    client.Connect(endpoint);
                    if (client.Connected)
                    {
                        using (SslStream stream = new SslStream(new NetworkStream(client), false, ValidateServerCertificate, null))
                        {
                            stream.AuthenticateAsClient("ServerName", certificates, SslProtocols.Tls, false);
                            if (stream.IsAuthenticated)
                            {
                                //生成协议包
                                byte[] buff = HttpClient.ParseHttpArgs(method, args);
                                stream.Write(buff, 0, buff.Length);
                                stream.Flush();
                                return ParseSslResponse(endpoint, stream, args, certificates);

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return null;
        }
Ejemplo n.º 16
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            cancelToken = cancelTokenSrc.Token;

            appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                    certificates.Add(addlCert);

            timerCleanup = new Timer(state => Cleanup(), null, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));
        }
 public async Task<Stream> ConnectAsync(string host, int port, X509Certificate clientCert, CancellationToken cancel)
 {
     Stream lowerStream = null;
     SslStream sslStream = null;
     X509CertificateCollection certCollection = null;;
     if (clientCert != null)
     {
         certCollection = new X509CertificateCollection(new[] { clientCert });
     }
     try
     {
         lowerStream = await _connectionResolver.ConnectAsync(host, port, cancel);
         sslStream = new SslStream(lowerStream);
         await sslStream.AuthenticateAsClientAsync(host, certCollection, _protocols, checkCertificateRevocation: true);
         return sslStream;
     }
     catch (Exception)
     {
         if (sslStream != null)
         {
             sslStream.Dispose();
         }
         if (lowerStream != null)
         {
             lowerStream.Dispose();
         }
         throw;
     }
 }
        /// <summary>
        /// Build a new SSL steam.
        /// </summary>
        /// <param name="channel">Channel which will use the stream</param>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream which is ready to be used (must have been validated)</returns>
        public SslStream Build(ITcpChannel channel, Socket socket)
        {
            var ns = new NetworkStream(socket);
            var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);

            try
            {
                X509CertificateCollection certificates = null;
                if (Certificate != null)
                {
                    certificates = new X509CertificateCollection(new[] { Certificate });
                }

                stream.AuthenticateAsClient(CommonName, certificates, Protocols, false);
            }
            catch (IOException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }
            catch (ObjectDisposedException err)
            {
                throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
            }
            catch (AuthenticationException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }

            return stream;
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Creates a new SSL filter to a server.
 /// </summary>
 /// <param name="targetHost">the name of the server that shares this SSL connection</param>
 /// <param name="clientCertificates">the <see cref="X509CertificateCollection"/> containing client certificates</param>
 public SslFilter(String targetHost, X509CertificateCollection clientCertificates)
 {
     TargetHost = targetHost;
     ClientCertificates = clientCertificates;
     UseClientMode = true;
     CheckCertificateRevocation = false;
 }
Ejemplo n.º 20
0
            public X509CertificateEnumerator(X509CertificateCollection mappings)
            {
                if (mappings == null)
                    throw new ArgumentNullException(nameof(mappings));

                _enumerator = ((IEnumerable)mappings).GetEnumerator();
            }
Ejemplo n.º 21
0
        internal SecureChannel(string hostname, bool serverMode, SchProtocols protocolFlags, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName, 
                                                  bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
        {
            GlobalLog.Enter("SecureChannel#" + ValidationHelper.HashString(this) + "::.ctor", "hostname:" + hostname + " #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
            if (Logging.On) Logging.PrintInfo(Logging.Web, this, ".ctor", "hostname=" + hostname + ", #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)) + ", encryptionPolicy=" + encryptionPolicy);
            SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true);

            m_Destination = hostname;

            GlobalLog.Assert(hostname != null, "SecureChannel#{0}::.ctor()|hostname == null", ValidationHelper.HashString(this));
            m_HostName = hostname;
            m_ServerMode = serverMode;

            if (serverMode)
                m_ProtocolFlags = (protocolFlags & SchProtocols.ServerMask);
            else
                m_ProtocolFlags = (protocolFlags & SchProtocols.ClientMask);

            m_ServerCertificate = serverCertificate;
            m_ClientCertificates = clientCertificates;
            m_RemoteCertRequired = remoteCertRequired;
            m_SecurityContext = null;
            m_CheckCertRevocation = checkCertRevocationStatus;
            m_CheckCertName = checkCertName;
            m_CertSelectionDelegate = certSelectionDelegate;
            m_RefreshCredentialNeeded = true;
            m_EncryptionPolicy = encryptionPolicy;
            GlobalLog.Leave("SecureChannel#" + ValidationHelper.HashString(this) + "::.ctor");
        }
Ejemplo n.º 22
0
 // Establishes SSL connection iff ssl is not null.
 public TcpConnection(string host, int port, SslOptions ssl)
 {
     _log.Info("Connecting to {0}:{1}...", host, port);
     _client = new TcpClient(host, port);
     if (ssl == null)
     {
         _strm = _client.GetStream();
     }
     else
     {
         try
         {
             RemoteCertificateValidationCallback cb =
                 (object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) =>
             {
                 if (errors == SslPolicyErrors.None)
                     return true;
                 if (errors != SslPolicyErrors.RemoteCertificateChainErrors)
                 {
                     _log.Error("SSL handshake error: {0}", errors);
                     return ssl.AllowAllErrors;
                 }
                 foreach (X509ChainStatus ch in chain.ChainStatus)
                 {
                     if (ch.Status == X509ChainStatusFlags.NotTimeValid && ssl.AllowExpiredCertificate)
                     {
                         _log.Warn("Ignoring NotTimeValid error in SSL handshake.");
                         continue;
                     }
                     if (ch.Status == X509ChainStatusFlags.PartialChain)
                     {
                         _log.Warn("Ignoring PartialChain error in SSL handshake.");
                         continue;
                     }
                     _log.Error("SSL handshake error: {0} {1}", ch.Status, ch.StatusInformation);
                     return ssl.AllowAllErrors;
                 }
                 return true;
             };
             var sslStrm = new SslStream(_client.GetStream(), leaveInnerStreamOpen: false,
                                         userCertificateValidationCallback: cb);
             var certs = new X509CertificateCollection();
             if (ssl.CertificateFilename != null)
                 certs.Add(new X509Certificate(ssl.CertificateFilename, ssl.CertificateFilePassword));
             sslStrm.AuthenticateAsClient(ssl.CertificateName ?? host, certs,
                                          System.Security.Authentication.SslProtocols.Default,
                                          checkCertificateRevocation: false);
             _strm = sslStrm;
         }
         catch
         {
             Dispose();
             throw;
         }
     }
     var protocols = new Dictionary<string, Mantle.IMessageFactory>() {
         { Mantle.Fix44.Protocol.Value, new Mantle.Fix44.MessageFactory() }
     };
     _receiver = new Mantle.Receiver(_strm, 1 << 20, protocols);
 }
Ejemplo n.º 23
0
		static bool BuildX509Chain (XX509CertificateCollection certs, X509Chain chain, ref SslPolicyErrors errors, ref int status11)
		{
#if MOBILE
			return false;
#else
			if (is_macosx)
				return false;

			var leaf = (X509Certificate2)certs [0];

			bool ok;
			try {
				ok = chain.Build (leaf);
				if (!ok)
					errors |= GetErrorsFromChain (chain);
			} catch (Exception e) {
				Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
				Console.Error.WriteLine ("Please, report this problem to the Mono team");
				errors |= SslPolicyErrors.RemoteCertificateChainErrors;
				ok = false;
			}

			try {
				status11 = GetStatusFromChain (chain);
			} catch {
				status11 = -2146762485; // TRUST_E_FAIL - generic
			}

			return ok;
#endif
		}
Ejemplo n.º 24
0
 public Http2ConnectionSettings (string host, uint port = 80, bool useTls = false, X509CertificateCollection certificates = null)
 {
     Host = host;
     Port = port;
     UseTls = useTls;
     Certificates = certificates;
 }
Ejemplo n.º 25
0
    public PushNotification(bool useSandbox, string p12File, string p12FilePassword)
    {
      if (useSandbox)
      {
        _host = SandboxHost;
        _feedbackHost = SandboxFeedbackHost;
      }
      else
      {
        _host = ProductionHost;
        _feedbackHost = ProductionFeedbackHost;
      }

      //Load Certificates in to collection.
      _certificate = string.IsNullOrEmpty(p12FilePassword)? new X509Certificate2(File.ReadAllBytes(p12File)): new X509Certificate2(File.ReadAllBytes(p12File), p12FilePassword);
      _certificates = new X509CertificateCollection {_certificate};
      
      // Loading Apple error response list.
      _errorList.Add(0, "No errors encountered");
      _errorList.Add(1, "Processing error");
      _errorList.Add(2, "Missing device token");
      _errorList.Add(3, "Missing topic");
      _errorList.Add(4, "Missing payload");
      _errorList.Add(5, "Invalid token size");
      _errorList.Add(6, "Invalid topic size");
      _errorList.Add(7, "Invalid payload size");
      _errorList.Add(8, "Invalid token");
      _errorList.Add(255, "None (unknown)");
    }
 public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
 {
     this._SslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation);
     LazyAsyncResult lazyResult = new LazyAsyncResult(this._SslState, asyncState, asyncCallback);
     this._SslState.ProcessAuthentication(lazyResult);
     return lazyResult;
 }
Ejemplo n.º 27
0
        public HttpsClientStream(Stream stream, SNCX.X509CertificateCollection clientCertificates,
                                 HttpWebRequest request, byte[] buffer)
            : base(stream, request.Address.Host, false, (SecurityProtocolType)
                   ServicePointManager.SecurityProtocol, clientCertificates)
        {
            // this constructor permit access to the WebRequest to call
            // ICertificatePolicy.CheckValidationResult
            _request = request;
            _status  = 0;
            if (buffer != null)
            {
                InputBuffer.Write(buffer, 0, buffer.Length);
            }
            // also saved from reflection
            CheckCertRevocationStatus = ServicePointManager.CheckCertificateRevocationList;

            ClientCertSelection += delegate(SNCX.X509CertificateCollection clientCerts,
                                            SNCX.X509Certificate serverCertificate,
                                            string targetHost, SNCX.X509CertificateCollection serverRequestedCertificates)
            {
                return(clientCerts == null || clientCerts.Count == 0 ? null : clientCerts[0]);
            };
            PrivateKeySelection += delegate(SNCX.X509Certificate certificate, string targetHost)
            {
                var cert = certificate as SNCX.X509Certificate2;
                return(cert == null ? null : cert.PrivateKey);
            };
        }
Ejemplo n.º 28
0
        internal SecureChannel(string hostname, bool serverMode, SslProtocols sslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName,
                                                  bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this, hostname, clientCertificates);
                NetEventSource.Log.SecureChannelCtor(this, hostname, clientCertificates, encryptionPolicy);
            }

            SslStreamPal.VerifyPackageInfo();

            _destination = hostname;

            if (hostname == null)
            {
                NetEventSource.Fail(this, "hostname == null");
            }
            _hostName = hostname;
            _serverMode = serverMode;

            _sslProtocols = sslProtocols;

            _serverCertificate = serverCertificate;
            _clientCertificates = clientCertificates;
            _remoteCertRequired = remoteCertRequired;
            _securityContext = null;
            _checkCertRevocation = checkCertRevocationStatus;
            _checkCertName = checkCertName;
            _certSelectionDelegate = certSelectionDelegate;
            _refreshCredentialNeeded = true;
            _encryptionPolicy = encryptionPolicy;
            
            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }
 public void AddRange(X509CertificateCollection value) {
     if (value == null) {
         throw new ArgumentNullException("value");
     }
     for (int i = 0; (i < value.Count); i = (i + 1)) {
         this.Add(value[i]);
     }
 }
Ejemplo n.º 30
0
	public void AddRange (X509CertificateCollection value)
	{
		if (value == null)
			throw new ArgumentNullException ("value");

		for (int i = 0; i < value.InnerList.Count; i++) 
			InnerList.Add (value [i]);
	}
Ejemplo n.º 31
0
        public CanGetSetClientCertificates()
        {
            _x509Certificate = new X509Certificate();
            _x509CertificateCollection = new X509CertificateCollection(){ _x509Certificate };

            Client.ClientCertificates.ShouldBeNull();
            Client.ClientCertificates = _x509CertificateCollection;
        }
		protected HttpWebClientProtocol () 
		{
			allowAutoRedirect = false;
			clientCertificates = null;
			cookieContainer = null;
			proxy = null; // FIXME
			userAgent = String.Format ("Mono Web Services Client Protocol {0}", Environment.Version);
		}
Ejemplo n.º 33
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="hostname">Hostname to connect to.</param>
 /// <param name="port">Port</param>
 public SimpleMLLPClient(string hostname, int port)
 {
     serverHostname = hostname;
     cCollection = new X509CertificateCollection();
     tcpClient = new TcpClient(hostname, port);
     clientStream = tcpClient.GetStream();
     streamToUse = clientStream;
 }
Ejemplo n.º 34
0
		public override IMonoTlsContext CreateTlsContext (
			string hostname, bool serverMode, TlsProtocols protocolFlags,
			X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
			bool remoteCertRequired, MonoEncryptionPolicy encryptionPolicy,
			MonoTlsSettings settings)
		{
			throw new NotSupportedException ();
		}
Ejemplo n.º 35
0
 private X509CertificateCollection GetCertCollection()
 {
     X509CertificateCollection certCollection = new X509CertificateCollection();
     string certLocation = TestContext.GetValue("certLocation");
     X509Certificate cert = X509Certificate.CreateFromCertFile(certLocation);
     certCollection.Add(cert);
     return certCollection;
 }
Ejemplo n.º 36
0
        public bool InvokeSystemValidator(string targetHost, bool serverMode, XX509CertificateCollection certificates, XX509Chain xchain, ref MonoSslPolicyErrors xerrors, ref int status11)
        {
            X509Chain chain  = xchain;
            var       errors = (SslPolicyErrors)xerrors;
            var       result = SystemCertificateValidator.Evaluate(settings, targetHost, certificates, chain, ref errors, ref status11);

            xerrors = (MonoSslPolicyErrors)errors;
            return(result);
        }
Ejemplo n.º 37
0
 internal X509Certificate SelectClientCertificate(
     string targetHost, XX509CertificateCollection localCertificates, X509Certificate remoteCertificate,
     string[] acceptableIssuers)
 {
     if (certSelectionCallback == null)
     {
         return(null);
     }
     return(certSelectionCallback(targetHost, localCertificates, remoteCertificate, acceptableIssuers));
 }
Ejemplo n.º 38
0
        static bool EvaluateSystem(XX509CertificateCollection certs, XX509CertificateCollection anchors, string host, X509Chain chain, ref SslPolicyErrors errors, ref int status11)
        {
            var  leaf = certs [0];
            bool result;

#if MONODROID
            result = AndroidPlatform.TrustEvaluateSsl(certs);
            if (result)
            {
                // chain.Build() + GetErrorsFromChain() (above) will ALWAYS fail on
                // Android (there are no mozroots or preinstalled root certificates),
                // thus `errors` will ALWAYS have RemoteCertificateChainErrors.
                // Android just verified the chain; clear RemoteCertificateChainErrors.
                errors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
            }
#else
            if (is_macosx)
            {
                // Attempt to use OSX certificates
                // Ideally we should return the SecTrustResult
                OSX509Certificates.SecTrustResult trustResult = OSX509Certificates.SecTrustResult.Deny;
                try {
                    trustResult = OSX509Certificates.TrustEvaluateSsl(certs, anchors, host);
                    // We could use the other values of trustResult to pass this extra information
                    // to the .NET 2 callback for values like SecTrustResult.Confirm
                    result = (trustResult == OSX509Certificates.SecTrustResult.Proceed ||
                              trustResult == OSX509Certificates.SecTrustResult.Unspecified);
                } catch {
                    result  = false;
                    errors |= SslPolicyErrors.RemoteCertificateChainErrors;
                    // Ignore
                }

                if (result)
                {
                    // TrustEvaluateSsl was successful so there's no trust error
                    // IOW we discard our own chain (since we trust OSX one instead)
                    errors = 0;
                }
                else
                {
                    // callback and DefaultCertificatePolicy needs this since 'result' is not specified
                    status11 = (int)trustResult;
                    errors  |= SslPolicyErrors.RemoteCertificateChainErrors;
                }
            }
            else
            {
                result = BuildX509Chain(certs, chain, ref errors, ref status11);
            }
#endif

            return(result);
        }
Ejemplo n.º 39
0
        public static X509Chain CreateX509Chain(XX509CertificateCollection certs)
        {
            var chain = new X509Chain();

            chain.ChainPolicy = new X509ChainPolicy((X509CertificateCollection)(object)certs);

#if !MOBILE
            chain.ChainPolicy.RevocationMode = revocation_mode;
#endif

            return(chain);
        }
Ejemplo n.º 40
0
 public bool SelectClientCertificate(
     string targetHost, XX509CertificateCollection localCertificates, X509Certificate remoteCertificate,
     string[] acceptableIssuers, out X509Certificate clientCertificate)
 {
     if (certSelectionCallback == null)
     {
         clientCertificate = null;
         return(false);
     }
     clientCertificate = certSelectionCallback(targetHost, localCertificates, remoteCertificate, acceptableIssuers);
     return(true);
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Initialize the dialog box used to select certificates.
        /// </summary>
        public FormSelectCertificate()
        {
            // This is needed for the designer.
            InitializeComponent();

            // Place an image of the icon in the dialog (I've found no way to do this from the designer).
            this.label2.Image = SystemIcons.Exclamation.ToBitmap();

            // This collection contains the certificates in the 'My' certificate store.  When a selection is made from the
            // list box, the corresponding certificate in this selection is made available to the caller.
            this.x509CertificateCollection = new X509CertificateCollection();
        }
Ejemplo n.º 42
0
        internal override MSI.IMonoTlsContext CreateTlsContext(
            string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
            SSCX.X509Certificate serverCertificate, PSSCX.X509CertificateCollection clientCertificates,
            bool remoteCertRequired, MSI.MonoEncryptionPolicy encryptionPolicy,
            MSI.MonoTlsSettings settings)
        {
            var config = TlsProviderFactory.CreateTlsConfiguration(
                hostname, serverMode, protocolFlags, serverCertificate,
                remoteCertRequired, settings);

            return(new TlsContextWrapper(config, serverMode));
        }
Ejemplo n.º 43
0
        static X509Certificate DefaultSelectionCallback(string targetHost, XX509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
        {
            X509Certificate clientCertificate;

            if (localCertificates == null || localCertificates.Count == 0)
            {
                clientCertificate = null;
            }
            else
            {
                clientCertificate = localCertificates [0];
            }
            return(clientCertificate);
        }
Ejemplo n.º 44
0
        internal bool ValidateClientCertificate(X509Certificate certificate, MonoSslPolicyErrors errors)
        {
            var certs = new XX509CertificateCollection();

            certs.Add(new X509Certificate2(certificate.GetRawCertData()));

            var result = ValidateChain(string.Empty, true, certificate, null, certs, (SslPolicyErrors)errors);

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

            return(result.Trusted && !result.UserDenied);
        }
Ejemplo n.º 45
0
        public static X509Chain CreateX509Chain(XX509CertificateCollection certs)
        {
            var chain = new X509Chain();

            chain.ChainPolicy = new X509ChainPolicy();

#if !MOBILE
            chain.ChainPolicy.RevocationMode = revocation_mode;
#endif

            for (int i = 1; i < certs.Count; i++)
            {
                chain.ChainPolicy.ExtraStore.Add(certs [i]);
            }

            return(chain);
        }
Ejemplo n.º 46
0
        public SSCX.X509Certificate GetRemoteCertificate(out PSSCX.X509CertificateCollection remoteCertificateStore)
        {
            MX.X509CertificateCollection monoCollection;
            var remoteCert = Context.GetRemoteCertificate(out monoCollection);

            if (remoteCert == null)
            {
                remoteCertificateStore = null;
                return(null);
            }

            remoteCertificateStore = new PSSCX.X509CertificateCollection();
            foreach (var cert in monoCollection)
            {
                remoteCertificateStore.Add(new PSSCX.X509Certificate2(cert.RawData));
            }
            return(new PSSCX.X509Certificate2(remoteCert.RawData));
        }
Ejemplo n.º 47
0
        public static bool Evaluate(
            MonoTlsSettings settings, string host, XX509CertificateCollection certs,
            X509Chain chain, ref SslPolicyErrors errors, ref int status11)
        {
            if (!CheckUsage(certs, host, ref errors, ref status11))
            {
                return(false);
            }

            if (settings != null && settings.SkipSystemValidators)
            {
                return(false);
            }

            var anchors = settings != null ? settings.TrustAnchors : null;

            return(EvaluateSystem(certs, anchors, host, chain, ref errors, ref status11));
        }
Ejemplo n.º 48
0
        public static MonoNewTlsStream CreateClient(
            Stream innerStream, bool leaveOpen, MonoTlsProvider provider, MonoTlsSettings settings,
            string targetHost, PSSCX.X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
        {
            var stream = new MonoNewTlsStream(innerStream, leaveOpen, provider, settings);

            try {
                stream.AuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
            } catch (Exception ex) {
                var tlsEx = stream.LastError;
                if (tlsEx != null)
                {
                    throw new AggregateException(ex, tlsEx);
                }
                throw;
            }
            return(stream);
        }
Ejemplo n.º 49
0
        ValidationResult ValidateChain(string host, bool server, X509Certificate leaf,
                                       X509Chain chain, XX509CertificateCollection certs,
                                       SslPolicyErrors errors)
        {
            var oldChain  = chain;
            var ownsChain = chain == null;

            try {
                var result = ValidateChain(host, server, leaf, ref chain, certs, errors);
                if (chain != oldChain)
                {
                    ownsChain = true;
                }

                return(result);
            } finally {
                // If ValidateChain() changed the chain, then we need to free it.
                if (ownsChain && chain != null)
                {
                    chain.Dispose();
                }
            }
        }
 public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation)
 {
     throw null;
 }
 public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation)
 {
 }
Ejemplo n.º 52
0
 public SslClientStream(Stream stream, string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates) : this(stream, targetHost, false, SecurityProtocolType.Default, clientCertificates)
 {
 }
Ejemplo n.º 53
0
 public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation)
 {
     throw new PlatformNotSupportedException();
 }
Ejemplo n.º 54
0
 internal override System.Security.Cryptography.X509Certificates.X509Certificate OnLocalCertificateSelection(System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection serverRequestedCertificates)
 {
     throw new NotSupportedException();
 }
        private void validateCertificates(X509CertificateCollection certificates)
        {
            ServerContext    context     = (ServerContext)this.Context;
            AlertDescription description = AlertDescription.BadCertificate;

            SSCX.X509CertificateMono client = null;
            int[] certificateErrors         = null;

            // note: certificate may be null is no certificate is sent
            // (e.g. optional mutual authentication)
            if (certificates.Count > 0)
            {
                X509Certificate leaf = certificates[0];

                ArrayList errors = new ArrayList();

                // SSL specific check - not all certificates can be
                // used to server-side SSL some rules applies after
                // all ;-)
                if (!checkCertificateUsage(leaf))
                {
                    // WinError.h CERT_E_PURPOSE 0x800B0106
                    errors.Add((int)-2146762490);
                }

                X509Chain verify;
                // was a chain supplied ? if so use it, if not
                if (certificates.Count > 1)
                {
                    // if so use it (and don't build our own)
                    X509CertificateCollection chain = new X509CertificateCollection(certificates);
                    chain.Remove(leaf);
                    verify = new X509Chain(chain);
                }
                else
                {
                    // if not, then let's build our own (based on what's available in the stores)
                    verify = new X509Chain();
                }

                bool result = false;

                try
                {
                    result = verify.Build(leaf);
                }
                catch (Exception)
                {
                    result = false;
                }

                if (!result)
                {
                    switch (verify.Status)
                    {
                    case X509ChainStatusFlags.InvalidBasicConstraints:
                        // WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
                        errors.Add((int)-2146869223);
                        break;

                    case X509ChainStatusFlags.NotSignatureValid:
                        // WinError.h TRUST_E_BAD_DIGEST 0x80096010
                        errors.Add((int)-2146869232);
                        break;

                    case X509ChainStatusFlags.NotTimeNested:
                        // WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
                        errors.Add((int)-2146762494);
                        break;

                    case X509ChainStatusFlags.NotTimeValid:
                        // WinError.h CERT_E_EXPIRED 0x800B0101
                        description = AlertDescription.CertificateExpired;
                        errors.Add((int)-2146762495);
                        break;

                    case X509ChainStatusFlags.PartialChain:
                        // WinError.h CERT_E_CHAINING 0x800B010A
                        description = AlertDescription.UnknownCA;
                        errors.Add((int)-2146762486);
                        break;

                    case X509ChainStatusFlags.UntrustedRoot:
                        // WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109
                        description = AlertDescription.UnknownCA;
                        errors.Add((int)-2146762487);
                        break;

                    default:
                        // unknown error
                        description = AlertDescription.CertificateUnknown;
                        errors.Add((int)verify.Status);
                        break;
                    }
                }
                client            = new SSCX.X509CertificateMono(leaf.RawData);
                certificateErrors = (int[])errors.ToArray(typeof(int));
            }
            else
            {
                certificateErrors = new int[0];
            }

            SSCX.X509CertificateCollection certCollection = new SSCX.X509CertificateCollection();
            foreach (X509Certificate certificate in certificates)
            {
                certCollection.Add(new SSCX.X509Certificate(certificate.RawData));
            }
            if (!context.SslStream.RaiseClientCertificateValidation(client, certificateErrors))
            {
                throw new TlsException(
                          description,
                          "Invalid certificate received from client.");
            }

            this.Context.ClientSettings.ClientCertificate = client;
        }
Ejemplo n.º 56
0
 public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
     throw new PlatformNotSupportedException();
 }
Ejemplo n.º 57
0
 internal System.Security.Cryptography.X509Certificates.X509Certificate RaiseClientCertificateSelection(System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection serverRequestedCertificates)
 {
     return(base.RaiseLocalCertificateSelection(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates));
 }
 public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState)
 {
     throw null;
 }
Ejemplo n.º 59
0
 public SslClientStream(Stream stream, string targetHost, bool ownsStream, SecurityProtocolType securityProtocolType, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates) : base(stream, ownsStream)
 {
     if (targetHost == null || targetHost.Length == 0)
     {
         throw new ArgumentNullException("targetHost is null or an empty string.");
     }
     this.context  = new ClientContext(this, securityProtocolType, targetHost, clientCertificates);
     this.protocol = new ClientRecordProtocol(this.innerStream, (ClientContext)this.context);
 }
Ejemplo n.º 60
0
 public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState)
 {
     throw new PlatformNotSupportedException();
 }