Exemplo n.º 1
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;
        }
        private void AuthAsServer()
        {
            var s = new SslServerStream(Parent.InnerStream, Options.ServerCertificate, false,
                                        Options.ClientCertificateRequired, !Parent.LeaveInnerStreamOpen,
                                        GetMonoSslProtocol(EnabledProtocols))
            {
                CheckCertRevocationStatus = Options.CertificateRevocationCheckMode != X509RevocationMode.NoCheck
            };

            // 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
            {
                // ... so, we cannot use the delegate argument.
                var cert2 = Options.ServerCertificate as X509Certificate2 ??
                            new X509Certificate2(Options.ServerCertificate);
                return(cert2.PrivateKey);
            };

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

            sslStream = s;
        }
Exemplo n.º 3
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));
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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, 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);
            };

            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(BeginWrite(new byte[0], 0, 0, asyncCallback, asyncState));
        }

        MonoSecurityProtocolType GetMonoSslProtocol(SslProtocols ms)
        {
            switch (ms)
            {
            case SslProtocols.Ssl2:
                return(MonoSecurityProtocolType.Ssl2);

            case SslProtocols.Ssl3:
                return(MonoSecurityProtocolType.Ssl3);

            case SslProtocols.Tls:
                return(MonoSecurityProtocolType.Tls);

            default:
                return(MonoSecurityProtocolType.Default);
            }
        }
Exemplo n.º 6
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());
                }
            }
        }
Exemplo n.º 7
0
        public SslServer(int port)
        {
            Listener  = new TcpListener(IPAddress.Any, port);
            client    = null;
            SslStream = new SslServerStream();
            SslStream.ServerTokenOutput = OnSslServerToken;
            SslStream.EncryptDataOutput = OnSslEncryptedData;
            SslStream.DecryptDataOutput = OnSslDecryptedData;

            X509Cert = new X509Certificate2("E:/MessageFramework/SelfCert.pfx", "messageframework");
        }
Exemplo n.º 8
0
        void RunInternal(object state)
        {
            RequestData rdata = initial.RequestData;

            initial.FreeBuffer();
            string vhost = null;             // TODO: read the headers in InitialWorkerRequest
            int    port  = ((IPEndPoint)localEP).Port;

            VPathToHost        vapp = server.GetApplicationForPath(vhost, port, rdata.Path, true);
            XSPApplicationHost host = null;

            if (vapp != null)
            {
                host = (XSPApplicationHost)vapp.AppHost;
            }

            if (host == null)
            {
                byte [] nf = HttpErrors.NotFound(rdata.Path);
                Write(nf, 0, nf.Length);
                Close();
                return;
            }

            broker    = (XSPRequestBroker)vapp.RequestBroker;
            requestId = broker.RegisterRequest(this);

#if MONO
            if (ssl != null)
            {
                SslServerStream s = (stream as SslServerStream);
                ssl.KeySize       = s.CipherStrength;
                ssl.SecretKeySize = s.KeyExchangeStrength;
            }
#endif

            try {
                string redirect;
                vapp.Redirect(rdata.Path, out redirect);
                host.ProcessRequest(requestId, localEP.Address.Address, localEP.Port,
                                    remoteEP.Address.Address, remoteEP.Port, rdata.Verb,
                                    rdata.Path, rdata.QueryString,
                                    rdata.Protocol, rdata.InputBuffer, redirect, sock.Handle, ssl);
            } catch (FileNotFoundException fnf) {
                // We print this one, as it might be a sign of a bad deployment
                // once we require the .exe and Mono.WebServer in bin or the GAC.
                Console.Error.WriteLine(fnf);
            } catch (IOException) {
                // This is ok (including EndOfStreamException)
            } catch (Exception e) {
                Console.Error.WriteLine(e);
            }
        }
Exemplo n.º 9
0
 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);
     };
 }
Exemplo n.º 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, true, false);
				ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
				ssl_stream.ClientCertValidationDelegate += OnClientCertificateValidation;
				stream = ssl_stream;
			}
			timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
			Init ();
		}
Exemplo n.º 11
0
        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);
            }
        }
Exemplo n.º 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
     {
         SslServerStream ssl_stream = new SslServerStream(new NetworkStream(sock, false), cert, false, false);
         ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
         stream = ssl_stream;
     }
     Init();
 }
Exemplo n.º 13
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)
     {
         stream = new NetworkStream(sock, owns_socket: false);
     }
     else
     {
         SslServerStream sslServerStream  = new SslServerStream(new NetworkStream(sock, owns_socket: false), cert, clientCertificateRequired: false, ownsStream: false);
         SslServerStream sslServerStream2 = sslServerStream;
         sslServerStream2.PrivateKeyCertSelectionDelegate = (PrivateKeySelectionCallback)Delegate.Combine(sslServerStream2.PrivateKeyCertSelectionDelegate, new PrivateKeySelectionCallback(OnPVKSelection));
         stream = sslServerStream;
     }
     Init();
 }
Exemplo n.º 14
0
 public HttpConnection(System.Net.Sockets.Socket sock, EndPointListener epl, bool secure, System.Security.Cryptography.X509Certificates.X509Certificate2 cert, AsymmetricAlgorithm key)
 {
     this.sock   = sock;
     this.epl    = epl;
     this.secure = secure;
     this.key    = key;
     if (!secure)
     {
         this.stream = new System.Net.Sockets.NetworkStream(sock, false);
     }
     else
     {
         SslServerStream sslServerStream  = new SslServerStream(new System.Net.Sockets.NetworkStream(sock, false), cert, false, false);
         SslServerStream sslServerStream2 = sslServerStream;
         sslServerStream2.PrivateKeyCertSelectionDelegate = (PrivateKeySelectionCallback)Delegate.Combine(sslServerStream2.PrivateKeyCertSelectionDelegate, new PrivateKeySelectionCallback(this.OnPVKSelection));
         this.stream = sslServerStream;
     }
     this.Init();
 }
Exemplo n.º 15
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;
            }
        }
Exemplo n.º 16
0
        public virtual IAsyncResult BeginAuthenticateAsServer(
            X509Certificate serverCertificate,
            bool clientCertificateRequired,
            SslProtocols enabledSslProtocols,
            bool checkCertificateRevocation,
            AsyncCallback asyncCallback,
            object asyncState)
        {
            if (this.IsAuthenticated)
            {
                throw new InvalidOperationException("This SslStreamM is already authenticated");
            }

            var monoSsl = this.GetMonoSslProtocol(enabledSslProtocols);

            SslServerStream sslServerStream = new SslServerStream(this.InnerStream, serverCertificate, clientCertificateRequired, !this.LeaveInnerStreamOpen, monoSsl);

            sslServerStream.CheckCertRevocationStatus       = checkCertificateRevocation;
            sslServerStream.PrivateKeyCertSelectionDelegate = (PrivateKeySelectionCallback)((cert, targetHost) =>
            {
                if (!(serverCertificate is X509Certificate2 x509Certificate2))
                {
                    x509Certificate2 = new X509Certificate2(serverCertificate);
                }
                return(x509Certificate2?.PrivateKey);
            });
            if (this.validation_callback != null)
            {
                sslServerStream.ClientCertValidationDelegate = (CertificateValidationCallback)((cert, certErrors) =>
                {
                    X509Chain chain = (X509Chain)null;
                    if (cert is X509Certificate2)
                    {
                        chain = new X509Chain();
                        chain.Build((X509Certificate2)cert);
                    }
                    SslPolicyErrors sslPolicyErrors = certErrors.Length > 0 ? SslPolicyErrors.RemoteCertificateChainErrors : SslPolicyErrors.None;
                    return(this.validation_callback((object)this, cert, chain, sslPolicyErrors));
                });
            }
            this.ssl_stream = (SslStreamBase)sslServerStream;
            return(this.BeginWrite(new byte[0], 0, 0, asyncCallback, asyncState));
        }
Exemplo n.º 17
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, true, false);
         ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
         ssl_stream.ClientCertValidationDelegate    += OnClientCertificateValidation;
         stream = ssl_stream;
     }
     timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
     Init();
 }
Exemplo n.º 18
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
            {
#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();
        }
Exemplo n.º 19
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, 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;
			};

			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 BeginWrite (new byte[0], 0, 0, asyncCallback, asyncState);
		}