예제 #1
0
 internal static async Task AuthenticateAsServerAsync(this System.Net.Security.SslStream source,
                                                      System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate,
                                                      bool clientCertificateRequired,
                                                      System.Security.Authentication.SslProtocols enabledSslProtocols,
                                                      bool checkCertificateRevocation)
 {
     await Task.Factory.FromAsync(
         (c, s) => source.BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, c, s),
         (r) => source.EndAuthenticateAsServer(r),
         null).ConfigureAwait(false);
 }
예제 #2
0
 internal static async Task AuthenticateAsClientAsync(this System.Net.Security.SslStream source,
                                                      string targetHost,
                                                      System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates,
                                                      System.Security.Authentication.SslProtocols enabledSslProtocols,
                                                      bool checkCertificateRevocation)
 {
     await Task.Factory.FromAsync(
         (c, s) => source.BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, c, s),
         (r) => source.EndAuthenticateAsClient(r),
         null).ConfigureAwait(false);
 }
예제 #3
0
 public GeneralSyslogServer(
     ServerType serverType,
     int port,
     System.Net.IPAddress listenIP,
     System.Security.Authentication.SslProtocols protocol,
     System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
     this.ServerType    = serverType;
     this.Port          = port;
     this.ListenAddress = listenIP;
     this.Protocol      = protocol;
     this.Certificate   = certificate;
 }
예제 #4
0
        private void con_LocalConnectionAuthenticated(ConnectionData data, System.Security.Authentication.SslProtocols protocol,
                                                      System.Security.Authentication.CipherAlgorithmType cipherAlgorithmType, int cipherAlgorithmStrength,
                                                      System.Security.Authentication.HashAlgorithmType hashAlgorithmType, int hashAlgorithmStrength,
                                                      System.Security.Authentication.ExchangeAlgorithmType exchangeAlgorithmType, int exchangeAlgorithmStrength)
        {
            ForwardingConnection con = data.Connection;

            AddLogEntry(logClient, con.ConId, "Local connection authenticated. Protocol: " + protocol.ToString() + ", Cipher: " + cipherAlgorithmType.ToString()
                        + " (" + cipherAlgorithmStrength + " Bit), "
                        + "Hash: " + hashAlgorithmType.ToString() + " (" + hashAlgorithmStrength + " Bit), Exchange: " + exchangeAlgorithmType
                        + " (" + exchangeAlgorithmStrength + " Bit)");

            AddLogEntry(logServer, con.ConId, "Connecting...");
        }
예제 #5
0
        private System.Security.Authentication.SslProtocols GetNetSecurityProtocol()
        {
            if (SslConnection.fNetSecurityProtocolTls == System.Security.Authentication.SslProtocols.None)
            {
                // In the worst case these Reflection calls will be executed several times
                try
                {
                    SslConnection.fNetSecurityProtocolTls = System.Security.Authentication.SslProtocols.Tls | (System.Security.Authentication.SslProtocols)Enum.Parse(typeof(System.Security.Authentication.SslProtocols), "Tls12");
                }
                catch (ArgumentException)
                {
                    // Enum.Parse will fail on .NET less than 4.5
                    SslConnection.fNetSecurityProtocolTls = System.Security.Authentication.SslProtocols.Tls;
                }
            }

            return(this.fFactory.UseTls ? SslConnection.fNetSecurityProtocolTls : System.Security.Authentication.SslProtocols.Default);
        }
예제 #6
0
        private void con_RemoteConnectionAuthenticated(ConnectionData data, System.Security.Authentication.SslProtocols protocol,
                                                       System.Security.Cryptography.X509Certificates.X509Certificate2 remoteCertificate,
                                                       System.Security.Authentication.CipherAlgorithmType cipherAlgorithmType, int cipherAlgorithmStrength,
                                                       System.Security.Authentication.HashAlgorithmType hashAlgorithmType, int hashAlgorithmStrength,
                                                       System.Security.Authentication.ExchangeAlgorithmType exchangeAlgorithmType, int exchangeAlgorithmStrength)
        {
            ForwardingConnection con = data.Connection;

            AddLogEntry(logServer, con.ConId, "Remote connection authenticated. Protocol: " + protocol.ToString() + ", Cipher: " + cipherAlgorithmType.ToString()
                        + " (" + cipherAlgorithmStrength + " Bit), "
                        + "Hash: " + hashAlgorithmType.ToString() + " (" + hashAlgorithmStrength + " Bit), Exchange: " + exchangeAlgorithmType
                        + " (" + exchangeAlgorithmStrength + " Bit)\r\n"
                        + "Certiticate Subject: " + remoteCertificate.Subject + "\r\n"
                        + "Certificate Issuer: " + remoteCertificate.Issuer + "\r\n"
                        + "Valid: Not before " + new DateTimeOffset(remoteCertificate.NotBefore).ToString()
                        + ", not after " + new DateTimeOffset(remoteCertificate.NotAfter).ToString() + "\r\n"
                        + "Fingerprint: " + remoteCertificate.Thumbprint);
        }
예제 #7
0
            private static void SetSslVersion(EasyRequest easy, IntPtr sslCtx = default(IntPtr))
            {
                // Get the requested protocols.
                System.Security.Authentication.SslProtocols protocols = easy._handler.SslProtocols;

                // We explicitly disallow choosing SSL2/3. Make sure they were filtered out.
                Debug.Assert((protocols & ~SecurityProtocol.AllowedSecurityProtocols) == 0,
                             "Disallowed protocols should have been filtered out.");

                // libcurl supports options for either enabling all of the TLS1.* protocols or enabling
                // just one of them; it doesn't currently support enabling two of the three, e.g. you can't
                // pick TLS1.1 and TLS1.2 but not TLS1.0, but you can select just TLS1.2.
                Interop.Http.CurlSslVersion curlSslVersion;
                switch (protocols)
                {
                case System.Security.Authentication.SslProtocols.Tls:
                    curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_0;
                    break;

                case System.Security.Authentication.SslProtocols.Tls11:
                    curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_1;
                    break;

                case System.Security.Authentication.SslProtocols.Tls12:
                    curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_2;
                    break;

                case System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12:
                    curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1;
                    break;

                default:
                    throw new NotSupportedException(SR.net_securityprotocolnotsupported);
                }

                try
                {
                    easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)curlSslVersion);
                }
                catch (CurlException e) when(e.HResult == (int)CURLcode.CURLE_UNKNOWN_OPTION)
                {
                    throw new NotSupportedException(SR.net_securityprotocolnotsupported, e);
                }
            }
        public void TestUploadCertificateImage()
        {
            //Get the cert number. The account needs to have CertCapture
            //be provisioned, already have a certificate created, and the
            //certificate needs to be valid.
            var certs  = Client.QueryCertificates(DefaultCompanyId, string.Empty, "valid EQ true", null, null, string.Empty).value;
            var certId = certs.FirstOrDefault().id.Value;

            //Use TLS 1.2 with .NET 2.0.
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            const System.Security.Authentication.SslProtocols _tls12 = (System.Security.Authentication.SslProtocols) 0x00000C00;
            const SecurityProtocolType tls12 = (SecurityProtocolType)_tls12;

            ServicePointManager.SecurityProtocol = tls12;

            //Get an image.
            using (WebClient webClient = new WebClient()) {
                byte[] jpegByteArr = webClient.DownloadData("https://developer.avalara.com/public/images/blog/12000-juris.jpg");

                FileResult fileResult = new FileResult()
                {
                    ContentType = "multipart/form-data",
                    Filename    = "test_cert_image.jpg",
                    Data        = jpegByteArr
                };

                //Send request.
                var certUploadResult = Client.UploadCertificateImage(DefaultCompanyId, certId, fileResult);

                //Response should be "OK"
                Assert.True(string.Equals(certUploadResult, "\"OK\""));

                //Test download of image attachment.
                var certAttachment = Client.DownloadCertificateImage(DefaultCompanyId, certId, null, CertificatePreviewType.Pdf);
                Assert.NotNull(certAttachment);
                Assert.True(string.Equals(certAttachment.ContentType, "application/pdf"));
                Assert.True(certAttachment.Data.Length > 1000);
            }
        }
예제 #9
0
 public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
 }
예제 #10
0
 public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
 }
예제 #11
0
        /// <summary>
        /// Extends BeginAuthenticateAsServer so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// sslstream.BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, asyncCallback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginAuthenticateAsServer(this SslStream sslstream, System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, Boolean clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation, AsyncCallback asyncCallback)
        {
            if (sslstream == null)
            {
                throw new ArgumentNullException("sslstream");
            }

            return(sslstream.BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, asyncCallback, null));
        }
예제 #12
0
		private System.Security.Authentication.SslProtocols GetNetSecurityProtocol()
		{
			if (SslConnection.fNetSecurityProtocolTls == System.Security.Authentication.SslProtocols.None)
			{
				// In the worst case these Reflection calls will be executed several times
				try
				{
					SslConnection.fNetSecurityProtocolTls = System.Security.Authentication.SslProtocols.Tls | (System.Security.Authentication.SslProtocols)Enum.Parse(typeof(System.Security.Authentication.SslProtocols), "Tls12");
				}
				catch (ArgumentException)
				{
					// Enum.Parse will fail on .NET less than 4.5
					SslConnection.fNetSecurityProtocolTls = System.Security.Authentication.SslProtocols.Tls;
				}
			}

			return this.fFactory.UseTls ? SslConnection.fNetSecurityProtocolTls : System.Security.Authentication.SslProtocols.Default;
		}
예제 #13
0
 public SslHandShake(string hostName, System.Security.Authentication.SslProtocols sslProtocol, System.Net.Security.RemoteCertificateValidationCallback serverCallback) : this(hostName, sslProtocol, serverCallback, null, null, false)
 {
 }
예제 #14
0
 /// <inheritdoc />
 public NetworkSender Create(string url, int maxQueueSize, System.Security.Authentication.SslProtocols sslProtocols, TimeSpan keepAliveTime)
예제 #15
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 null;
 }
예제 #16
0
        /// <summary>Connects to a remote POP3 server</summary>
        /// <param name="hostname">The <paramref name="hostname"/> of the POP3 server</param>
        /// <param name="port">The port of the POP3 server</param>
        /// <param name="sslVersion">Which SSL version to use</param>
        /// <param name="useSsl"><see langword="true"/> if SSL should be used. <see langword="false"/> if plain TCP should be used.</param>
        /// <param name="receiveTimeout">Timeout in milliseconds before a socket should time out from reading. Set to 0 or -1 to specify infinite timeout.</param>
        /// <param name="sendTimeout">Timeout in milliseconds before a socket should time out from sending. Set to 0 or -1 to specify infinite timeout.</param>
        /// <param name="certificateValidator">If you want to validate the certificate in a SSL connection, pass a reference to your validator. Supply <see langword="null"/> if default should be used.</param>
        /// <exception cref="PopServerNotAvailableException">If the server did not send an OK message when a connection was established</exception>
        /// <exception cref="PopServerNotFoundException">If it was not possible to connect to the server</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="hostname"/> is <see langword="null"/></exception>
        /// <exception cref="ArgumentOutOfRangeException">If port is not in the range [<see cref="IPEndPoint.MinPort"/>, <see cref="IPEndPoint.MaxPort"/> or if any of the timeouts is less than -1.</exception>
        public void Connect(string hostname, int port, bool useSsl, string sslVersion, int receiveTimeout, int sendTimeout, RemoteCertificateValidationCallback certificateValidator)
        {
            const string METHOD = CLASS + "Connect()";

            AssertDisposed();

            if (hostname == null)
            {
                throw new ArgumentNullException("hostname");
            }

            if (hostname.Length == 0)
            {
                throw new ArgumentException("hostname cannot be empty", "hostname");
            }

            if (port > IPEndPoint.MaxPort || port < IPEndPoint.MinPort)
            {
                throw new ArgumentOutOfRangeException("port");
            }

            if (receiveTimeout < -1)
            {
                throw new ArgumentOutOfRangeException("receiveTimeout");
            }

            if (sendTimeout < -1)
            {
                throw new ArgumentOutOfRangeException("sendTimeout");
            }

            if (State != ConnectionState.Disconnected)
            {
                throw new InvalidUseException("You cannot ask to connect to a POP3 server, when we are already connected to one. Disconnect first.");
            }

            TcpClient clientSocket = new TcpClient();

            clientSocket.ReceiveTimeout = receiveTimeout;
            clientSocket.SendTimeout    = sendTimeout;

            try
            {
                clientSocket.Connect(hostname, port);
            }
            catch (Exception ex)
            {
                // Close the socket - we are not connected, so no need to close stream underneath
                clientSocket.Close();

                throw new PopServerNotFoundException("Server not found", ex);
            }

            Stream stream;

            if (useSsl)
            {
                // If we want to use SSL, open a new SSLStream on top of the open TCP stream.
                // We also want to close the TCP stream when the SSL stream is closed
                // If a validator was passed to us, use it.
                SslStream sslStream;
                if (certificateValidator == null)
                {
                    sslStream = new SslStream(clientSocket.GetStream(), false);
                }
                else
                {
                    sslStream = new SslStream(clientSocket.GetStream(), false, certificateValidator);
                }
                sslStream.ReadTimeout  = receiveTimeout;
                sslStream.WriteTimeout = sendTimeout;

                // Authenticate the server (use the right TLS version)
                System.Security.Authentication.SslProtocols sslProtocol = System.Security.Authentication.SslProtocols.Tls;    //Default to TLS 1.0 for now
                switch (sslVersion)
                {
                case "Ssl30":
                    sslProtocol = System.Security.Authentication.SslProtocols.Ssl3;
                    break;

                case "Tls10":
                    sslProtocol = System.Security.Authentication.SslProtocols.Tls;
                    break;

                case "Tls11":
                    sslProtocol = System.Security.Authentication.SslProtocols.Tls11;
                    break;

                case "Tls12":
                    sslProtocol = System.Security.Authentication.SslProtocols.Tls12;
                    break;
                }
                sslStream.AuthenticateAsClient(hostname, null, sslProtocol, true);

                stream = sslStream;
            }
            else
            {
                // If we do not want to use SSL, use plain TCP
                stream = clientSocket.GetStream();
            }

            // Now do the connect with the same stream being used to read and write to
            Connect(stream);
        }
예제 #17
0
 public WebSocket(string uri, string subProtocol, List <KeyValuePair <string, string> > cookies, List <KeyValuePair <string, string> > customHeaderItems, string userAgent, string origin, WebSocketVersion version, EndPoint httpConnectProxy, System.Security.Authentication.SslProtocols sslProtocols)
 {
     m_SecureProtocols = sslProtocols;
     Initialize(uri, subProtocol, cookies, customHeaderItems, userAgent, origin, version, httpConnectProxy, 0);
 }
예제 #18
0
    public Boolean SendSessionedMail(Boolean UseSSL, Boolean UseMD5, System.Security.Authentication.SslProtocols protocol)
    {
        Message message = new Message();

        ServerCollection Hosts = null;
        int    Port            = 0;
        string UserName        = string.Empty;
        string Password        = string.Empty;
        bool   PORTExist       = false;

        try
        {
            if (Session["From"] != null)
            {
                message.From.Email = Session["From"].ToString();
            }
            else
            {
                return(false);
                //throw new Exception("From Email is a mandatory information");
            }
            if (Session["FromName"] != null)
            {
                message.From.Name = Session["FromName"].ToString();
            }
            else
            {
                return(false);
                //throw new Exception("From Name is a mandatory information");
            }

            if (Session["To"] != null)
            {
                message.To.AddRange((AddressCollection)Session["To"]);
            }
            else
            {
                return(false);
                //throw new Exception("Email to is a mandatory information");
            }
            if (Session["CC"] != null)
            {
                message.Cc.AddRange((AddressCollection)Session["CC"]);
            }


            if (Session["BCC"] != null)
            {
                message.Bcc.AddRange((AddressCollection)Session["BCC"]);
            }

            if (Session["Subject"] != null)
            {
                message.Subject = Session["Subject"].ToString();
            }
            else
            {
                //May not be needed
                //throw new Exception("Subject to is a mandatory information");
            }
            if (Session["BodyText"] != null)
            {
                message.BodyText.Text = Session["BodyText"].ToString();
            }

            if (Session["BodyHTML"] != null)
            {
                message.BodyHtml.Text = Session["BodyHTML"].ToString();
            }


            if (Session["Hosts"] != null)
            {
                Hosts = (ServerCollection)Session["Hosts"];
            }

            if (Session["Port"] != null)
            {
                Port      = (int)Session["Port"];
                PORTExist = true;
            }

            if (Session["User"] != null)
            {
                UserName = (string)Session["User"];
            }

            if (Session["Password"] != null)
            {
                Password = (string)Session["Password"];
            }

            //TODO - Need to find a way to manage multiple attachemnts
            // Session is not a solution as it will generate too much network traffic
            // Probably need to store it locally and associate with Session ID

            if (UserName.Length > 0 && Password.Length > 0 && Hosts.Count > 0 && UseSSL)
            {
                //Use SSL to send mail
                SmtpClient   smtpClient = new SmtpClient();
                SslHandShake handShake  = new SslHandShake(Hosts[0].Host, protocol);
                handShake.ServerCertificateValidationCallback = MyServerCertificateValidationCallback;
                message.Send(Hosts[0].Host, UserName, Password, UseMD5 ? SaslMechanism.CramMd5 : SaslMechanism.Login);
                return(true);
            }
            else if (UserName.Length > 0 && Password.Length > 0 && Hosts.Count > 0 && PORTExist)
            {
                //Use Authentication for sending mail
                message.Send(Hosts[0].Host, Port, UserName, Password, UseMD5 ? SaslMechanism.CramMd5 : SaslMechanism.Login);
                return(true);
            }
            else if ((UserName.Trim().Length == 0 || Password.Length == 0) && Hosts.Count > 0 && PORTExist)
            {
                //Use specified port for sending mail
                message.Send(Hosts[0].Host, Port);
                return(true);
            }
            else if ((UserName.Trim().Length == 0 || Password.Length == 0) && Hosts.Count > 0 && !PORTExist)
            {
                //Send without authentication
                message.Send(Hosts);
                return(true);
            }
            else
            {
                //Send directly without specifying a server
                message.DirectSend();
                return(true);
            }
            return(false);
        }
        catch (Exception ex)
        {
            return(false);
        }
        finally
        {
            message = null;
        }
    }
예제 #19
0
        /// <summary>
        /// Extends BeginAuthenticateAsClient so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// sslstream.BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, asyncCallback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginAuthenticateAsClient(this SslStream sslstream, String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation, AsyncCallback asyncCallback)
        {
            if (sslstream == null)
            {
                throw new ArgumentNullException("sslstream");
            }

            return(sslstream.BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, asyncCallback, null));
        }
예제 #20
0
 public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
     throw null;
 }
예제 #21
0
        /// <inheritdoc />
        public NetworkSender Create(string url, int maxQueueSize, System.Security.Authentication.SslProtocols sslProtocols, TimeSpan keepAliveTime)
        {
            if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
            {
                return(new HttpNetworkSender(url)
                {
                    MaxQueueSize = maxQueueSize,
                });
            }

            if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            {
                return(new HttpNetworkSender(url)
                {
                    MaxQueueSize = maxQueueSize,
                });
            }

            if (url.StartsWith("tcp://", StringComparison.OrdinalIgnoreCase))
            {
                return(new TcpNetworkSender(url, AddressFamily.Unspecified)
                {
                    MaxQueueSize = maxQueueSize,
                    SslProtocols = sslProtocols,
                    KeepAliveTime = keepAliveTime,
                });
            }

            if (url.StartsWith("tcp4://", StringComparison.OrdinalIgnoreCase))
            {
                return(new TcpNetworkSender(url, AddressFamily.InterNetwork)
                {
                    MaxQueueSize = maxQueueSize,
                    SslProtocols = sslProtocols,
                    KeepAliveTime = keepAliveTime,
                });
            }

            if (url.StartsWith("tcp6://", StringComparison.OrdinalIgnoreCase))
            {
                return(new TcpNetworkSender(url, AddressFamily.InterNetworkV6)
                {
                    MaxQueueSize = maxQueueSize,
                    SslProtocols = sslProtocols,
                    KeepAliveTime = keepAliveTime,
                });
            }

            if (url.StartsWith("udp://", StringComparison.OrdinalIgnoreCase))
            {
                return(new UdpNetworkSender(url, AddressFamily.Unspecified));
            }

            if (url.StartsWith("udp4://", StringComparison.OrdinalIgnoreCase))
            {
                return(new UdpNetworkSender(url, AddressFamily.InterNetwork));
            }

            if (url.StartsWith("udp6://", StringComparison.OrdinalIgnoreCase))
            {
                return(new UdpNetworkSender(url, AddressFamily.InterNetworkV6));
            }
            throw new ArgumentException("Unrecognized network address", nameof(url));
        }
예제 #22
0
 public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
     throw null;
 }
예제 #23
0
 public WebSocketWrapper(string url, string id = null, log4net.ILog log = null, System.Security.Authentication.SslProtocols sslProtocols = System.Security.Authentication.SslProtocols.Default)
 {
     this.url          = url;
     this.id           = id;
     this.Log          = log;
     this.sslProtocols = sslProtocols;
 }
예제 #24
0
 public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback asyncCallback, object asyncState)
 {
     throw null;
 }
 public virtual new IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, Object asyncState)
 {
     return(default(IAsyncResult));
 }
예제 #26
0
 public SslHandShake(string hostName, System.Security.Authentication.SslProtocols sslProtocol, System.Net.Security.RemoteCertificateValidationCallback serverCallback, System.Net.Security.LocalCertificateSelectionCallback clientCallback, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates) : this(hostName, sslProtocol, serverCallback, clientCallback, clientCertificates, false)
 {
 }
 public virtual new IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, Object asyncState)
 {
     return(default(IAsyncResult));
 }
예제 #28
0
 public SslHandShake(string hostName, System.Security.Authentication.SslProtocols sslProtocol) : this(hostName, sslProtocol, null, null, null, false)
 {
 }
예제 #29
0
        public static int ValidateHttpWebRequest(string server, int port, bool verbose, System.Security.Authentication.SslProtocols sslProtocols, string expected, out string actual)
        {
            var url = new Uri($"https://{server}:{port}/");

            if (verbose)
            {
                Console.WriteLine($"STARTING {server} protocol {sslProtocols}");
            }
            actual = "FAIL_NOT_SET!";

            ServicePointManager.DefaultConnectionLimit = 1;
            var startingProtocol = ServicePointManager.SecurityProtocol;

            if (sslProtocols != SslProtocolsExtensions.DontPassAnything)
            {
                // DontPassAnything really means don't set any value at all.
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)sslProtocols;
            }
            var sp = ServicePointManager.FindServicePoint(url);

            if (sp != null)
            {
                // Kill the old service point. Since in practice we only ever do a single test,
                // there shouldn't ever be an old service point and this code should never
                // be called.
                sp.ConnectionLimit = 1;
                sp.MaxIdleTime     = 0;
                int nopen = sp.CurrentConnections;
            }
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, change, policyerorrs) =>
            {
                // Always accept the certificate. This is only OK because
                // we're doing a test. In real code, accepting all certificates
                // is a terrible idea and causes security violations.
                return(true);
            };

            string step = "Starting";

            try
            {
                step = "Make WebRequest";
                var req = WebRequest.Create(url);
                step = "Get Response";
                WebResponse response = null;
                try
                {
                    response = req.GetResponse();
                }
                catch (Exception ex)
                {
                    var we = ex as WebException;
                    if (we != null && we.Status == WebExceptionStatus.SecureChannelFailure)
                    {
                        actual = "FAILED_TLS";
                    }
                    else
                    {
                        actual = $"FAIL_EXCEPTION_AT_GET_{ex.Message}";
                    }
                }
                if (response != null)
                {
                    var reader    = new StreamReader(response.GetResponseStream());
                    var data      = reader.ReadToEnd();
                    var dataitems = data.Split(new char[] { ' ' });
                    actual = dataitems[0];
                }
                step = "Close";
                step = "Done";
            }
            catch (Exception ex)
            {
                if (verbose)
                {
                    Console.WriteLine($"EXCEPTION at {step}: {ex.Message}");
                }
                actual = $"FAIL_EXCEPTION_AT{step}_{ex.Message}";
            }

            int Retval = 0;

            if (actual != expected && expected != Program.ExpectWasNotSet)
            {
                Retval = 1;
            }
            return(Retval);
        }
예제 #30
0
 public override void ResetSessionSecurity(IAppSession session, System.Security.Authentication.SslProtocols security)
 {
     throw new NotSupportedException();
 }
예제 #31
0
        // the listener thread's listen function
        // note: no maxConnections parameter. high level API should handle that.
        //       (Transport can't send a 'too full' message anyway)
        void Listen(int port)
        {
            // absolutely must wrap with try/catch, otherwise thread
            // exceptions are silent
            try
            {
                // start listener on all IPv4 and IPv6 address via .Create
                listener = TcpListener.Create(port);
                listener.Server.NoDelay     = NoDelay;
                listener.Server.SendTimeout = SendTimeout;
                listener.Start();
                Logger.Log("Server: listening port=" + port);

                X509Certificate cert           = null;
                bool            selfSignedCert = false;

                if (Encrypted)
                {
                    if (CertFile == null)
                    {
                        // Create a new self-signed certificate
                        selfSignedCert = true;
                        cert           =
                            new X509Certificate2Builder
                        {
                            SubjectName = string.Format("CN={0}", ((IPEndPoint)listener.LocalEndpoint).Address.ToString())
                        }.Build();
                    }
                    else
                    {
                        cert           = X509Certificate.CreateFromCertFile(CertFile);
                        selfSignedCert = false;
                    }
                }

                // keep accepting new clients
                while (true)
                {
                    // wait and accept new client
                    // note: 'using' sucks here because it will try to
                    // dispose after thread was started but we still need it
                    // in the thread
                    TcpClient client = listener.AcceptTcpClient();

                    // set socket options
                    client.NoDelay     = NoDelay;
                    client.SendTimeout = SendTimeout;

                    // generate the next connection id (thread safely)
                    int connectionId = NextConnectionId();

                    // add to dict immediately
                    ClientToken token = new ClientToken(client);
                    clients[connectionId] = token;

                    Stream stream = client.GetStream();

                    Thread sslAuthenticator = null;
                    if (Encrypted)
                    {
                        RemoteCertificateValidationCallback trustCert = (object sender, X509Certificate x509Certificate,
                                                                         X509Chain x509Chain, SslPolicyErrors policyErrors) =>
                        {
                            if (selfSignedCert)
                            {
                                // All certificates are accepted
                                return(true);
                            }
                            else
                            {
                                if (policyErrors == SslPolicyErrors.None)
                                {
                                    return(true);
                                }
                                else
                                {
                                    return(false);
                                }
                            }
                        };

                        SslStream sslStream = new SslStream(client.GetStream(), false, trustCert);
                        stream = sslStream;

                        sslAuthenticator = new Thread(() => {
                            try
                            {
                                // Using System.Security.Authentication.SslProtocols.None (the Microsoft recommended parameter which
                                // chooses the highest version of TLS) does not seem to work with Unity. Unity 2018.2 added support
                                // for TLS 1.2 when used with the .NET 4.x runtime, so use preprocessor directives to choose the right protocol
#if UNITY_2018_2_OR_NEWER && NET_4_6
                                System.Security.Authentication.SslProtocols protocol = System.Security.Authentication.SslProtocols.Tls12;
#else
                                System.Security.Authentication.SslProtocols protocol = System.Security.Authentication.SslProtocols.Default;
#endif

                                bool checkCertificateRevocation = !selfSignedCert;
                                sslStream.AuthenticateAsServer(cert, false, protocol, checkCertificateRevocation);
                            }
                            catch (Exception exception)
                            {
                                Logger.LogError("SSL Authenticator exception: " + exception);
                            }
                        });

                        sslAuthenticator.IsBackground = true;
                        sslAuthenticator.Start();
                    }

                    // spawn a send thread for each client
                    Thread sendThread = new Thread(() =>
                    {
                        // wrap in try-catch, otherwise Thread exceptions
                        // are silent
                        try
                        {
                            if (sslAuthenticator != null)
                            {
                                sslAuthenticator.Join();
                            }

                            // run the send loop
                            SendLoop(connectionId, client, stream, token.sendQueue, token.sendPending);
                        }
                        catch (ThreadAbortException)
                        {
                            // happens on stop. don't log anything.
                            // (we catch it in SendLoop too, but it still gets
                            //  through to here when aborting. don't show an
                            //  error.)
                        }
                        catch (Exception exception)
                        {
                            Logger.LogError("Server send thread exception: " + exception);
                        }
                    });
                    sendThread.IsBackground = true;
                    sendThread.Start();

                    // spawn a receive thread for each client
                    Thread receiveThread = new Thread(() =>
                    {
                        // wrap in try-catch, otherwise Thread exceptions
                        // are silent
                        try
                        {
                            if (sslAuthenticator != null)
                            {
                                sslAuthenticator.Join();
                            }

                            // run the receive loop
                            ReceiveLoop(connectionId, client, stream, receiveQueue, MaxMessageSize);

                            // remove client from clients dict afterwards
                            clients.TryRemove(connectionId, out ClientToken _);

                            // sendthread might be waiting on ManualResetEvent,
                            // so let's make sure to end it if the connection
                            // closed.
                            // otherwise the send thread would only end if it's
                            // actually sending data while the connection is
                            // closed.
                            sendThread.Interrupt();
                        }
                        catch (Exception exception)
                        {
                            Logger.LogError("Server client thread exception: " + exception);
                        }
                    });
                    receiveThread.IsBackground = true;
                    receiveThread.Start();
                }
            }
            catch (ThreadAbortException exception)
            {
                // UnityEditor causes AbortException if thread is still
                // running when we press Play again next time. that's okay.
                Logger.Log("Server thread aborted. That's okay. " + exception);
            }
            catch (SocketException exception)
            {
                // calling StopServer will interrupt this thread with a
                // 'SocketException: interrupted'. that's okay.
                Logger.Log("Server Thread stopped. That's okay. " + exception);
            }
            catch (Exception exception)
            {
                // something went wrong. probably important.
                Logger.LogError("Server Exception: " + exception);
            }
        }