Exemple #1
1
        private void Start()
        {
            try
            {
                Core.SystemForm.Status(messages.get("connecting", Core.SelectedLanguage));

                if (!SSL)
                {
                    _networkStream = new System.Net.Sockets.TcpClient(Server, Port).GetStream();
                    _StreamWriter = new System.IO.StreamWriter(_networkStream);
                    _StreamReader = new System.IO.StreamReader(_networkStream, Encoding.UTF8);
                }

                if (SSL)
                {
                    System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Server, Port);
                    _networkSsl = new System.Net.Security.SslStream(client.GetStream(), false,
                        new System.Net.Security.RemoteCertificateValidationCallback(Protocol.ValidateServerCertificate), null);
                    _networkSsl.AuthenticateAsClient(Server);
                    _StreamWriter = new System.IO.StreamWriter(_networkSsl);
                    _StreamReader = new System.IO.StreamReader(_networkSsl, Encoding.UTF8);
                }

                Connected = true;

                Send("hello");

                while (IsConnected && !_StreamReader.EndOfStream)
                {
                    try
                    {
                        string text = null;
                        while (Core.IsBlocked)
                        {
                            System.Threading.Thread.Sleep(100);
                        }

                        text = _StreamReader.ReadLine();
                        Core.trafficscanner.Insert(Server, " >> " + text);
                        Quassel_Parser parser = new Quassel_Parser(this, text);
                        parser.Proccess();
                    }
                    catch (IOException fail)
                    {
                        SystemWindow.scrollback.InsertText("Disconnected: " + fail.Message.ToString(), ContentLine.MessageStyle.System, false, 0);
                        Disconnect();
                    }
                }
            }
            catch (Exception h)
            {
                Core.handleException(h);
                Disconnect();
            }
        }
Exemple #2
0
 private void SetSocketAsConnected()
 {
     try {
         this.socketState = TcpSocketState.Connected;
         this.remoteIP    = ((System.Net.IPEndPoint) this.tcpClient.Client.RemoteEndPoint).Address;
         if (this.useSsl)
         {
             //send test stream with: cat dump.pcap | socat - SSL:localhost:57012,verify=0
             //socat GOPEN:dump.pcap SSL:localhost:57443,verify=0
             System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(tcpClient.GetStream(), false);
             //sslStream.ReadTimeout = idleTimeoutMS; //8 seconds
             sslStream.AuthenticateAsServer(ServerCert.Instance, false, System.Security.Authentication.SslProtocols.Default, false);
             this.pcapStream = sslStream;
         }
         else
         {
             this.pcapStream = this.tcpClient.GetStream();
         }
         this.pcapStream.ReadTimeout = this.idleTimeoutMS;
         //this.tcpClient.ReceiveTimeout = this.idleTimeoutMS;//not required, we do  stream.ReadTimeout instead
     }
     catch {
         this.Dispose();
     }
 }
Exemple #3
0
        public void Connect(string hostname, int port, bool ssl)
        {
            try {
                Host = hostname;
                Port = port;
                Ssl  = ssl;

                _Connection = new TcpClient(hostname, port);
                _Stream     = _Connection.GetStream();
                if (ssl)
                {
                    var sslSream = new System.Net.Security.SslStream(_Stream);
                    _Stream = sslSream;
                    sslSream.AuthenticateAsClient(hostname);
                }

                //Create a new thread to retrieve data (needed for Imap Idle).
                _ReadThread      = new Thread(ReceiveData);
                _ReadThread.Name = "_ReadThread";
                _ReadThread.Start();

                string info = _Responses.Take();
                OnConnected(info);

                IsConnected = true;
                Host        = hostname;
            } catch (Exception) {
                IsConnected = false;
                throw;
            }
        }
 public static IAsyncResult BeginAuthenticateAsServer(this System.Net.Security.SslStream stream
                                                      , System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate
                                                      , AsyncCallback callback, object state
                                                      )
 {
     return(stream.AuthenticateAsServerAsync(serverCertificate).AsApm(callback, state));
 }
		public virtual void Connect(string hostname, int port, bool ssl, System.Net.Security.RemoteCertificateValidationCallback validateCertificate) {
			try {
				Host = hostname;
				Port = port;
				Ssl = ssl;

				_Connection = new TcpClient(hostname, port);
				_Stream = _Connection.GetStream();
				if (ssl) {
					System.Net.Security.SslStream sslStream;
					if (validateCertificate != null)
						sslStream = new System.Net.Security.SslStream(_Stream, false, validateCertificate);
					else
						sslStream = new System.Net.Security.SslStream(_Stream, false);
					_Stream = sslStream;
					sslStream.AuthenticateAsClient(hostname);
				}

				OnConnected(GetResponse());

				IsConnected = true;
				Host = hostname;
			} catch (Exception) {
				IsConnected = false;
				Utilities.TryDispose(ref _Stream);
				throw;
			}
		}
Exemple #6
0
        public void Connect(string host, int port, bool useSsl, bool skipSslValidation)
        {
            System.Net.Security.RemoteCertificateValidationCallback validateCertificate = null;
            if (skipSslValidation)
                validateCertificate = (sender, cert, chain, err) => true;
            try
            {
                _Connection = new TcpClient(host, port);
                _Stream = _Connection.GetStream();
                if (useSsl)
                {
                    System.Net.Security.SslStream sslStream;
                    if (validateCertificate != null)
                        sslStream = new System.Net.Security.SslStream(_Stream, false, validateCertificate);
                    else
                        sslStream = new System.Net.Security.SslStream(_Stream, false);
                    _Stream = sslStream;
                    sslStream.AuthenticateAsClient(host);
                }

                OnConnected(GetResponse());

                IsConnected = true;
            }
            catch (Exception)
            {
                IsConnected = false;
                Utilities.TryDispose(ref _Stream);
                throw;
            }
        }
Exemple #7
0
        public void Connect(string hostname, int port, bool ssl)
        {
            try {
                Host = hostname;
                Port = port;
                Ssl  = ssl;

                _Connection = new TcpClient(hostname, port);
                _Stream     = _Connection.GetStream();
                if (ssl)
                {
                    var sslSream = new System.Net.Security.SslStream(_Stream);
                    _Stream = sslSream;
                    sslSream.AuthenticateAsClient(hostname);
                }

                _Reader = new StreamReader(_Stream, System.Text.Encoding.Default);
                string info = _Reader.ReadLine();
                OnConnected(info);

                IsConnected = true;
                Host        = hostname;
            } catch (Exception) {
                IsConnected = false;
                throw;
            }
        }
Exemple #8
0
        public void Connect(string hostname, int port, bool ssl, bool skipSslValidation)
        {
            try {
            Host = hostname;
            Port = port;
            Ssl = ssl;

            _Connection = new TcpClient(hostname, port);
            _Stream = _Connection.GetStream();
            if (ssl) {
            System.Net.Security.SslStream sslStream;
            if (skipSslValidation)
                sslStream = new System.Net.Security.SslStream(_Stream, false, (sender, cert, chain, err) => true);
            else
                sslStream = new System.Net.Security.SslStream(_Stream, false);
              _Stream = sslStream;
              sslStream.AuthenticateAsClient(hostname);
            }

            _Reader = new StreamReader(_Stream);
            string info = _Reader.ReadLine();
            OnConnected(info);

            IsConnected = true;
            Host = hostname;
              } catch (Exception) {
            IsConnected = false;
            Utilities.TryDispose(ref _Reader);
            Utilities.TryDispose(ref _Stream);
            throw;
              }
        }
Exemple #9
0
        private void startTLS()
        {
            transportStream = new System.Net.Security.SslStream(tcpClient.GetStream(), false
                                                                , new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate))
            {
                ReadTimeout  = IOTimeout,
                WriteTimeout = IOTimeout
            };

            // According to RFC 5425 we MUST support TLS 1.2, but this protocol version only implemented in framework 4.5 and Windows Vista+...
            ((System.Net.Security.SslStream)transportStream).AuthenticateAsClient(
                hostname,
                null,
                (System.Security.Authentication.SslProtocols)_sslProtocol,
                false
                );



            if (!((System.Net.Security.SslStream)transportStream).IsEncrypted)
            {
                throw new System.Security.SecurityException("Could not establish an encrypted connection");
            }

            messageTransfer = MessageTransfer.OctetCounting;
        }
Exemple #10
0
        public virtual void Connect(string hostname, int port, bool ssl, System.Net.Security.RemoteCertificateValidationCallback validateCertificate)
        {
            try {
                Host = hostname;
                Port = port;
                Ssl  = ssl;

                _Connection = new TcpClient(hostname, port);
                _Stream     = _Connection.GetStream();
                if (ssl)
                {
                    System.Net.Security.SslStream sslStream;
                    if (validateCertificate != null)
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false, validateCertificate);
                    }
                    else
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false);
                    }
                    _Stream = sslStream;
                    sslStream.AuthenticateAsClient(hostname);
                }

                OnConnected(GetResponse());

                IsConnected = true;
                Host        = hostname;
            } catch (Exception) {
                IsConnected = false;
                Utilities.TryDispose(ref _Stream);
                throw;
            }
        }
Exemple #11
0
        private Stream OpenNetworkStream()
        {
            Socket socket = CreateSocket();

            if (RequestUri.Scheme == "http")
            {
                int port = RequestUri.IsDefaultPort ? 80 : RequestUri.Port;
                socket.Connect(RequestUri.Host, port);

                return(new NetworkStream(socket));
            }
            else if (RequestUri.Scheme == "https")
            {
                int port = RequestUri.IsDefaultPort ? 443 : RequestUri.Port;
                socket.Connect(RequestUri.Host, port);

                var stream    = new NetworkStream(socket);
                var sslStream = new System.Net.Security.SslStream(stream);

                try {
                    sslStream.AuthenticateAsClient(RequestUri.Host);
                } catch (Exception ex) {
                    Booru.BooruApp.BooruApplication.Log.Log(Booru.BooruLog.Category.Network, ex, "Caught exception trying to open secure connection");
                }
                return(sslStream);
            }
            else
            {
                throw new InvalidDataException("unknown uri scheme " + RequestUri.Scheme);
            }
        }
Exemple #12
0
        public void Connect(string hostname, int port, bool ssl)
        {
            try {
            Host = hostname;
            Port = port;
            Ssl = ssl;

            _Connection = new TcpClient(hostname, port);
            _Stream = _Connection.GetStream();
            if (ssl) {
              var sslSream = new System.Net.Security.SslStream(_Stream);
              _Stream = sslSream;
              sslSream.AuthenticateAsClient(hostname);
            }

            _Reader = new StreamReader(_Stream, System.Text.Encoding.Default);
            string info = _Reader.ReadLine();
            OnConnected(info);

            IsConnected = true;
            Host = hostname;
              } catch (Exception) {
            IsConnected = false;
            throw;
              }
        }
Exemple #13
0
        public HttpConnection(Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
        {
            this.sock = sock;

            this.epl = epl;

            this.secure = secure;

            this.key = key;

            var networkstream = new NetworkStream(sock, false);

            if (secure)
            {
                var sslstream = new System.Net.Security.SslStream(networkstream);

                sslstream.AuthenticateAsServer(cert);

                stream = sslstream;
            }
            else
            {
                stream = networkstream;
            }

            timer = new Timer(OnTimeout, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);

            if (buffer == null)
            {
                buffer = new byte[BufferSize];
            }

            Init();
        }
        public void ConnectToGmail(string user, string pass)      //---#1 log in
        {
            try
            {
                tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);   // PORTS: TCP - 143. TCP/SSL - 993.
                ssl  = new System.Net.Security.SslStream(tcpc.GetStream());
                ssl.AuthenticateAsClient("imap.gmail.com");
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                Environment.Exit(0);
            }

            ReceiveResponse("");
            ReceiveResponse(prefix + " LOGIN " + user + " " + pass + " \r\n");

            if (answer.Contains("OK"))
            {
                userAvailable = true;
            }
            else
            {
                userAvailable = false;
            }
        }
Exemple #15
0
        static void Main(string[] args)
        {
            try
            {
                // there should be no gap between the imap command and the \r\n
                // ssl.read() -- while ssl.readbyte!= eof does not work because there is no eof from server
                // cannot check for \r\n because in case of larger response from server ex:read email message
                // there are lot of lines so \r \n appears at the end of each line
                //ssl.timeout sets the underlying tcp connections timeout if the read or write
                //time out exceeds then the undelying connection is closed
                tcpc = new System.Net.Sockets.TcpClient("imap.mail.ru", 993);

                ssl = new System.Net.Security.SslStream(tcpc.GetStream());
                ssl.AuthenticateAsClient("imap.mail.ru");
                receiveResponse("");

                Console.WriteLine("username : "******"password : "******"$ LOGIN " + username + " " + password + "\r\n");

                // Getting amount of Inbox
                String   inbox = receiveResponse("$ SELECT INBOX\r\n");
                string[] words = inbox.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
                words[1] = words[1].Trim(new char[] { ' ', 'E' }); // " xx EXISTS"
                string subString        = "EXISTS";
                int    indexOfSubstring = words[1].IndexOf(subString);
                words[1] = words[1].Substring(0, indexOfSubstring - 1); // "xx"
                int amount = Convert.ToInt32(words[1]);
                Console.WriteLine("Всего писем: " + amount + "\r\n");
                for (int i = 0; i < amount; i++)
                {
                    Console.WriteLine("Письмо №{0}" + ":", i + 1);
                    GetMail(i);
                }
                //receiveResponse("$ LOGOUT\r\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: " + ex.Message);
            }
            finally
            {
                if (ssl != null)
                {
                    ssl.Close();
                    ssl.Dispose();
                }
                if (tcpc != null)
                {
                    tcpc.Close();
                }
            }


            Console.ReadKey();
        }
Exemple #16
0
        public void Connect(string hostname, int port, bool ssl)
        {
            try {
            Host = hostname;
            Port = port;
            Ssl = ssl;

            _Connection = new TcpClient(hostname, port);
            _Stream = _Connection.GetStream();
            if (ssl) {
              var sslSream = new System.Net.Security.SslStream(_Stream);
              _Stream = sslSream;
              sslSream.AuthenticateAsClient(hostname);
            }

            //Create a new thread to retrieve data (needed for Imap Idle).
            _ReadThread = new Thread(ReceiveData);
            _ReadThread.Name = "_ReadThread";
            _ReadThread.Start();

            string info = _Responses.Take();
            OnConnected(info);

            IsConnected = true;
            Host = hostname;
              } catch (Exception) {
            IsConnected = false;
            throw;
              }
        }
Exemple #17
0
 internal static async Task <int> ReadAsync(this System.Net.Security.SslStream source,
                                            byte[] buffer, int offset, int count)
 {
     return(await Task.Factory.FromAsync(
                (c, s) => source.BeginRead(buffer, offset, count, c, s),
                (r) => source.EndRead(r),
                null).ConfigureAwait(false));
 }
Exemple #18
0
 internal static Task AuthenticateAsClientAsync(this System.Net.Security.SslStream source,
                                                string targetHost)
 {
     return(Task.Factory.FromAsync(
                (c, s) => source.BeginAuthenticateAsClient(targetHost, c, s),
                (r) => source.EndAuthenticateAsClient(r),
                null));
 }
Exemple #19
0
 internal static async Task AuthenticateAsClientAsync(this System.Net.Security.SslStream source,
                                                      string targetHost)
 {
     await Task.Factory.FromAsync(
         (c, s) => source.BeginAuthenticateAsClient(targetHost, c, s),
         (r) => source.EndAuthenticateAsClient(r),
         null).ConfigureAwait(false);
 }
Exemple #20
0
 internal static async Task AuthenticateAsServerAsync(this System.Net.Security.SslStream source,
                                                      System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate)
 {
     await Task.Factory.FromAsync(
         (c, s) => source.BeginAuthenticateAsServer(serverCertificate, c, s),
         (r) => source.EndAuthenticateAsServer(r),
         null).ConfigureAwait(false);
 }
Exemple #21
0
 internal static Task WriteAsync(this System.Net.Security.SslStream source,
                                 byte[] buffer, int offset, int count)
 {
     return(Task.Factory.FromAsync(
                (c, s) => source.BeginWrite(buffer, offset, count, c, s),
                (r) => source.EndWrite(r),
                null));
 }
Exemple #22
0
 internal static async Task WriteAsync(this System.Net.Security.SslStream source,
                                       byte[] buffer, int offset, int count)
 {
     await Task.Factory.FromAsync(
         (c, s) => source.BeginWrite(buffer, offset, count, c, s),
         (r) => source.EndWrite(r),
         null).ConfigureAwait(false);
 }
Exemple #23
0
        public void Connect(string address)
        {
            try
            {
                System.Net.Sockets.TcpClient tcp143 = new System.Net.Sockets.TcpClient();
                System.Net.Sockets.TcpClient tcp993 = new System.Net.Sockets.TcpClient();

                if (!tcp143.ConnectAsync(address, 143).Wait(1000))
                {
                    if (!tcp993.ConnectAsync(address, 993).Wait(1000))
                    {
                        throw new Exception("Connection timeout");
                    }
                    else
                    {
                        tcpc = tcp993;
                    }
                }
                else
                {
                    if (tcp143 != null)
                    {
                        tcpc = tcp143;
                        Read(true);
                        Write("CAPABILITIES");
                        if (Read(false).Contains("STARTTLS"))
                        {
                            Write("STARTTLS");
                        }
                        else
                        {
                            if (!tcp993.ConnectAsync(address, 993).Wait(1000))
                            {
                                throw new Exception("Connection not secure");
                            }
                            else
                            {
                                tcpc = tcp993;
                            }
                        }
                    }
                }

                ssl = new System.Net.Security.SslStream(tcpc.GetStream());
                ssl.AuthenticateAsClient(address);
                ssl.Flush();
                secure = true;
                Read(true);
            }
            catch (System.Net.Sockets.SocketException)
            {
                throw new Exception("Connection failed");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        // Reads a first int giving the global message's lenght, then reads the message.
        public ByteMessage(System.Net.Security.SslStream stream)
        {
            byte[] b_dataLenght = new byte[4];
            stream.Read(b_dataLenght, 0, 4);
            int dataLenght = BitConverter.ToInt32(b_dataLenght, 0);

            bytes = new byte[dataLenght];

            stream.Read(bytes, 0, dataLenght);
        }
Exemple #25
0
 internal static async Task AuthenticateAsServerAsync(this System.Net.Security.SslStream source,
                                                      System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate,
                                                      bool clientCertificateRequired,
                                                      System.Security.Authentication.SslProtocols enabledSslProtocols,
                                                      bool checkCertificateRevocation)
 {
     await Task.Factory.FromAsync(
         (c, s) => source.BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, c, s),
         (r) => source.EndAuthenticateAsServer(r),
         null).ConfigureAwait(false);
 }
Exemple #26
0
 internal static async Task AuthenticateAsClientAsync(this System.Net.Security.SslStream source,
                                                      string targetHost,
                                                      System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates,
                                                      System.Security.Authentication.SslProtocols enabledSslProtocols,
                                                      bool checkCertificateRevocation)
 {
     await Task.Factory.FromAsync(
         (c, s) => source.BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, c, s),
         (r) => source.EndAuthenticateAsClient(r),
         null).ConfigureAwait(false);
 }
Exemple #27
0
        /// <summary>
        /// Generates a new instance
        /// </summary>
        /// <param name="pTcpClient"></param>
        public Client(System.Net.Sockets.TcpClient pTcpClient)
        {
            m_pTcpClient = pTcpClient;
            m_pWorkerThread = new System.Threading.Thread(workerThread);

            // Initialize the SSL connection
            m_pSslStream = new System.Net.Security.SslStream(m_pTcpClient.GetStream(), false);
            m_pSslStream.AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile("Resources/Certificate.cer"), false, System.Security.Authentication.SslProtocols.Tls, false);

            m_pWorkerThread.Start();
        }
        /// <summary>
        /// Cria a stream para a uri no socket informado.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="socket"></param>
        /// <returns></returns>
        private async Task <System.IO.Stream> CreateStream(Uri uri, System.Net.Sockets.Socket socket)
        {
            System.IO.Stream stream = new System.Net.Sockets.NetworkStream(socket);
            if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                var sslStream = new System.Net.Security.SslStream(stream);
                await sslStream.AuthenticateAsClientAsync(uri.Host, new System.Security.Cryptography.X509Certificates.X509CertificateCollection(), _sslProtocols, checkCertificateRevocation : false);

                stream = sslStream;
            }
            return(stream);
        }
Exemple #29
0
        protected override void Write(System.Net.Security.SslStream ssl)
        {
            if (string.IsNullOrEmpty(Message))
            {
                return;
            }

            var writer = new StreamWriter(ssl);

            writer.WriteLine(Message, IdGenerator.GenerateId(), _account.Login, AccountHelper.ToInsecurePassword(_account.SecuredPassword));
            writer.Flush();
            this.Debug(string.Format(Message, "", _account.Login, "*******"));
        }
Exemple #30
0
 public AuthenticateAsyncState(
     System.Net.Security.SslStream stream,
     String targetHost,
     System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates,
     System.Security.Authentication.SslProtocols enabledSslProtocols,
     Boolean checkCertificateRevocation
     )
 {
     this.Stream                     = stream;
     this.TargetHost                 = targetHost;
     this.ClientCertificates         = clientCertificates;
     this.EnabledSslProtocols        = enabledSslProtocols;
     this.CheckCertificateRevocation = checkCertificateRevocation;
 }
Exemple #31
0
        public virtual void Connect(string hostname, int port, bool ssl, System.Net.Security.RemoteCertificateValidationCallback validateCertificate)
        {
            try {
                Host = hostname;
                Port = port;
                Ssl  = ssl;

                _Connection.SendTimeout    = this.Timeout;
                _Connection.ReceiveTimeout = this.Timeout;
                IAsyncResult ar = _Connection.BeginConnect(hostname, port, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(this.Timeout), true))
                    {
                        throw new TimeoutException(string.Format("Could not connect to {0} on port {1}.", hostname, port));
                    }
                    _Connection.EndConnect(ar);
                }
                finally
                {
                    wh.Close();
                }
                _Stream = _Connection.GetStream();
                if (ssl)
                {
                    System.Net.Security.SslStream sslStream;
                    if (validateCertificate != null)
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false, validateCertificate);
                    }
                    else
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false);
                    }
                    _Stream = sslStream;
                    sslStream.AuthenticateAsClient(hostname);
                }

                OnConnected(GetResponse());

                IsConnected = true;
                Host        = hostname;
            } catch (Exception) {
                IsConnected = false;
                Utilities.TryDispose(ref _Stream);
                throw;
            }
        }
Exemple #32
0
        protected override async Task <Stream> GetClientStreamAsync(Socket socket, CancellationToken cancellationToken)
        {
            var network = await base.GetClientStreamAsync(socket, cancellationToken).ConfigureAwait(false);

            if (!https)
            {
                return(network);
            }

            var ssl = new SslStream(network, false);

            await ssl.AuthenticateAsServerAsync(certificate, false, false).ConfigureAwait(false);

            return(ssl);
        }
 /// <summary>
 /// Saving a mail message before beeing sent by the SMTP client
 /// </summary>
 /// <param name="self">The caller</param>
 /// <param name="imapServer">The address of the IMAP server</param>
 /// <param name="imapPort">The port of the IMAP server</param>
 /// <param name="userName">The username to log on to the IMAP server</param>
 /// <param name="password">The password to log on to the IMAP server</param>
 /// <param name="sentFolderName">The name of the folder where the message will be saved</param>
 /// <param name="mailMessage">The message being saved</param>
 public static void SendAndSaveMessageToIMAP(this System.Net.Mail.SmtpClient self, System.Net.Mail.MailMessage mailMessage, string imapServer, int imapPort, string userName, string password, string sentFolderName)
 {
     try
     {
         path = System.Environment.CurrentDirectory + "\\emailresponse.txt";
         if (System.IO.File.Exists(path))
         {
             System.IO.File.Delete(path);
         }
         sw   = new System.IO.StreamWriter(System.IO.File.Create(path));
         tcpc = new System.Net.Sockets.TcpClient(imapServer, imapPort);
         ssl  = new System.Net.Security.SslStream(tcpc.GetStream());
         ssl.AuthenticateAsClient(imapServer);
         SendCommandAndReceiveResponse("");
         SendCommandAndReceiveResponse(string.Format("$ LOGIN {1} {2}  {0}", System.Environment.NewLine, userName, password));
         using (var m = mailMessage.RawMessage())
         {
             m.Position = 0;
             var sr    = new System.IO.StreamReader(m);
             var myStr = sr.ReadToEnd();
             SendCommandAndReceiveResponse(string.Format("$ APPEND {1} (\\Seen) {{{2}}}{0}", System.Environment.NewLine, sentFolderName, myStr.Length));
             SendCommandAndReceiveResponse(string.Format("{1}{0}", System.Environment.NewLine, myStr));
         }
         SendCommandAndReceiveResponse(string.Format("$ LOGOUT{0}", System.Environment.NewLine));
     }
     catch (System.Exception ex)
     {
         System.Diagnostics.Debug.WriteLine("error: " + ex.Message);
     }
     finally
     {
         if (sw != null)
         {
             sw.Close();
             sw.Dispose();
         }
         if (ssl != null)
         {
             ssl.Close();
             ssl.Dispose();
         }
         if (tcpc != null)
         {
             tcpc.Close();
         }
     }
     self.Send(mailMessage);
 }
Exemple #34
0
 protected virtual void DoSslHandShake(ActiveUp.Net.Security.SslHandShake sslHandShake)
 {
     ActiveUp.Net.Mail.Logger.AddEntry("DoSslHandShake:Creating SslStream...", 2);
     this._sslStream = new System.Net.Security.SslStream(base.GetStream(), false, sslHandShake.ServerCertificateValidationCallback, sslHandShake.ClientCertificateSelectionCallback);
     ActiveUp.Net.Mail.Logger.AddEntry("DoSslHandShake:AuthenticateAsClient...", 2);
     try
     {
         this._sslStream.AuthenticateAsClient(sslHandShake.HostName, sslHandShake.ClientCertificates, sslHandShake.SslProtocol, sslHandShake.CheckRevocation);
     }
     catch (Exception ex)
     {
         ActiveUp.Net.Mail.Logger.AddEntry(string.Format("DoSslHandShake:AuthenticateAsClient failed with Exception {0}", ex.ToString()), 2);
         this._sslStream = null;
         throw;
     }
 }
Exemple #35
0
        /// <todo />
        public static Task AuthenticateAsClientAsync(
            this System.Net.Security.SslStream stream,
            String targetHost,
            System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates,
            System.Security.Authentication.SslProtocols enabledSslProtocols,
            Boolean checkCertificateRevocation
            )
        {
            var authArgs = new AuthenticateAsyncState(stream, targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);

            return(Task.Factory.FromAsync(
                       (aArgs, cb, state) => aArgs.Stream.BeginAuthenticateAsClient(aArgs.TargetHost, aArgs.ClientCertificates, aArgs.EnabledSslProtocols, aArgs.CheckCertificateRevocation, cb, state),
                       result => ((System.Net.Security.SslStream)result.AsyncState).EndAuthenticateAsClient(result),
                       authArgs,
                       stream
                       ));
        }
Exemple #36
0
 internal void traceStream(System.Net.Security.SslStream stream, string connInfo)
 {
     System.Text.StringBuilder s = new System.Text.StringBuilder();
     s.Append("SSL connection summary");
     if (connInfo.Length > 0)
     {
         s.Append("\n");
         s.Append(connInfo);
     }
     s.Append("\nauthenticated = " + (stream.IsAuthenticated ? "yes" : "no"));
     s.Append("\nencrypted = " + (stream.IsEncrypted ? "yes" : "no"));
     s.Append("\nsigned = " + (stream.IsSigned ? "yes" : "no"));
     s.Append("\nmutually authenticated = " + (stream.IsMutuallyAuthenticated ? "yes" : "no"));
     s.Append("\nhash algorithm = " + stream.HashAlgorithm + "/" + stream.HashStrength);
     s.Append("\ncipher algorithm = " + stream.CipherAlgorithm + "/" + stream.CipherStrength);
     s.Append("\nkey exchange algorithm = " + stream.KeyExchangeAlgorithm + "/" + stream.KeyExchangeStrength);
     s.Append("\nprotocol = " + stream.SslProtocol);
     _logger.trace(_securityTraceCategory, s.ToString());
 }
Exemple #37
0
 public int Connect()
 {
     try
     {
         tcpc            = new System.Net.Sockets.TcpClient(Host, Port);
         ssl             = new System.Net.Security.SslStream(tcpc.GetStream());
         ssl.ReadTimeout = 2000;
         ssl.AuthenticateAsClient(Host);
         receiveResponse("");
         commandNumber = 0;
         currentState  = IMAPState.NotAuthenticated;
         return(0);
     }
     catch (Exception ex)
     {
         currentState = IMAPState.NoConnection;
         return(-1);
     }
 }
Exemple #38
0
    public Task ConnectAsync()
    {
        this.sock.Connect(this.Host, this.Port);

        if (this.secure)
        {
            this.sslStream = new System.Net.Security.SslStream(this.sock.GetStream(), true, new RemoteCertificateValidationCallback(ValidateServerCertificate));
            this.sslStream.AuthenticateAsClient(this.Host);

            this.streamRead = new StreamReader(this.sslStream);
            this.streamWriter = new StreamWriter(this.sslStream);
        }
        else
        {
            this.streamRead = new StreamReader(this.sock.GetStream());
            this.streamWriter = new StreamWriter(this.sock.GetStream());
        }
        this.streamWriter.AutoFlush = true;

        return new Task(new Action(nope));
    }
Exemple #39
0
        public int Authenticate()
        {
            int s = 0, n;
            try
            {
                if (StartTls)
                {
                    string text = "STARTTLS\r\n";
                    ns_client.Write(UTF8.GetBytes(text), 0, UTF8.GetByteCount(text));
                    Chunk c = CreateChunk(512);
                    n = ns_client.Read(c.buffer, 0, c.size);
                    text = UTF8.GetString(c.buffer, 0, n);
                    //Console.WriteLine(text);

                    ssl_stream = new System.Net.Security.SslStream(ns_client);
                    ssl_stream.AuthenticateAsClient(Host, null, System.Security.Authentication.SslProtocols.Tls12, false);

                    text = "EHLO " + Host + "\r\n";
                    ssl_stream.Write(UTF8.GetBytes(text), 0, UTF8.GetByteCount(text));
                    ResetChunk(ref c, 512);
                    n = ssl_stream.Read(c.buffer, 0, c.size);
                    text = UTF8.GetString(c.buffer, 0, n);

                    IsAuthenticationRequired = false;
                    AuthenticationMethod = new List<string>();

                    string[] cond = text.Split('\n');
                    for (int i = 0; i < cond.Length; i++)
                    {
                        if (cond[i].Contains("SIZE"))
                        {
                            int m = 0;
                            int.TryParse(cond[i].Substring(cond[i].IndexOf("SIZE") + 4, cond[i].Length - cond[i].IndexOf("SIZE") - 4 - 1).Trim(), out m);
                            MaximumSize = m;
                        }
                        if (cond[i].Contains("AUTH"))
                        {
                            IsAuthenticationRequired = true;
                            text = cond[i].Substring(cond[i].IndexOf("AUTH") + 4, cond[i].Length - cond[i].IndexOf("AUTH") - 4 - 1).Trim();
                            foreach (string item in text.Split(' '))
                                AuthenticationMethod.Add(item);
                        }
                    }

                    if (AuthenticationMethod.Contains("PLAIN"))
                    {
                        text = "AUTH PLAIN\r\n";
                        ssl_stream.Write(UTF8.GetBytes(text), 0, UTF8.GetByteCount(text));
                        ResetChunk(ref c);
                        n = ssl_stream.Read(c.buffer, 0, c.size);
                        text = UTF8.GetString(c.buffer, 0, n);
                        if (!text.StartsWith("334"))
                            return s = 1;

                        text = UserID + '\0' + UserName + '\0' + Password;
                        text = Convert.ToBase64String(UTF8.GetBytes(text)) + "\r\n";
                        ssl_stream.Write(UTF8.GetBytes(text), 0, UTF8.GetByteCount(text));
                        ResetChunk(ref c);
                        n = ssl_stream.Read(c.buffer, 0, c.size);
                        text = UTF8.GetString(c.buffer, 0, n);
                        if (!text.StartsWith("235"))
                            return s = 2;
                    }
                }
            }
            catch (Exception)
            {
                s = -1;
            }

            return s;
        }
Exemple #40
0
 public async Task AuthenticateAsClientAsync(string targethost) {
     ssl = new System.Net.Security.SslStream(UnderlyingStream, false, (s, c, h, l) => true, null);
     await ssl.AuthenticateAsClientAsync(targethost, null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Ssl3, false);
     UnderlyingStream = ssl;
 }
Exemple #41
0
 private void DoSslHandShake(ActiveUp.Net.Security.SslHandShake sslHandShake)
 {
     this._sslStream = new System.Net.Security.SslStream(base.GetStream(), false, sslHandShake.ServerCertificateValidationCallback, sslHandShake.ClientCertificateSelectionCallback);
     this._sslStream.AuthenticateAsClient(sslHandShake.HostName, sslHandShake.ClientCertificates, sslHandShake.SslProtocol, sslHandShake.CheckRevocation);
 }
Exemple #42
0
        private void DoSslHandShake(ActiveUp.Net.Security.SslHandShake sslHandShake)
        {
            this._sslStream = new System.Net.Security.SslStream(base.GetStream(), false, sslHandShake.ServerCertificateValidationCallback, sslHandShake.ClientCertificateSelectionCallback);
            bool authenticationFailed = false;
            try
            {
                this._sslStream.AuthenticateAsClient(sslHandShake.HostName, sslHandShake.ClientCertificates, sslHandShake.SslProtocol, sslHandShake.CheckRevocation);
            }
            catch (Exception)
            {
                authenticationFailed = true;
            }

            if (authenticationFailed)
            {
                System.Net.ServicePointManager.CertificatePolicy = new ActiveUp.Net.Security.TrustAllCertificatePolicy();
                this._sslStream.AuthenticateAsClient(sslHandShake.HostName, sslHandShake.ClientCertificates, sslHandShake.SslProtocol, sslHandShake.CheckRevocation);
            }

        }
Exemple #43
0
 public async Task AuthenticateAsClientAsync(string targethost, System.Net.Security.RemoteCertificateValidationCallback validationCallback) {
     ssl = new System.Net.Security.SslStream(UnderlyingStream, false, validationCallback, null);
     await ssl.AuthenticateAsClientAsync(targethost, null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Ssl3, false);
     UnderlyingStream = ssl;
 }
Exemple #44
0
 public void AuthenticateAsServer(X509Certificate certificate) {
     ssl = new System.Net.Security.SslStream(UnderlyingStream);
     ssl.AuthenticateAsServer(certificate, false, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Ssl3,
                              false);
     UnderlyingStream = ssl;
 }
Exemple #45
0
        public virtual void Connect(string hostname, int port, bool ssl, System.Net.Security.RemoteCertificateValidationCallback validateCertificate)
        {
            try {
                Host = hostname;
                Port = port;
                Ssl = ssl;

                _Connection.SendTimeout = this.Timeout;
                _Connection.ReceiveTimeout = this.Timeout;
                IAsyncResult ar = _Connection.BeginConnect(hostname, port, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(this.Timeout), true))
                    {
                        throw new TimeoutException(string.Format("Could not connect to {0} on port {1}.", hostname, port));
                    }
                    _Connection.EndConnect(ar);
                }
                finally
                {
                    wh.Close();
                }
                _Stream = _Connection.GetStream();
                if (ssl) {
                    System.Net.Security.SslStream sslStream;
                    if (validateCertificate != null)
                        sslStream = new System.Net.Security.SslStream(_Stream, false, validateCertificate);
                    else
                        sslStream = new System.Net.Security.SslStream(_Stream, false);
                    _Stream = sslStream;
                    sslStream.AuthenticateAsClient(hostname);
                }

                OnConnected(GetResponse());

                IsConnected = true;
                Host = hostname;
            } catch (Exception) {
                IsConnected = false;
                Utilities.TryDispose(ref _Stream);
                throw;
            }
        }
Exemple #46
0
        /// <summary>
        /// Sends the message via a socket connection to an SMTP relay host. 
        /// </summary>
        /// <param name="hostname">Friendly-name or IP address of SMTP relay host</param>
        /// <param name="port">Port on which to connect to SMTP relay host</param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        private void SendSSL(string HostName, int Port, string UserName, string Password, string FromEmail, string ToEmail, byte[] MIMEMessage)
        {
            //This Doesn't Work Yet... :(

            const int bufsize = 1000;
            TcpClient smtp;
            System.Net.Security.SslStream ns;
            int cb, startOfBlock;
            byte[] recv = new byte[bufsize];
            byte[] data;
            string message, block;

            try
            {

                smtp = new TcpClient(HostName, Port);
                ns = new System.Net.Security.SslStream(smtp.GetStream(), true);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                message = "EHLO\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
            }
            catch(Exception ex)
            {
                throw new Exception(string.Format("Unable to establish SMTP session with {0}:{1}", HostName, Port), ex);
            }

            try
            {

                //figure out the line containing 250-AUTH
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                startOfBlock = message.IndexOf("250-AUTH");
                block = message.Substring(startOfBlock, message.IndexOf("\n", startOfBlock) - startOfBlock);
                //check the auth protocols
                if (-1 == block.IndexOf("LOGIN"))
                    throw new Exception("Mailhost does not support LOGIN authentication");

                message = "AUTH LOGIN\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("334"))
                    throw new Exception(string.Format("Unexpected reply to AUTH LOGIN:\n{0}", message));

                message = string.Format("{0}\r\n", Convert.ToBase64String(Encoding.ASCII.GetBytes(UserName)));
                System.Diagnostics.Debug.WriteLine(message, "Client (username)");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("334"))
                    throw new Exception(string.Format("Unexpected reply to username:\n{0}", message));

                message = string.Format("{0}\r\n", Convert.ToBase64String(Encoding.ASCII.GetBytes(Password)));
                System.Diagnostics.Debug.WriteLine(message, "Client (password)");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (message.StartsWith("535"))
                    throw new Exception("Authentication unsuccessful");
                if (!message.StartsWith("2"))
                    throw new Exception(string.Format("Unexpected reply to password:\n{0}", message));

                message = string.Format("MAIL FROM: <{0}>\r\n", FromEmail);
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("250"))
                    throw new Exception(string.Format("Unexpected reply to MAIL FROM:\n{0}", message));

                message = string.Format("RCPT TO: <{0}>\r\n", ToEmail);
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("250"))
                    throw new Exception(string.Format("Unexpected reply to RCPT TO:\n{0}", message));

                message = "DATA\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("354"))
                    throw new Exception(string.Format("Unexpected reply to DATA:\n{0}", message));

                data = MIMEMessage;
                ns.Write(data, 0, data.Length);
                message = "\r\n.\r\n";
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);

                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("250"))
                    throw new Exception(string.Format("Unexpected reply to end of data marker (\\r\\n.\\r\\n):\n{0}", message));

                message = "QUIT\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);

            }
            catch (Exception ex)
            {
                General.Debugging.Report.SendError("SMTP Communication Error", ex);
                throw new Exception(string.Format("SMTP Communication Error: {0}", message), ex);
            }
            finally
            {
                if (null != smtp) smtp.Close();
            }
        }
Exemple #47
0
 private static void Authenticate(Profile user)
 {
     tcpc = new TcpClient("imap." + user.Server, 993);
     ssl = new System.Net.Security.SslStream(tcpc.GetStream());
     ssl.AuthenticateAsClient("imap." + user.Server);
     ImapRequest("$ LOGIN " + user.Adress + " " + user.Password + "\r\n");
 }
        // Get a TLS stream ...
        private Stream GetTlsStream()
        {
            // An outdated (?) mono only SSL class...
#if MONO_BUILD               
            Mono.Security.Protocol.Tls.SslClientStream sssl =
                 new Mono.Security.Protocol.Tls.SslClientStream(stream, server, true);
            if(sssl != null)
            {   if(tlsmode != TlsModeEnum.Required)
                    // hook server certificate validation to ignore errors
                    sssl.ServerCertValidationDelegate =
                        new Mono.Security.Protocol.Tls.CertificateValidationCallback(ValCert);

                // dummy write to cause TLS handshake
                byte[] data = {}; 
                sssl.Write(data, 0, 0);
                return sssl;
            }
            // Works for Windows and mono (partially)...
#else
            System.Net.Security.SslStream sssl = new System.Net.Security.SslStream(stream, true, //false,
                new System.Net.Security.RemoteCertificateValidationCallback(ValCert));
            if(sssl != null)
            {   sssl.AuthenticateAsClient(server);
                return sssl;
            }
#endif
            RaiseError(ZIMapException.Error.CannotConnect, "No TLS support available: " + server);
            return null;
        }
Exemple #49
0
        /// <summary>
        /// Sends request to Clusterpoint Server. Returned CPS_Response should be casted to command-specific response class.
        /// </summary>
        /// <param name="request">Request to send.</param>
        /// <returns>Command-specific CPS_Response object instance.</returns>
        public CPS_Response sendRequest(CPS_Request request)
        {
            bool firstSend = true;
            string previousRenderedStorage = "";
            string requestXml = "";
            byte[] requestBytes = null;
            string rawResponse = "";
            bool quit = true;

            if (this.p_connectionSwitcher != null)
                this.p_connectionSwitcher.newRequest(request);

            do
            {
                CPS_Exception e = null;

                if (this.p_connectionSwitcher != null)
                    this.p_connectionString = this.parseConnectionString(this.p_connectionSwitcher.getConnectionString(ref this.p_storageName));

                try
                {
                    if (this.p_transactionId != null)
                        request.setParam("transaction_id", this.p_transactionId);
                    if (firstSend || previousRenderedStorage != this.p_storageName)
                    {
                        requestXml = this.renderRequest(request);
                        requestBytes = Encoding.UTF8.GetBytes(requestXml);
                        previousRenderedStorage = this.p_storageName;

                        if (this.p_debug)
                        {
                            FileStream fs = new FileStream("request.xml", FileMode.Create);
                            fs.Write(requestBytes, 0, requestBytes.Length);
                            fs.Close();
                        }
                    }
                    firstSend = false;

                    this.p_lastRequestSize = requestXml.Length;
                    this.p_lastNetworkDuration = 0;

                    Stopwatch totTimer = new Stopwatch();
                    Stopwatch netTimer = new Stopwatch();

                    totTimer.Start();
                    if (this.p_connectionString.Scheme.ToLower() == "http")
                    {
                        // TODO: implement HMAC support when server side supports it
                        HttpWebRequest webreq = (HttpWebRequest)HttpWebRequest.Create(this.p_connectionString.OriginalString);
                        webreq.UserAgent = this.p_applicationId;
                        webreq.Method = "POST";
                        webreq.ContentType = "application/x-www-form-urlencoded";
                        webreq.ContentLength = requestBytes.Length;
                        webreq.Headers["Recipient"] = this.p_storageName;
                        webreq.Proxy = null;

                        Stream webreq_data;
                        try
                        {
                            webreq_data = webreq.GetRequestStream();
                        }
                        catch (Exception)
                        {
                            throw new CPS_Exception("Invalid connection string").SetCode(CPS_Exception.ERROR_CODE.INVALID_CONNECTION_STRING);
                        }

                        netTimer.Start();
                        webreq_data.Write(requestBytes, 0, requestBytes.Length);
                        webreq_data.Close();
                        netTimer.Stop();

                        HttpWebResponse webrsp;
                        try
                        {
                            webrsp = (HttpWebResponse)webreq.GetResponse();
                        }
                        catch (Exception)
                        {
                            throw new CPS_Exception("Invalid connection string").SetCode(CPS_Exception.ERROR_CODE.INVALID_CONNECTION_STRING);
                        }
                        Stream webrsp_data = webrsp.GetResponseStream();
                        StreamReader webrsp_reader = new StreamReader(webrsp_data);

                        netTimer.Start();
                        rawResponse = webrsp_reader.ReadToEnd();
                        webrsp_reader.Close();
                        netTimer.Stop();
                    }

                    if (this.p_connectionString.Scheme.ToLower() == "tcp" || this.p_connectionString.Scheme.ToLower() == "tcps")
                    {
                        int port = this.p_connectionString.Port;
                        if (port <= 0)
                            port = 5550;
                        TcpClient tcp;
                        try
                        {
                            netTimer.Start();
                            tcp = new TcpClient(this.p_connectionString.Host, port);
                            netTimer.Stop();
                        }
                        catch (SocketException)
                        {
                            netTimer.Stop();
                            throw new CPS_Exception("Cannot connect to specified server").SetCode(CPS_Exception.ERROR_CODE.SOCKET_ERROR);
                        }
                        catch (Exception) // all other cases
                        {
                            netTimer.Stop();
                            throw new CPS_Exception("Invalid connection string").SetCode(CPS_Exception.ERROR_CODE.INVALID_CONNECTION_STRING);
                        }

                        NetworkStream net = tcp.GetStream();
                        System.IO.Stream strm = net;

                        if (this.p_connectionString.Scheme.ToLower() == "tcps")
                        {
                            System.Net.Security.SslStream ssl = new System.Net.Security.SslStream(strm, false, new System.Net.Security.RemoteCertificateValidationCallback(ConnectionServerValidationCallback), null);

                            try
                            {
                                ssl.AuthenticateAsClient(this.p_connectionString.Host);
                            }
                            catch (Exception)
                            {
                                throw new CPS_Exception("Error establishing SSL connection").SetCode(CPS_Exception.ERROR_CODE.SSL_HANDSHAKE);
                            }

                            strm = ssl;
                        }

                        Protobuf pb = new Protobuf();
                        pb.CreateField(1, Protobuf.WireType.LengthDelimited, requestBytes);
                        pb.CreateStringField(2, this.p_storageName);

                        if (this.p_hmacUserKey != null && this.p_hmacSignKey != null)
                        {
                            string characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                            char[] tokenchars = new char[16];
                            for (int i = 0; i < 16; i++)
                                tokenchars[i] = characters[this.p_random.Next(characters.Length)];
                            string token = new string(tokenchars);

                            System.DateTime epoch = new System.DateTime(1970, 1, 1, 0, 0, 0, 0).ToUniversalTime();
                            System.DateTime validity = System.DateTime.Now.ToUniversalTime();
                            validity.AddSeconds(10);
                            System.TimeSpan dtdiff = validity - epoch;
                            UInt64 unixvalidity = (UInt64)dtdiff.TotalSeconds;

                            pb.CreateStringField(14, token);
                            pb.CreateFixed64Field(15, unixvalidity);
                            pb.CreateStringField(16, this.p_hmacUserKey);
                            pb.CreateStringField(17, CPS_Hasher.SHA1(CPS_Hasher.SHA1(requestXml) + token + unixvalidity + this.p_hmacSignKey));
                            pb.CreateStringField(18, CPS_Hasher.SHA1_HMAC(this.p_hmacSignKey, requestXml + token + unixvalidity));
                        }

                        MemoryStream ms = new MemoryStream();
                        Protobuf_Streamer pbs = new Protobuf_Streamer(ms);
                        pb.WriteToStream(pbs);

                        byte[] header = CPS_Length2Header((int)(ms.Length));

                        netTimer.Start();
                        try
                        {
                            strm.Write(header, 0, 8);
                            strm.Write(ms.GetBuffer(), 0, (int)(ms.Length));
                        }
                        catch (Exception)
                        {
                            netTimer.Stop();
                            throw new CPS_Exception("Error sending request").SetCode(CPS_Exception.ERROR_CODE.SOCKET_ERROR);
                        }
                        strm.Flush();

                        try
                        {
                            strm.Read(header, 0, 8);
                            netTimer.Stop();
                        }
                        catch (Exception)
                        {
                            netTimer.Stop();
                            throw new CPS_Exception("Error receiving response").SetCode(CPS_Exception.ERROR_CODE.SOCKET_ERROR);
                        }

                        int len = CPS_Header2Length(header);
                        if (len <= 0)
                            throw new CPS_Exception("Invalid response from server").SetCode(CPS_Exception.ERROR_CODE.INVALID_RESPONSE);

                        byte[] recv = new byte[len];
                        int got = 0;
                        netTimer.Start();
                        while (got < len)
                        {
                            int br = 0;
                            try
                            {
                                br = strm.Read(recv, got, len - got);
                                if (br == 0)
                                {
                                    netTimer.Stop();
                                    throw new CPS_Exception("Server unexpectedly closed connection").SetCode(CPS_Exception.ERROR_CODE.SOCKET_ERROR);
                                }
                            }
                            catch (Exception)
                            {
                                netTimer.Stop();
                                throw new CPS_Exception("Error receiving response").SetCode(CPS_Exception.ERROR_CODE.SOCKET_ERROR);
                            }
                            got += br;
                        }
                        strm.Close();
                        netTimer.Stop();

                        ms = new MemoryStream(recv);
                        pbs = new Protobuf_Streamer(ms);
                        pb = new Protobuf(pbs);

                        rawResponse = pb.GetStringField(1);
                    }
                    totTimer.Stop();

                    this.p_lastRequestDuration = totTimer.ElapsedMilliseconds;
                    this.p_lastRequestDuration = this.p_lastRequestDuration / 1000.0;

                    this.p_lastNetworkDuration = netTimer.ElapsedMilliseconds;
                    this.p_lastNetworkDuration = this.p_lastNetworkDuration / 1000.0;

                    this.p_lastResponseSize = rawResponse.Length;

                    if (this.p_debug)
                    {
                        FileStream fs = new FileStream("response.xml", FileMode.Create);
                        byte[] responseBytes = Encoding.UTF8.GetBytes(rawResponse);
                        fs.Write(responseBytes, 0, responseBytes.Length);
                        fs.Close();
                    }
                }
                catch (CPS_Exception e_)
                {
                    e = e_;
                }

                if (this.p_connectionSwitcher != null)
                    quit = !this.p_connectionSwitcher.shouldRetry(rawResponse, e);
                else
                    quit = true;

                if (quit && e != null)
                    throw e;
            }
            while (!quit);

            switch (request.getCommand())
            {
                case "search":
                case "similar":
                    return new CPS_SearchResponse(this, request, rawResponse);
                case "update":
                case "delete":
                case "replace":
                case "partial-replace":
                case "partial-xreplace":
                case "insert":
                case "create-alert":
                case "update-alerts":
                case "delete-alerts":
                    return new CPS_ModifyResponse(this, request, rawResponse);
                case "alternatives":
                    return new CPS_AlternativesResponse(this, request, rawResponse);
                case "list-words":
                    return new CPS_ListWordsResponse(this, request, rawResponse);
                case "status":
                    return new CPS_StatusResponse(this, request, rawResponse);
                case "retrieve":
                case "list-last":
                case "list-first":
                case "retrieve-last":
                case "retrive-first":
                case "lookup":
                case "show-history":
                    return new CPS_LookupResponse(this, request, rawResponse);
                case "search-delete":
                    return new CPS_SearchDeleteResponse(this, request, rawResponse);
                case "list-paths":
                    return new CPS_ListPathsResponse(this, request, rawResponse);
                case "list-facets":
                    return new CPS_ListFacetsResponse(this, request, rawResponse);
                case "list-alerts":
                    return new CPS_Response(this, request, rawResponse);
                    // TODO: change this !!!
                default:
                    CPS_Response ret = new CPS_Response(this, request, rawResponse);
                    // This is explicitly processed here, because of .NET limitations. PHP API changes this directly from CPS_Response constructor.
                    if (request.getCommand() == "begin-transaction" || request.getCommand() == "commit-transaction" || request.getCommand() == "rollback-transaction")
                        this.p_transactionId = ret.getTransactionId();
                    return ret;
            }
        }
Exemple #50
0
        /// <summary>
        /// Attempts to connect to given server
        /// </summary>
        /// <param name="strIPAddress"></param>
        /// <param name="nPort"></param>
        /// <param name="bSslEnabled"></param>
        /// <param name="nClientRecvType"></param>
        /// <returns></returns>
        public bool connect(string strIPAddress, int nPort, bool bSslEnabled = true, ClientType nClientType = ClientType.CLIENTTYPE_SERIALIZEDOBJECT)
        {
            m_pTcpClient = new System.Net.Sockets.TcpClient();
            m_bSslEnabled = bSslEnabled;
            m_nClientType = nClientType;

            try
            {
                m_pTcpClient.Connect(strIPAddress, nPort);
            }
            catch
            {
                return false;
            }

            if (m_bSslEnabled)
            {
                // Initialize SSL
                m_pSslStream = new System.Net.Security.SslStream(m_pTcpClient.GetStream(), false, new System.Net.Security.RemoteCertificateValidationCallback(validateServerCertificate), null);

                try
                {
                    m_pSslStream.AuthenticateAsClient(strIPAddress);
                }
                catch
                {
                    return false;
                }
            }

            // Initialize handler object
            switch (m_nClientType)
            {
                case ClientType.CLIENTTYPE_SERIALIZEDOBJECT:

                    m_pInHandlerObj = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    m_pOutHandlerObj = m_pInHandlerObj;

                    break;
                case ClientType.CLIENTTYPE_STRING:

                    m_pInHandlerObj = new System.IO.StreamReader(getStream());
                    m_pOutHandlerObj = new System.IO.StreamWriter(getStream());

                    ((System.IO.StreamWriter)m_pOutHandlerObj).AutoFlush = true;

                    break;
            }

            m_pWorkerThread = new System.Threading.Thread(workerThread);
            m_pWorkerThread.Start();

            return true;
        }
Exemple #51
0
        public HttpConnection(Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
        {
            this.sock   = sock;

            this.epl    = epl;

            this.secure = secure;

            this.key    = key;

            var networkstream = new NetworkStream(sock, false);

            if (secure)
            {
                var sslstream = new System.Net.Security.SslStream(networkstream);

                sslstream.AuthenticateAsServer(cert);

                stream  = sslstream;
            }
            else
            {
                stream = networkstream;
            }

            timer = new Timer(OnTimeout, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);

            if (buffer == null)
            {
                buffer = new byte[BufferSize];
            }

            Init();
        }
 /// <summary>
 /// Processes the request.
 /// </summary>
 internal void process(object objParameter)
 {
     Stream tcpStream = null;
     try
     {
         tcpStream = tcpClient.GetStream();
         if (this.secure_https)
         {
             try
             {
                 tcpStream = new System.Net.Security.SslStream(tcpStream, false, null, null);
                 ((System.Net.Security.SslStream)tcpStream).AuthenticateAsServer(ssl_certificate);
             }
             catch (Exception ex)
             {
                 SimpleHttpLogger.LogVerbose(ex);
                 return;
             }
         }
         inputStream = new BufferedStream(tcpStream);
         rawOutputStream = tcpStream;
         outputStream = new StreamWriter(rawOutputStream);
         try
         {
             parseRequest();
             readHeaders();
             RawQueryString = ParseQueryStringArguments(this.request_url.Query, preserveKeyCharacterCase: true);
             QueryString = ParseQueryStringArguments(this.request_url.Query);
             requestCookies = Cookies.FromString(GetHeaderValue("Cookie", ""));
             try
             {
                 if (http_method.Equals("GET"))
                     handleGETRequest();
                 else if (http_method.Equals("POST"))
                     handlePOSTRequest();
             }
             catch (Exception e)
             {
                 if (!isOrdinaryDisconnectException(e))
                     SimpleHttpLogger.Log(e);
                 writeFailure("500 Internal Server Error");
             }
         }
         catch (Exception e)
         {
             if (!isOrdinaryDisconnectException(e))
                 SimpleHttpLogger.LogVerbose(e);
             this.writeFailure("400 Bad Request", "The request cannot be fulfilled due to bad syntax.");
         }
         outputStream.Flush();
         rawOutputStream.Flush();
         inputStream = null; outputStream = null; rawOutputStream = null;
     }
     catch (Exception ex)
     {
         if (!isOrdinaryDisconnectException(ex))
             SimpleHttpLogger.LogVerbose(ex);
     }
     finally
     {
         try
         {
             if (tcpClient != null)
                 tcpClient.Close();
         }
         catch (Exception ex) { SimpleHttpLogger.LogVerbose(ex); }
         try
         {
             if (tcpStream != null)
                 tcpStream.Close();
         }
         catch (Exception ex) { SimpleHttpLogger.LogVerbose(ex); }
     }
 }
Exemple #53
-1
        static string SendAPNS(string deviceToken, string content)
        {
            //ref:https://msdn.microsoft.com/en-us/library/txafckwd.aspx
            //ref2:http://stackoverflow.com/questions/16101100/string-format-input-string-was-not-in-correct-format-for-string-with-curly-brack
            //要多加雙括號"{{"才能讓參數寫入string的format
            string jsonContent = String.Format("{{\"aps:\":{{\"alert\":\"{0}\",\"badge\":8,\"sound\":\"default\"}}}}",deviceToken);
            //Json: { MID = 1000242, MsgID = 12345, RegID = "c1564dd73cd73a003d2ad143d96c9e6d651f8b48b45ba8c0ae9c5db87513fde8", Subj = "測試12 主題一:88個badge", Sum = 88, Title = "test2 Content" };
            //str = "{\"aps\":{\"alert\":\"" + s2 + "\",\"badge\":10,\"sound\":\"default\"}}";
            string hostIP = "gateway.sandbox.push.apple.com";//;//"gateway.push.apple.com";//feedback.sandbox.push.apple.com//"feedback.sandbox.push.apple.com";
            int port = 2195;//2196;
            string password = "******";//AllPay

            //certificate load 需要去Apple申請App的憑證才有此檔
            string certificatepath = "allpay_apns_dev.p12";//"AllPayEPAPNS.p12" ;//"aps_production_allpay.p12";// //"allpay.p12";//bin/debug
            string certificateFullPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppleCertificate", certificatepath);

            certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(File.ReadAllBytes(certificateFullPath), password,X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            var certificates = new System.Security.Cryptography.X509Certificates.X509Certificate2Collection();
            certificates.Add(certificate);

            //使用TCP Cient來建立connect(就是走簡易的http)
            TcpClient apnsClient = new TcpClient();
            Stopwatch timer = new Stopwatch();
            try
            {
                timer.Start();
                apnsClient.Connect(hostIP, port);
            }
            catch (SocketException ex)
            {
                timer.Stop();
                Console.WriteLine("TimeSpend:{0}ms  ex:{1}", timer.ElapsedMilliseconds, ex.Message);
            }
            //主要認證憑證就是這段,可以使用event認證兩方的憑證,目前APNs這邊都只使用Apple給的憑證
            System.Net.Security.SslStream apnsStream = new System.Net.Security.SslStream(apnsClient.GetStream(),
                                                                                        false,
                                                                                        new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate),
                                                                                        new System.Net.Security.LocalCertificateSelectionCallback(SelectLocalCertificate));

            try
            {
                apnsStream.AuthenticateAsClient(hostIP, certificates, System.Security.Authentication.SslProtocols.Tls, false);
                timer.Stop();
                Console.WriteLine("做完認證的TimeSpend:{0}ms", timer.ElapsedMilliseconds);
            }
            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");
                return "";
            }
            //需要取得Apple手機給的token來當作裝置的識別碼,送的格式參考APPLE規定的JSON
            byte[] message = ToBytes(deviceToken, content);
            apnsStream.Write(message);//這邊就可以開始送資料了
            return Encoding.UTF8.GetString(message);
        }