Inheritance: SslStreamBase
示例#1
0
        public ServerContext(
            SslServerStream stream,
            SecurityProtocolType securityProtocolType,
            System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate,
            bool clientCertificateRequired,
            bool requestClientCertificate)
            : base(securityProtocolType)
        {
            this.sslStream = stream;
            this.clientCertificateRequired  = clientCertificateRequired;
            this.request_client_certificate = requestClientCertificate;
            Mono.Security.X509.X509Certificate x509Certificate1 = new Mono.Security.X509.X509Certificate(serverCertificate.GetRawCertData());
            this.ServerSettings.Certificates = new Mono.Security.X509.X509CertificateCollection();
            this.ServerSettings.Certificates.Add(x509Certificate1);
            this.ServerSettings.UpdateCertificateRSA();
            this.ServerSettings.CertificateTypes    = new ClientCertificateType[1];
            this.ServerSettings.CertificateTypes[0] = ClientCertificateType.RSA;
            Mono.Security.X509.X509CertificateCollection rootCertificates = X509StoreManager.TrustedRootCertificates;
            string[] strArray = new string[rootCertificates.Count];
            int      num      = 0;

            foreach (Mono.Security.X509.X509Certificate x509Certificate2 in rootCertificates)
            {
                strArray[num++] = x509Certificate2.IssuerName;
            }
            this.ServerSettings.DistinguisedNames = strArray;
        }
		public ServerContext(
			SslServerStream			stream,
			SecurityProtocolType	securityProtocolType,
			X509Certificate			serverCertificate,
			bool					clientCertificateRequired)
			: base(securityProtocolType)
		{
			this.sslStream					= stream;
			this.clientCertificateRequired	= clientCertificateRequired;

			// Convert the System.Security cert to a Mono Cert
			MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData());

			// Add server certificate to the certificate collection
			this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection();
			this.ServerSettings.Certificates.Add(cert);

			this.ServerSettings.UpdateCertificateRSA();

			// Add requested certificate types
			this.ServerSettings.CertificateTypes = new ClientCertificateType[1];
			this.ServerSettings.CertificateTypes[0] = ClientCertificateType.RSA;

			// Add certificate authorities
			this.ServerSettings.DistinguisedNames = new string[0];
		}
		public XSPWorker (Socket client, EndPoint localEP, ApplicationServer server,
			bool secureConnection,
			SecurityProtocolType securityProtocol,
			X509Certificate cert,
			PrivateKeySelectionCallback keyCB,
			bool allowClientCert,
			bool requireClientCert) 
		{
			if (secureConnection) {
				ssl = new SslInformation {
					AllowClientCertificate = allowClientCert,
					RequireClientCertificate = requireClientCert,
					RawServerCertificate = cert.GetRawCertData ()
				};

				netStream = new LingeringNetworkStream (client, true);
				var s = new SslServerStream (netStream, cert, requireClientCert, false);
				s.PrivateKeyCertSelectionDelegate += keyCB;
				s.ClientCertValidationDelegate += ClientCertificateValidation;
				stream = s;
			} else {
				netStream = new LingeringNetworkStream (client, false);
				stream = netStream;
			}

			sock = client;
			this.server = server;
			remoteEP = (IPEndPoint) client.RemoteEndPoint;
			this.localEP = (IPEndPoint) localEP;
		}
示例#4
0
        public ServerContext(
            SslServerStream stream,
            SecurityProtocolType securityProtocolType,
            X509Certificate serverCertificate,
            bool clientCertificateRequired)
            : base(securityProtocolType)
        {
            this.sslStream = stream;
            this.clientCertificateRequired = clientCertificateRequired;

            // Convert the System.Security cert to a Mono Cert
            MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData());

            // Add server certificate to the certificate collection
            this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection();
            this.ServerSettings.Certificates.Add(cert);

            this.ServerSettings.UpdateCertificateRSA();

            // Add requested certificate types
            this.ServerSettings.CertificateTypes    = new ClientCertificateType[1];
            this.ServerSettings.CertificateTypes[0] = ClientCertificateType.RSA;

            // Add certificate authorities
            MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates;
            string[] list = new string [trusted.Count];
            int      i    = 0;

            foreach (MonoX509.X509Certificate root in trusted)
            {
                list [i++] = root.IssuerName;
            }
            this.ServerSettings.DistinguisedNames = list;
        }
		public ServerContext(
			SslServerStream			stream,
			SecurityProtocolType	securityProtocolType,
			X509Certificate			serverCertificate,
			bool					clientCertificateRequired)
			: base(securityProtocolType)
		{
			this.sslStream					= stream;
			this.clientCertificateRequired	= clientCertificateRequired;

			// Convert the System.Security cert to a Mono Cert
			MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData());

			// Add server certificate to the certificate collection
			this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection();
			this.ServerSettings.Certificates.Add(cert);

			this.ServerSettings.UpdateCertificateRSA();

			// Add requested certificate types
			this.ServerSettings.CertificateTypes = new ClientCertificateType[1];
			this.ServerSettings.CertificateTypes[0] = ClientCertificateType.RSA;

			// Add certificate authorities
			MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates;
			string[] list = new string [trusted.Count];
			int i = 0;
			foreach (MonoX509.X509Certificate root in trusted)
			{
				list [i++] = root.IssuerName;
			}
			this.ServerSettings.DistinguisedNames = list;
		}
        public ServerContext(
            SslServerStream stream,
            SecurityProtocolType securityProtocolType,
            X509Certificate serverCertificate,
            bool clientCertificateRequired,
            bool requestClientCertificate)
            : base(securityProtocolType)
        {
            SslStream = stream;
            ClientCertificateRequired = clientCertificateRequired;
            RequestClientCertificate  = requestClientCertificate;

            // Convert the System.Security cert to a Mono Cert
            var cert = new MonoSecurity::Mono.Security.X509.X509Certificate(serverCertificate.GetRawCertData());

            // Add server certificate to the certificate collection
            ServerSettings.Certificates = new X509CertificateCollection();
            ServerSettings.Certificates.Add(cert);

            ServerSettings.UpdateCertificateRSA();

            if (CertificateValidationHelper.SupportsX509Chain)
            {
                // Build the chain for the certificate and if the chain is correct, add all certificates
                // (except the root certificate [FIRST ONE] ... the client is supposed to know that one,
                // otherwise the whole concept of a trusted chain doesn't work out ...
                var chain = new X509Chain(X509StoreManager.IntermediateCACertificates);

                if (chain.Build(cert))
                {
                    for (var j = chain.Chain.Count - 1; j > 0; j--)
                    {
                        ServerSettings.Certificates.Add(chain.Chain[j]);
                    }
                }
            }

            // Add requested certificate types
            ServerSettings.CertificateTypes = new ClientCertificateType [ServerSettings.Certificates.Count];
            for (var j = 0; j < ServerSettings.CertificateTypes.Length; j++)
            {
                ServerSettings.CertificateTypes[j] = ClientCertificateType.RSA;
            }

            if (CertificateValidationHelper.SupportsX509Chain)
            {
                // Add certificate authorities
                var trusted = X509StoreManager.TrustedRootCertificates;
                var list    = new string [trusted.Count];
                var i       = 0;
                foreach (var root in trusted)
                {
                    list[i++] = root.IssuerName;
                }
                ServerSettings.DistinguisedNames = list;
            }
        }
示例#7
0
		static void Main (string [] args)
		{
			certfile = (args.Length > 1) ? args [0] : "ssl.cer";
			keyfile = (args.Length > 1) ? args [1] : "ssl.pvk";

			Socket listenSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			IPEndPoint localEndPoint = new IPEndPoint (IPAddress.Any, 4433);
			Socket requestSocket;

			listenSocket.Bind (localEndPoint);
			listenSocket.Listen (10);

			while (true) {
				try {
					requestSocket = listenSocket.Accept ();
					using (NetworkStream ns = new NetworkStream (requestSocket, FileAccess.ReadWrite, true)) {
						using (SslServerStream s = new SslServerStream (ns, Certificate, false, false)) {
							s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
							s.ClientCertValidationDelegate += new CertificateValidationCallback (VerifyClientCertificate);
							StreamReader reader = new StreamReader (s);
							StreamWriter writer = new StreamWriter (s, Encoding.ASCII);

							string line;
							// Read request header
							do {
								line = reader.ReadLine ();
								if (line != null)
									Console.WriteLine (line);
							}
							while (line != null && line.Length > 0);

							string answer = String.Format ("HTTP/1.0 200{0}Connection: close{0}" +
								"Content-Type: text/html{0}Content-Encoding: {1}{0}{0}" +
								"<html><body><h1>Hello {2}!</h1></body></html>{0}",
								"\r\n", Encoding.ASCII.WebName,
								s.ClientCertificate == null ? "World" : s.ClientCertificate.GetName ());

							// Send response
							writer.Write (answer);

							writer.Flush ();
							s.Flush ();
							ns.Flush ();
						}
					}
				}
				catch (Exception ex) {
					Console.WriteLine ("---------------------------------------------------------");
					Console.WriteLine (ex.ToString ());
				}
			}
		}
示例#8
0
		public ServerContext(
			SslServerStream			stream,
			SecurityProtocolType	securityProtocolType,
			X509Certificate			serverCertificate,
			bool					clientCertificateRequired,
			bool					requestClientCertificate)
			: base(securityProtocolType)
		{
			this.sslStream					= stream;
			this.clientCertificateRequired	= clientCertificateRequired;
			this.request_client_certificate	= requestClientCertificate;

			// Convert the System.Security cert to a Mono Cert
			MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData());

			// Add server certificate to the certificate collection
			this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection();
			this.ServerSettings.Certificates.Add(cert);

			this.ServerSettings.UpdateCertificateRSA();

			if (CertificateValidationHelper.SupportsX509Chain) {
				// Build the chain for the certificate and if the chain is correct, add all certificates 
				// (except the root certificate [FIRST ONE] ... the client is supposed to know that one,
				// otherwise the whole concept of a trusted chain doesn't work out ... 
				MonoX509.X509Chain chain = new MonoX509.X509Chain (MonoX509.X509StoreManager.IntermediateCACertificates);

				if (chain.Build (cert)) {
					for (int j = chain.Chain.Count - 1; j > 0; j--)
						ServerSettings.Certificates.Add (chain.Chain [j]);
				}
			}

			// Add requested certificate types
			ServerSettings.CertificateTypes = new ClientCertificateType [ServerSettings.Certificates.Count];
			for (int j = 0; j < this.ServerSettings.CertificateTypes.Length; j++)
				ServerSettings.CertificateTypes [j] = ClientCertificateType.RSA;

			if (CertificateValidationHelper.SupportsX509Chain) {
				// Add certificate authorities
				MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates;
				string[] list = new string [trusted.Count];
				int i = 0;
				foreach (MonoX509.X509Certificate root in trusted) {
					list [i++] = root.IssuerName;
				}
				this.ServerSettings.DistinguisedNames = list;
			}
		}
		public TlsServerSession (X509Certificate2 cert, bool mutual)
		{
			this.mutual = mutual;
			stream = new MemoryStream ();
			ssl = new SslServerStream (stream, cert, mutual, true, SecurityProtocolType.Tls);
			ssl.PrivateKeyCertSelectionDelegate = delegate (X509Certificate c, string host) {
				if (c.GetCertHashString () == cert.GetCertHashString ())
					return cert.PrivateKey;
				return null;
			};
			ssl.ClientCertValidationDelegate = delegate (X509Certificate certificate, int[] certificateErrors) {
				// FIXME: use X509CertificateValidator
				return true;
			};
		}
示例#10
0
		public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
		{
			this.sock = sock;
			this.epl = epl;
			this.secure = secure;
			this.key = key;
			if (secure == false) {
				stream = new NetworkStream (sock, false);
			} else {
				SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
				ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
				stream = ssl_stream;
			}
			timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
			Init ();
		}
示例#11
0
		public HttpConnection (Socket sock, IHttpListenerContextBinder epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
		{
			this.sock = sock;
			this.epl = epl;
			this.secure = secure;
			this.key = key;
			if (secure == false) {
				stream = new NetworkStream (sock, false);
			} else {
				SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
				ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
				stream = ssl_stream;

			}
			Init ();
		}
示例#12
0
		public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
		{
			this.sock = sock;
			this.epl = epl;
			this.secure = secure;
			this.key = key;
			if (secure == false) {
				stream = new NetworkStream (sock, false);
			} else {
#if EMBEDDED_IN_1_0
				throw new NotImplementedException ();
#else
				SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
				ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
				stream = ssl_stream;
#endif
			}
			Init ();
		}
示例#13
0
		public SocketPongClient(Socket socket, bool useTls, int readBufferSize, string certFile, string pvkFile, string pvkPassword):
			base(useTls, readBufferSize, socket)
		{
			if (useTls)
			{
				_privateKey = PrivateKey.CreateFromFile(pvkFile, pvkPassword).RSA;
				
				SslServerStream secureStream = new SslServerStream(
					base.NetworkStream,
					X509Certificate.CreateFromCertFile(certFile),
					false,
					true,
					Mono.Security.Protocol.Tls.SecurityProtocolType.Tls);

				secureStream.PrivateKeyCertSelectionDelegate = new PrivateKeySelectionCallback(PrivateKeyCertSelectionCallback);

				base.SecureStream = secureStream;
			}
		}
示例#14
0
		public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
		{
			if (IsAuthenticated)
				throw new InvalidOperationException ("This SslStream is already authenticated");

			SslServerStream s = new SslServerStream (InnerStream, serverCertificate, false, clientCertificateRequired, !LeaveInnerStreamOpen, GetMonoSslProtocol (enabledSslProtocols));
			s.CheckCertRevocationStatus = checkCertificateRevocation;
			// Due to the Mono.Security internal, it cannot reuse
			// the delegated argument, as Mono.Security creates 
			// another instance of X509Certificate which lacks 
			// private key but is filled the private key via this
			// delegate.
			s.PrivateKeyCertSelectionDelegate = delegate (X509Certificate cert, string targetHost) {
				// ... so, we cannot use the delegate argument.
				X509Certificate2 cert2 = serverCertificate as X509Certificate2 ?? new X509Certificate2 (serverCertificate);
				return cert2 != null ? cert2.PrivateKey : null;
			};

			s.ClientCertValidationDelegate = delegate (X509Certificate cert, int[] certErrors) {
				var errors = certErrors.Length > 0 ? MonoSslPolicyErrors.RemoteCertificateChainErrors : MonoSslPolicyErrors.None;
				return ((ChainValidationHelper)certificateValidator).ValidateClientCertificate (cert, errors);
			};

			ssl_stream = s;

			return BeginWrite (new byte[0], 0, 0, asyncCallback, asyncState);
		}
		public bool StartTls() {
			if (this.SslIsActive) {
				Console.WriteLine("if (this.SslIsActive)");
				return true;
			}

			try {
				Console.WriteLine("lalelu1");
				if (this._isServer) {
					if (_serverCertificate == null) {
						Assembly assembly = Assembly.GetExecutingAssembly();
						Stream stream = assembly.GetManifestResourceStream("localhost.cer");
						byte[] certificateBytes = new byte[stream.Length];
						stream.Read(certificateBytes, 0, Convert.ToInt32(stream.Length));
						_serverCertificate = new X509Certificate(certificateBytes);
					}

					Console.WriteLine("if (this._isServer)");
					this._sslServerStream = new SslServerStream(this._stream, _serverCertificate, false, false);
					this._sslServerStream.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback(this.PrivateKeySelectionCallback);
					this._currentUsedStream = this._sslServerStream;
				} else {
					Console.WriteLine("if (!this._isServer)");
					//this._sslClientStream = new SslClientStream(this._stream, "mail.gmx.net", false);
					this._sslClientStream = new SslStream(this._stream, true, new RemoteCertificateValidationCallback(CertificateValidationCallback));
					//this._sslClientStream.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback(this.PrivateKeySelectionCallback);
					this._sslClientStream.AuthenticateAsClient("SslStreamCert");
					this._currentUsedStream = this._sslClientStream;
				}

				Console.WriteLine("bar");
				return true;
			} catch(Exception ex) {
				this._sslServerStream = null;
				this._sslClientStream = null;
				logger.ErrorException(ex.Message, ex);
				return false;
			}
		}
示例#16
0
        protected override void CreateFrondEndConnection(Socket socket)
        {
            X509Certificate2 serverCertificate = new X509Certificate2(_certificateFile);

            SslServerStream secureStream = new SslServerStream(
                new NetworkStream(socket,  true),
                serverCertificate,
                true,
                true,
                SecurityProtocolType.Tls);
            secureStream.CheckCertRevocationStatus = true;
            secureStream.PrivateKeyCertSelectionDelegate += delegate (X509Certificate cert, string targetHost)
            {
                X509Certificate2 cert2 = serverCertificate as X509Certificate2 ?? new X509Certificate2 (serverCertificate);
                return cert2 != null ? cert2.PrivateKey : null;
            };

            SslConnection connection = null;

            try
            {
                secureStream.ClientCertValidationDelegate += ValidateRemoteCertificate;
                secureStream.Read (new byte [0], 0, 0);

                connection = new SslConnection(socket, secureStream);
            }
            catch(Exception e)
            {
                _logger.FatalFormat("Error negotiating ssl connection: {0}", e);
                return;
            }

            RaiseClientConnectedEvent(connection);
        }
示例#17
0
		public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols sslProtocolType, bool checkCertificateRevocation, AsyncCallback callback, object asyncState)
		{
			if (IsAuthenticated)
				throw new InvalidOperationException ("This SslStream is already authenticated");

			SslServerStream s = new SslServerStream (InnerStream, serverCertificate, clientCertificateRequired, !LeaveInnerStreamOpen, GetMonoSslProtocol (sslProtocolType));
			s.CheckCertRevocationStatus = checkCertificateRevocation;
			// Due to the Mono.Security internal, it cannot reuse
			// the delegated argument, as Mono.Security creates 
			// another instance of X509Certificate which lacks 
			// private key but is filled the private key via this
			// delegate.
			s.PrivateKeyCertSelectionDelegate = delegate (X509Certificate cert, string targetHost) {
				// ... so, we cannot use the delegate argument.
				X509Certificate2 cert2 = serverCertificate as X509Certificate2 ?? new X509Certificate2 (serverCertificate);
				return cert2 != null ? cert2.PrivateKey : null;
			};

			if (validation_callback != null)
				s.ClientCertValidationDelegate = delegate (X509Certificate cert, int [] certErrors) {
					X509Chain chain = null;
					if (cert is X509Certificate2) {
						chain = new X509Chain ();
						chain.Build ((X509Certificate2) cert);
					}
					// FIXME: SslPolicyErrors is incomplete
					SslPolicyErrors errors = certErrors.Length > 0 ? SslPolicyErrors.RemoteCertificateChainErrors : SslPolicyErrors.None;
					return validation_callback (this, cert, chain, errors);
				};

			ssl_stream = s;

			return BeginRead (new byte [0], 0, 0, callback, asyncState);
		}